5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2010, Roland Mas
7 * Copyright 2010-2011, Franck Villaume - Capgemini
8 * Copyright 2010-2011, Alain Peyrat - Alcatel-Lucent
9 * Copyright 2012, Franck Villaume - TrivialDev
10 * http://fusionforge.org
12 * This file is part of FusionForge. FusionForge is free software;
13 * you can redistribute it and/or modify it under the terms of the
14 * GNU General Public License as published by the Free Software
15 * Foundation; either version 2 of the Licence, or (at your option)
18 * FusionForge is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 require_once $gfcommon.'tracker/ArtifactTypes.class.php';
29 require_once $gfcommon.'tracker/ArtifactTypeFactory.class.php';
30 require_once $gfcommon.'forum/Forum.class.php';
31 require_once $gfcommon.'forum/ForumFactory.class.php';
32 require_once $gfcommon.'pm/ProjectGroup.class.php';
33 require_once $gfcommon.'pm/ProjectGroupFactory.class.php';
34 require_once $gfcommon.'include/Role.class.php';
35 require_once $gfcommon.'frs/FRSPackage.class.php';
36 require_once $gfcommon.'docman/DocumentGroup.class.php';
37 require_once $gfcommon.'docman/DocumentGroupFactory.class.php';
38 require_once $gfcommon.'mail/MailingList.class.php';
39 require_once $gfcommon.'mail/MailingListFactory.class.php';
40 require_once $gfcommon.'survey/SurveyFactory.class.php';
41 require_once $gfcommon.'survey/SurveyQuestionFactory.class.php';
42 require_once $gfcommon.'include/gettext.php';
43 require_once $gfcommon.'include/GroupJoinRequest.class.php';
48 * group_get_object() - Get the group object.
50 * group_get_object() is useful so you can pool group objects/save database queries
51 * You should always use this instead of instantiating the object directly.
53 * You can now optionally pass in a db result handle. If you do, it re-uses that query
54 * to instantiate the objects.
56 * IMPORTANT! That db result must contain all fields
57 * from groups table or you will have problems
60 * @param int Result set handle ("SELECT * FROM groups WHERE group_id=xx")
61 * @return object a group object or false on failure
63 function &group_get_object($group_id, $res = false) {
64 //create a common set of group objects
65 //saves a little wear on the database
67 //automatically checks group_type and
68 //returns appropriate object
71 if (!isset($GROUP_OBJ["_".$group_id."_"])) {
73 //the db result handle was passed in
75 $res = db_query_params('SELECT * FROM groups WHERE group_id=$1', array($group_id)) ;
77 if (!$res || db_numrows($res) < 1) {
78 $GROUP_OBJ["_".$group_id."_"]=false;
81 check group type and set up object
83 if (db_result($res,0,'type_id') == 1) {
85 $GROUP_OBJ["_".$group_id."_"] = new Group($group_id, $res);
88 $GROUP_OBJ["_".$group_id."_"] = false;
92 return $GROUP_OBJ["_".$group_id."_"];
95 function &group_get_objects($id_arr) {
98 // Note: if we don't do this, the result may be corrupted
102 foreach ($id_arr as $id) {
104 // See if this ID already has been fetched in the cache
106 if (!isset($GROUP_OBJ["_".$id."_"])) {
110 if (count($fetch) > 0) {
111 $res=db_query_params('SELECT * FROM groups WHERE group_id = ANY ($1)',
112 array(db_int_array_to_any_clause($fetch)));
113 while ($arr = db_fetch_array($res)) {
114 $GROUP_OBJ["_".$arr['group_id']."_"] = new Group($arr['group_id'],$arr);
117 foreach ($id_arr as $id) {
118 $return[] =& $GROUP_OBJ["_".$id."_"];
123 function &group_get_active_projects() {
124 $res = db_query_params('SELECT group_id FROM groups WHERE status=$1',
126 return group_get_objects(util_result_column_to_array($res,0));
129 function &group_get_template_projects() {
130 $res=db_query_params ('SELECT group_id FROM groups WHERE is_template=1 AND status != $1',
132 return group_get_objects (util_result_column_to_array($res,0)) ;
135 function &group_get_object_by_name($groupname) {
136 $res = db_query_params('SELECT * FROM groups WHERE unix_group_name=$1', array($groupname));
137 return group_get_object(db_result($res, 0, 'group_id'), $res);
140 function &group_get_objects_by_name($groupname_arr) {
141 $res = db_query_params('SELECT group_id FROM groups WHERE unix_group_name = ANY ($1)',
142 array(db_string_array_to_any_clause($groupname_arr)));
143 $arr =& util_result_column_to_array($res,0);
144 return group_get_objects($arr);
147 function &group_get_object_by_publicname($groupname) {
148 $res = db_query_params('SELECT * FROM groups WHERE lower(group_name) LIKE $1',
149 array(htmlspecialchars(strtolower($groupname))));
150 return group_get_object(db_result($res, 0, 'group_id'), $res);
153 class Group extends Error {
155 * Associative array of data from db.
157 * @var array $data_array.
162 * array of User objects.
164 * @var array $membersArr.
169 * Whether the use is an admin/super user of this project.
171 * @var bool $is_admin.
176 * Artifact types result handle.
178 * @var int $types_res.
183 * Associative array of data for plugins.
185 * @var array $plugins_data.
191 * Associative array of data for the group menu.
193 * @var array $menu_data.
198 * Group - Group object constructor - use group_get_object() to instantiate.
200 * @param int Required - group_id of the group you want to instantiate.
201 * @param int Database result from select query OR associative array of all columns.
202 * @return boolean success or not
204 function Group($id = false, $res = false) {
207 //setting up an empty object
208 //probably going to call create()
212 if (!$this->fetchData($id)) {
217 // Assoc array was passed in
219 if (is_array($res)) {
220 $this->data_array =& $res;
222 if (db_numrows($res) < 1) {
223 //function in class we extended
224 $this->setError(_('Group Not Found'));
225 $this->data_array=array();
228 //set up an associative array for use by other functions
229 $this->data_array = db_fetch_array_by_row($res, 0);
237 * fetchData - May need to refresh database fields if an update occurred.
239 * @param int The group_id.
240 * @return boolean success or not
242 function fetchData($group_id) {
243 $res = db_query_params ('SELECT * FROM groups WHERE group_id=$1',
245 if (!$res || db_numrows($res) < 1) {
246 $this->setError(sprintf(_('fetchData():: %s'),db_error()));
249 $this->data_array = db_fetch_array($res);
254 * create - Create new group.
256 * This method should be called on empty Group object.
257 * It will add an entry for a pending group/project (status 'P')
259 * @param object The User object.
260 * @param string The full name of the user.
261 * @param string The Unix name of the user.
262 * @param string The new group description.
263 * @param string The purpose of the group.
264 * @param boolean Whether to send an email or not
265 * @param int The id of the project this new project is based on
266 * @return boolean success or not
268 function create(&$user, $group_name, $unix_name, $description, $purpose, $unix_box = 'shell1',
269 $scm_box = 'cvs1', $is_public = 1, $send_mail = true, $built_from_template = 0) {
270 // $user is ignored - anyone can create pending group
273 if ($this->getID()!=0) {
274 $this->setError(_('Group::create: Group object already exists'));
276 } else if (!$this->validateGroupName($group_name)) {
278 } else if (!account_groupnamevalid($unix_name)) {
279 $this->setError(_('Invalid Unix name'));
281 } else if (!$SYS->sysUseUnixName($unix_name)) {
282 $this->setError(_('Unix name already taken'));
284 } else if (db_numrows(db_query_params('SELECT group_id FROM groups WHERE unix_group_name=$1',
285 array($unix_name))) > 0) {
286 $this->setError(_('Unix name already taken'));
288 } else if (strlen($purpose)<10) {
289 $this->setError(_('Please describe your Registration Purpose in a more comprehensive manner'));
291 } else if (strlen($purpose)>1500) {
292 $this->setError(_('The Registration Purpose text is too long. Please make it smaller than 1500 bytes.'));
294 } else if (strlen($description)<10) {
295 $this->setError(_('Describe in a more comprehensive manner your project.'));
299 // Check if sys_use_project_vhost for homepage
300 if (forge_get_config('use_project_vhost')) {
301 $homepage = $unix_name.".".forge_get_config('web_host');
303 $homepage = forge_get_config('web_host')."/www/".$unix_name."/";
308 $res = db_query_params('
323 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)',
324 array (htmlspecialchars ($group_name),
326 htmlspecialchars($description),
327 $unix_name.".".forge_get_config('web_host'),
332 htmlspecialchars($purpose),
334 md5(util_randbytes()),
335 $built_from_template));
336 if (!$res || db_affected_rows($res) < 1) {
337 $this->setError(sprintf(_('ERROR: Could not create group: %s'),db_error()));
342 $id = db_insertid($res, 'groups', 'group_id');
344 $this->setError(sprintf(_('ERROR: Could not get group id: %s'),db_error()));
349 if (!$this->fetchData($id)) {
354 $gjr = new GroupJoinRequest($this);
355 $gjr->create($user->getID(),
356 'Fake GroupJoinRequest to store the creator of a project',
359 $hook_params = array();
360 $hook_params['group'] = $this;
361 $hook_params['group_id'] = $this->getID();
362 $hook_params['group_name'] = $group_name;
363 $hook_params['unix_group_name'] = $unix_name;
364 plugin_hook("group_create", $hook_params);
368 $this->sendNewProjectNotificationEmail();
376 * updateAdmin - Update core properties of group object.
378 * This function require site admin privilege.
380 * @param object User requesting operation (for access control).
381 * @param boolean Whether group is publicly accessible (0/1).
382 * @param int Group type (1-project, 2-foundry).
383 * @param string Machine on which group's home directory located.
384 * @param string Domain which serves group's WWW.
388 function updateAdmin(&$user, $is_public, $type_id, $unix_box, $http_domain) {
389 $perm =& $this->getPermission();
391 if (!$perm || !is_object($perm)) {
392 $this->setError(_('Could not get permission.'));
396 if (!$perm->isSuperUser()) {
397 $this->setError(_('Permission denied.'));
403 $res = db_query_params('
405 SET type_id=$1, unix_box=$2, http_domain=$3
412 if (!$res || db_affected_rows($res) < 1) {
413 $this->setError(_('ERROR: DB: Could not change group properties: %s'),db_error());
418 // Log the audit trail
419 if ($type_id != $this->data_array['type_id']) {
420 $this->addHistory('type_id', $this->data_array['type_id']);
422 if ($unix_box != $this->data_array['unix_box']) {
423 $this->addHistory('unix_box', $this->data_array['unix_box']);
425 if ($http_domain != $this->data_array['http_domain']) {
426 $this->addHistory('http_domain', $this->data_array['http_domain']);
429 if (!$this->fetchData($this->getID())) {
438 * update - Update number of common properties.
440 * Unlike updateAdmin(), this function accessible to project admin.
442 * @param object User requesting operation (for access control).
443 * @param boolean Whether group is publicly accessible (0/1).
444 * @param string Project's license (string ident).
445 * @param int Group type (1-project, 2-foundry).
446 * @param string Machine on which group's home directory located.
447 * @param string Domain which serves group's WWW.
448 * @return int status.
451 function update(&$user, $group_name, $homepage, $short_description, $use_mail, $use_survey, $use_forum,
452 $use_pm, $use_pm_depend_box, $use_scm, $use_news, $use_docman,
453 $new_doc_address, $send_all_docs, $logo_image_id,
454 $use_ftp, $use_tracker, $use_frs, $use_stats, $tags, $is_public) {
456 $perm =& $this->getPermission();
458 if (!$perm || !is_object($perm)) {
459 $this->setError(_('Could not get permission.'));
463 if (!$perm->isAdmin()) {
464 $this->setError(_('Permission denied.'));
468 // Validate some values
469 if ($this->getPublicName() != $group_name) {
470 if (!$this->validateGroupName($group_name)) {
475 if ($new_doc_address) {
476 $invalid_mails = validate_emails($new_doc_address);
477 if (count($invalid_mails) > 0) {
478 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
483 // in the database, these all default to '1',
484 // so we have to explicity set 0
497 if (!$use_pm_depend_box) {
498 $use_pm_depend_box = 0;
521 if (!$send_all_docs) {
525 $homepage = ltrim($homepage);
527 $homepage = util_make_url('/projects/' . $this->getUnixName() . '/');
530 if (strlen(htmlspecialchars($short_description))>255) {
531 $this->setError(_('Error updating project information: Maximum length for Project Description is 255 chars.'));
537 //XXX not yet actived logo_image_id='$logo_image_id',
538 $res = db_query_params('UPDATE groups
541 short_description=$3,
546 use_pm_depend_box=$8,
556 array(htmlspecialchars($group_name),
558 htmlspecialchars($short_description),
575 $this->setError(sprintf(_('Error updating project information: %s'), db_error()));
580 if (!$this->setUseDocman($use_docman)) {
581 $this->setError(sprintf(_('Error updating project information: use_docman %s'), db_error()));
586 if ($this->setTags($tags) === false) {
591 $hook_params = array();
592 $hook_params['group'] = $this;
593 $hook_params['group_id'] = $this->getID();
594 $hook_params['group_homepage'] = $homepage;
595 $hook_params['group_name'] = htmlspecialchars($group_name);
596 $hook_params['group_description'] = htmlspecialchars($short_description);
597 $hook_params['group_ispublic'] = $is_public;
598 if (!plugin_hook("group_update", $hook_params)) {
599 if (!$this->isError()) {
600 $this->setError(_('Error updating project information in plugin_hook group_update'));
606 // Log the audit trail
607 $this->addHistory('Changed Public Info', '');
609 if (!$this->fetchData($this->getID())) {
618 * getID - Simply return the group_id for this object.
620 * @return int group_id.
623 return $this->data_array['group_id'];
627 * getType() - Foundry, project, etc.
629 * @return int The type flag from the database.
632 return $this->data_array['type_id'];
637 * getStatus - the status code.
639 * Statuses char include I,H,A,D,P.
640 * TODO : document what these mean :
647 function getStatus() {
648 return $this->data_array['status'];
652 * setStatus - set the status code.
654 * Statuses include I,H,A,D,P.
655 * TODO : document what these mean :
662 * @param object User requesting operation (for access control).
663 * @param string Status value.
664 * @return boolean success.
667 function setStatus(&$user, $status) {
670 if (!forge_check_global_perm('approve_projects')) {
671 $this->setPermissionDeniedError();
675 // Projects in 'A' status can only go to 'H' or 'D'
676 // Projects in 'D' status can only go to 'A'
677 // Projects in 'P' status can only go to 'A' OR 'D'
678 // Projects in 'I' status can only go to 'P'
679 // Projects in 'H' status can only go to 'A' OR 'D'
680 $allowed_status_changes = array(
681 'AH'=>1,'AD'=>1,'DA'=>1,'PA'=>1,'PD'=>1,
682 'IP'=>1,'HA'=>1,'HD'=>1
685 // Check that status transition is valid
686 if ($this->getStatus() != $status
687 && !array_key_exists($this->getStatus(). $status, $allowed_status_changes)) {
688 $this->setError(_('Invalid Status Change From: ').$this->getStatus(). _(' To: '.$status));
694 $res = db_query_params('UPDATE groups
696 WHERE group_id=$2', array($status, $this->getID()));
698 if (!$res || db_affected_rows($res) < 1) {
699 $this->setError(sprintf(_('ERROR: DB: Could not change group status: %s'),db_error()));
705 // Activate system group, if not yet
706 if (!$SYS->sysCheckGroup($this->getID())) {
707 if (!$SYS->sysCreateGroup($this->getID())) {
708 $this->setError($SYS->getErrorMessage());
713 if (!$this->activateUsers()) {
718 /* Otherwise, the group is not active, and make sure that
719 System group is not active either */
720 } else if ($SYS->sysCheckGroup($this->getID())) {
721 if (!$SYS->sysRemoveGroup($this->getID())) {
722 $this->setError($SYS->getErrorMessage());
728 $hook_params = array();
729 $hook_params['group'] = $this;
730 $hook_params['group_id'] = $this->getID();
731 $hook_params['status'] = $status;
732 plugin_hook("group_setstatus", $hook_params);
736 // Log the audit trail
737 if ($status != $this->getStatus()) {
738 $this->addHistory('Status', $this->getStatus());
741 $this->data_array['status'] = $status;
746 * isProject - Simple boolean test to see if it's a project or not.
748 * @return boolean is_project.
750 function isProject() {
751 if ($this->getType()==1) {
759 * isPublic - Wrapper around RBAC to check if a project is anonymously readable
761 * @return boolean is_public.
763 function isPublic() {
764 $ra = RoleAnonymous::getInstance() ;
765 return $ra->hasPermission('project_read', $this->getID());
769 * isActive - Database field status of 'A' returns true.
771 * @return boolean is_active.
773 function isActive() {
774 if ($this->getStatus()=='A') {
782 * isTemplate - Simply returns the is_template flag from the database.
784 * @return boolean is_template.
786 function isTemplate() {
787 return $this->data_array['is_template'];
791 * setAsTemplate - Set the template status of a project
793 * @param boolean is_template.
795 function setAsTemplate($booleanparam) {
797 $booleanparam = $booleanparam ? 1 : 0;
798 $res = db_query_params('UPDATE groups SET is_template=$1 WHERE group_id=$2',
799 array($booleanparam, $this->getID()));
801 $this->data_array['is_template']=$booleanparam;
811 * getTemplateProject - Return the project template this project is built from
813 * @return object The template project
815 function getTemplateProject() {
816 return group_get_object($this->data_array['built_from_template']);
820 * getUnixName - the unix_name
822 * @return string unix_name.
824 function getUnixName() {
825 return strtolower($this->data_array['unix_group_name']);
829 * getPublicName - the full-length public name.
831 * @return string The group_name.
833 function getPublicName() {
834 return $this->data_array['group_name'];
838 * getRegisterPurpose - the text description of the purpose of this project.
840 * @return string The description.
842 function getRegisterPurpose() {
843 return $this->data_array['register_purpose'];
847 * getDescription - the text description of this project.
849 * @return string The description.
851 function getDescription() {
852 return $this->data_array['short_description'];
856 * getStartDate - the unix time this project was registered.
858 * @return int (unix time) of registration.
860 function getStartDate() {
861 return $this->data_array['register_time'];
865 * getLogoImageID - the id of the logo in the database for this project.
867 * @return int The ID of logo image in db_images table (or 100 if none).
869 function getLogoImageID() {
870 return $this->data_array['logo_image_id'];
874 * getUnixBox - the hostname of the unix box where this project is located.
876 * @return string The name of the unix machine for the group.
878 function getUnixBox() {
879 return $this->data_array['unix_box'];
883 * getSCMBox - the hostname of the scm box where this project is located.
885 * @return string The name of the unix machine for the group.
887 function getSCMBox() {
888 return $this->data_array['scm_box'];
891 * setSCMBox - the hostname of the scm box where this project is located.
893 * @param string The name of the new SCM_BOX
895 function setSCMBox($scm_box) {
897 if ($scm_box == $this->data_array['scm_box']) {
902 $res = db_query_params('UPDATE groups SET scm_box=$1 WHERE group_id=$2', array($scm_box, $this->getID ()));
904 $this->addHistory('scm_box', $this->data_array['scm_box']);
905 $this->data_array['scm_box'] = $scm_box;
910 $this->setError(_("Couldn't insert SCM_BOX to database"));
914 $this->setError(_("SCM Box can't be empty"));
920 * getDomain - the hostname.domain where their web page is located.
922 * @return string The name of the group [web] domain.
924 function getDomain() {
925 return $this->data_array['http_domain'];
929 * getRegistrationPurpose - the text description of the purpose of this project.
931 * @return string The application for project hosting.
933 function getRegistrationPurpose() {
934 return $this->data_array['register_purpose'];
939 * getAdmins() - Get array of Admin user objects.
941 * @return array Array of User objects.
943 function &getAdmins() {
944 $roles = RBACEngine::getInstance()->getRolesByAllowedAction ('project_admin', $this->getID());
948 foreach ($roles as $role) {
949 if (! ($role instanceof RoleExplicit)) {
952 if ($role->getHomeProject() == NULL
953 || $role->getHomeProject()->getID() != $this->getID()) {
957 foreach ($role->getUsers() as $u) {
958 $user_ids[] = $u->getID();
961 return user_get_objects(array_unique($user_ids));
965 Common Group preferences for tools
969 * enableAnonSCM - whether or not this group has opted to enable Anonymous SCM.
971 * @return boolean enable_scm.
973 function enableAnonSCM() {
974 $r = RoleAnonymous::getInstance();
975 return $r->hasPermission('scm', $this->getID(), 'read');
978 function SetUsesAnonSCM($booleanparam) {
980 $booleanparam = $booleanparam ? 1 : 0;
981 $r = RoleAnonymous::getInstance();
982 $r->setSetting('scm', $this->getID(), $booleanparam);
987 * enablePserver - whether or not this group has opted to enable Pserver.
989 * @return boolean enable_pserver.
991 function enablePserver() {
992 if ($this->usesSCM()) {
993 return $this->data_array['enable_pserver'];
999 function SetUsesPserver($booleanparam) {
1001 $booleanparam = $booleanparam ? 1 : 0;
1002 $res = db_query_params('UPDATE groups SET enable_pserver=$1 WHERE group_id=$2',
1003 array($booleanparam, $this->getID()));
1005 $this->data_array['enable_pserver'] = $booleanparam;
1014 * usesSCM - whether or not this group has opted to use SCM.
1016 * @return boolean uses_scm.
1018 function usesSCM() {
1019 if (forge_get_config('use_scm')) {
1020 return $this->data_array['use_scm'];
1027 * setUseSCM - Set the SCM usage
1029 * @param boolean enabled/disabled
1031 function setUseSCM($booleanparam) {
1033 $booleanparam = $booleanparam ? 1 : 0 ;
1034 $res = db_query_params('UPDATE groups SET use_scm=$1 WHERE group_id=$2',
1035 array($booleanparam, $this->getID()));
1037 $this->data_array['use_scm']=$booleanparam;
1047 * usesMail - whether or not this group has opted to use mailing lists.
1049 * @return boolean uses_mail.
1051 function usesMail() {
1052 if (forge_get_config('use_mail')) {
1053 return $this->data_array['use_mail'];
1060 * setUseMail - Set the mailing-list usage
1062 * @param boolean enabled/disabled
1064 function setUseMail($booleanparam) {
1066 $booleanparam = $booleanparam ? 1 : 0 ;
1067 $res = db_query_params('UPDATE groups SET use_mail=$1 WHERE group_id=$2',
1068 array($booleanparam, $this->getID()));
1070 $this->data_array['use_mail']=$booleanparam;
1080 * usesNews - whether or not this group has opted to use news.
1082 * @return boolean uses_news.
1084 function usesNews() {
1085 if (forge_get_config('use_news')) {
1086 return $this->data_array['use_news'];
1093 * usesForum - whether or not this group has opted to use discussion forums.
1095 * @return boolean uses_forum.
1097 function usesForum() {
1098 if (forge_get_config('use_forum')) {
1099 return $this->data_array['use_forum'];
1106 * setUseForum - Set the forum usage
1108 * @param boolean enabled/disabled
1110 function setUseForum($booleanparam) {
1112 $booleanparam = $booleanparam ? 1 : 0;
1113 $res = db_query_params('UPDATE groups SET use_forum=$1 WHERE group_id=$2',
1114 array($booleanparam, $this->getID()));
1116 $this->data_array['use_forum']=$booleanparam;
1126 * usesStats - whether or not this group has opted to use stats.
1128 * @return boolean uses_stats.
1130 function usesStats() {
1131 return $this->data_array['use_stats'];
1135 * usesFRS - whether or not this group has opted to use file release system.
1137 * @return boolean uses_frs.
1139 function usesFRS() {
1140 if (forge_get_config('use_frs')) {
1141 return $this->data_array['use_frs'];
1148 * setUseFRS - Set the FRS usage
1150 * @param boolean enabled/disabled
1152 function setUseFRS($booleanparam) {
1154 $booleanparam = $booleanparam ? 1 : 0;
1155 $res = db_query_params('UPDATE groups SET use_frs=$1 WHERE group_id=$2',
1156 array ($booleanparam, $this->getID()));
1158 $this->data_array['use_frs']=$booleanparam;
1168 * usesTracker - whether or not this group has opted to use tracker.
1170 * @return boolean uses_tracker.
1172 function usesTracker() {
1173 if (forge_get_config('use_tracker')) {
1174 return $this->data_array['use_tracker'];
1181 * setUseTracker - Set the tracker usage
1183 * @param boolean enabled/disabled
1185 function setUseTracker ($booleanparam) {
1187 $booleanparam = $booleanparam ? 1 : 0 ;
1188 $res = db_query_params ('UPDATE groups SET use_tracker=$1 WHERE group_id=$2',
1189 array ($booleanparam, $this->getID()));
1191 $this->data_array['use_tracker']=$booleanparam;
1201 * useCreateOnline - whether or not this group has opted to use create online documents option.
1203 * @return boolean use_docman_create_online.
1205 function useCreateOnline() {
1206 if (forge_get_config('use_docman')) {
1207 return $this->data_array['use_docman_create_online'];
1214 * usesDocman - whether or not this group has opted to use docman.
1216 * @return boolean use_docman.
1218 function usesDocman() {
1219 if (forge_get_config('use_docman')) {
1220 return $this->data_array['use_docman'];
1227 * setUseDocman - Set the docman usage
1229 * @param boolean enabled/disabled
1231 function setUseDocman($booleanparam) {
1233 $booleanparam = $booleanparam ? 1 : 0;
1234 $res = db_query_params('UPDATE groups SET use_docman = $1 WHERE group_id = $2',
1235 array($booleanparam, $this->getID()));
1237 // check if / doc_group exists, if not create it
1238 $trashdir = db_query_params('select groupname from doc_groups where groupname = $1 and group_id = $2',
1239 array('.trash', $this->getID()));
1240 if ($trashdir && db_numrows($trashdir) == 0) {
1241 $resinsert = db_query_params('insert into doc_groups (groupname, group_id, stateid) values ($1, $2, $3)',
1242 array('.trash', $this->getID(), '2'));
1248 $this->data_array['use_docman'] = $booleanparam;
1258 * useDocmanSearch - whether or not this group has opted to use docman search engine.
1260 * @return boolean use_docman_search.
1262 function useDocmanSearch() {
1263 if (forge_get_config('use_docman')) {
1264 return $this->data_array['use_docman_search'];
1271 * useWebdav - whether or not this group has opted to use webdav interface.
1273 * @return boolean use_docman_search.
1275 function useWebdav() {
1276 if (forge_get_config('use_webdav')) {
1277 return $this->data_array['use_webdav'];
1284 * usesFTP - whether or not this group has opted to use FTP.
1286 * @return boolean uses_ftp.
1288 function usesFTP() {
1289 if (forge_get_config('use_ftp')) {
1290 return $this->data_array['use_ftp'];
1297 * usesSurvey - whether or not this group has opted to use surveys.
1299 * @return boolean uses_survey.
1301 function usesSurvey() {
1302 if (forge_get_config('use_survey')) {
1303 return $this->data_array['use_survey'];
1310 * usesPM - whether or not this group has opted to Project Manager.
1312 * @return boolean uses_projman.
1315 if (forge_get_config('use_pm')) {
1316 return $this->data_array['use_pm'];
1323 * setUsePM - Set the PM usage
1325 * @param boolean enabled/disabled
1327 function setUsePM($booleanparam) {
1329 $booleanparam = $booleanparam ? 1 : 0;
1330 $res = db_query_params('UPDATE groups SET use_pm=$1 WHERE group_id=$2',
1331 array($booleanparam, $this->getID()));
1333 $this->data_array['use_pm']=$booleanparam;
1343 * getPlugins - get a list of all available group plugins
1345 * @return array array containing plugin_id => plugin_name
1347 function getPlugins() {
1348 if (!isset($this->plugins_data)) {
1349 $this->plugins_data = array();
1350 $res = db_query_params('SELECT group_plugin.plugin_id, plugins.plugin_name
1351 FROM group_plugin, plugins
1352 WHERE group_plugin.group_id=$1
1353 AND group_plugin.plugin_id=plugins.plugin_id', array($this->getID()));
1354 $rows = db_numrows($res);
1356 for ($i=0; $i<$rows; $i++) {
1357 $plugin_id = db_result($res, $i, 'plugin_id');
1358 $this->plugins_data[$plugin_id] = db_result($res, $i, 'plugin_name');
1361 return $this->plugins_data;
1365 * usesPlugin - returns true if the group uses a particular plugin
1367 * @param string name of the plugin
1368 * @return boolean whether plugin is being used or not
1370 function usesPlugin($pluginname) {
1371 $plugins_data = $this->getPlugins();
1372 foreach ($plugins_data as $p_id => $p_name) {
1373 if ($p_name == $pluginname) {
1381 * added for Codendi compatibility
1382 * usesServices - returns true if the group uses a particular plugin or feature
1384 * @param string name of the plugin
1385 * @return boolean whether plugin is being used or not
1387 function usesService($feature) {
1388 $plugins_data = $this->getPlugins();
1389 $pm = plugin_manager_get_object();
1390 foreach ($plugins_data as $p_id => $p_name) {
1391 if ($p_name == $feature) {
1394 if ($pm->getPluginByName($p_name)->provide($feature)) {
1402 * setPluginUse - enables/disables plugins for the group
1404 * @param string name of the plugin
1405 * @param boolean the new state
1406 * @return string database result
1408 function setPluginUse($pluginname, $val=true) {
1409 if ($val == $this->usesPlugin($pluginname)) {
1410 // State is already good, returning
1413 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1414 array($pluginname));
1415 $rows = db_numrows($res);
1417 // Error: no plugin by that name
1420 $plugin_id = db_result($res,0,'plugin_id');
1422 unset($this->plugins_data);
1424 $res = db_query_params('INSERT INTO group_plugin (group_id, plugin_id) VALUES ($1, $2)',
1425 array($this->getID(),
1429 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1 AND plugin_id=$2',
1430 array($this->getID(),
1434 $this->normalizeAllRoles () ;
1438 * getDocEmailAddress - get email address(es) to send doc notifications to.
1440 * @return string email address.
1442 function getDocEmailAddress() {
1443 return $this->data_array['new_doc_address'];
1447 * DocEmailAll - whether or not this group has opted to use receive notices on all doc updates.
1449 * @return boolean email_on_all_doc_updates.
1451 function docEmailAll() {
1452 return $this->data_array['send_all_docs'];
1457 * getHomePage - The URL for this project's home page.
1459 * @return string homepage URL.
1461 function getHomePage() {
1462 return $this->data_array['homepage'];
1466 * getTags - Tags of this project.
1468 * @return string List of tags. Comma separated
1470 function getTags() {
1471 $sql = 'SELECT name FROM project_tags WHERE group_id = $1';
1472 $res = db_query_params($sql, array($this->getID()));
1473 return join(', ', util_result_column_to_array($res));
1477 * setTags - Set tags of this project.
1479 * @return string database result.
1481 function setTags($tags) {
1483 $sql = 'DELETE FROM project_tags WHERE group_id=$1';
1484 $res = db_query_params($sql, array($this->getID()));
1486 $this->setError('Deleting old tags: '.db_error());
1490 $inserted = array();
1491 $tags_array = preg_split('/[;,]/', $tags);
1492 foreach ($tags_array as $tag) {
1493 $tag = preg_replace('/[\t\r\n]/', ' ', $tag);
1494 // Allowed caracteres: [A-Z][a-z][0-9] -_&'#+.
1495 if (preg_match('/[^[:alnum:]| |\-|_|\&|\'|#|\+|\.]/', $tag)) {
1496 $this->setError(_('Bad tag name, you only can use the following characters: [A-Z][a-z][0-9]-_&\'#+. and space'));
1501 if ($tag == '' || array_search($tag, $inserted) !== false) continue;
1502 $sql = 'INSERT INTO project_tags (group_id,name) VALUES ($1, $2)';
1503 $res = db_query_params($sql, array($this->getID(), $tag));
1505 $this->setError(_('Setting tags:') . ' ' .
1517 * getPermission - Return a Permission for this Group
1519 * @return object The Permission.
1521 function &getPermission() {
1522 return permission_get_object($this);
1526 function delete($sure, $really_sure, $really_really_sure) {
1527 if (!$sure || !$really_sure || !$really_really_sure) {
1528 $this->setMissingParamsError(_('Please tick all checkboxes.'));
1531 if ($this->getID() == forge_get_config('news_group') ||
1532 $this->getID() == 1 ||
1533 $this->getID() == forge_get_config('stats_group') ||
1534 $this->getID() == forge_get_config('peer_rating_group')) {
1535 $this->setError(_('Cannot Delete System Group'));
1538 $perm = $this->getPermission();
1539 if (!$perm || !is_object($perm)) {
1540 $this->setPermissionDeniedError();
1542 } elseif ($perm->isError()) {
1543 $this->setPermissionDeniedError();
1545 } elseif (!$perm->isSuperUser()) {
1546 $this->setPermissionDeniedError();
1552 // Remove all the members
1554 $members = $this->getMembers();
1555 foreach ($members as $i) {
1556 if(!$this->removeUser($i->getID())) {
1557 $this->setError(_('Could not properly remove member:').' '.$i->getID());
1562 // unlink roles from this project
1563 $ra = RoleAnonymous::getInstance();
1564 $rl = RoleLoggedIn::getInstance();
1565 $ra->unlinkProject($this);
1566 $rl->unlinkProject($this);
1567 // @todo : unlink all the other roles created in the project...
1572 $atf = new ArtifactTypeFactory($this);
1573 $at_arr = $atf->getArtifactTypes();
1574 foreach ($at_arr as $i) {
1575 if (!is_object($i)) {
1578 if (!$i->delete(1,1)) {
1579 $this->setError(_('Could not properly delete the tracker:').' '.$i->getErrorMessage());
1586 $ff = new ForumFactory($this);
1587 $f_arr = $ff->getForums();
1588 foreach ($f_arr as $i) {
1589 if (!is_object($i)) {
1592 if(!$i->delete(1,1)) {
1593 $this->setError(_('Could not properly delete the forum:').' '.$i->getErrorMessage());
1598 // Delete Subprojects
1600 $pgf = new ProjectGroupFactory($this);
1601 $pg_arr = $pgf->getProjectGroups();
1602 foreach ($pg_arr as $i) {
1603 if (!is_object($i)) {
1606 if (!$i->delete(1,1)) {
1607 $this->setError(_('Could not properly delete the ProjectGroup:').' '.$i->getErrorMessage());
1612 // Delete FRS Packages
1614 $res = db_query_params('SELECT * FROM frs_package WHERE group_id=$1',
1615 array($this->getID()));
1617 $this->setError(_('Error FRS Packages: ').db_error());
1622 while ($arr = db_fetch_array($res)) {
1623 $frsp=new FRSPackage($this, $arr['package_id'], $arr);
1624 if (!$frsp->delete(1, 1)) {
1625 $this->setError(_('Could not properly delete the FRSPackage:').' '.$frsp->getErrorMessage());
1632 $news_group=group_get_object(forge_get_config('news_group'));
1633 $res = db_query_params('SELECT forum_id FROM news_bytes WHERE group_id=$1',
1634 array($this->getID()));
1636 $this->setError(_('Error Deleting News: ').db_error());
1641 for ($i=0; $i<db_numrows($res); $i++) {
1642 $Forum = new Forum($news_group,db_result($res,$i,'forum_id'));
1643 if (!$Forum->delete(1,1)) {
1644 $this->setError(_("Could Not Delete News Forum: %d"),$Forum->getID());
1648 $res = db_query_params('DELETE FROM news_bytes WHERE group_id=$1',
1649 array($this->getID()));
1651 $this->setError(_('Error Deleting News: ').db_error());
1659 $res = db_query_params('DELETE FROM doc_data WHERE group_id=$1',
1660 array($this->getID()));
1662 $this->setError(_('Error Deleting Documents: ').db_error());
1667 $res = db_query_params('DELETE FROM doc_groups WHERE group_id=$1',
1668 array($this->getID()));
1670 $this->setError(_('Error Deleting Documents: ').db_error());
1678 $res=db_query_params('DELETE FROM project_tags WHERE group_id=$1', array($this->getID()));
1680 $this->setError(_('Error Deleting Tags: ').db_error());
1686 // Delete group history
1688 $res = db_query_params('DELETE FROM group_history WHERE group_id=$1',
1689 array($this->getID()));
1691 $this->setError(_('Error Deleting Project History: ').db_error());
1697 // Delete group plugins
1699 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1',
1700 array($this->getID()));
1702 $this->setError(_('Error Deleting Project Plugins: ').db_error());
1708 // Delete group cvs stats
1710 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE group_id=$1',
1711 array ($this->getID())) ;
1713 $this->setError(_('Error Deleting SCM Statistics: ').db_error());
1721 $sf = new SurveyFactory($this);
1722 $s_arr =& $sf->getSurveys();
1723 foreach ($s_arr as $i) {
1724 if (!is_object($i)) {
1727 if (!$i->delete()) {
1728 $this->setError(_('Could not properly delete the survey'));
1734 // Delete SurveyQuestions
1736 $sqf = new SurveyQuestionFactory($this);
1737 $sq_arr =& $sqf->getSurveyQuestions();
1738 foreach ($sq_arr as $i) {
1739 if (!is_object($i)) {
1742 if (!$i->delete()) {
1743 $this->setError(_('Could not properly delete the survey questions'));
1749 // Delete Mailing List Factory
1751 $mlf = new MailingListFactory($this);
1752 $ml_arr = $mlf->getMailingLists();
1753 foreach ($ml_arr as $i) {
1754 if (!is_object($i)) {
1757 if (!$i->delete(1,1)) {
1758 $this->setError(_('Could not properly delete the mailing list'));
1766 $res = db_query_params('DELETE FROM trove_group_link WHERE group_id=$1',
1767 array($this->getID()));
1769 $this->setError(_('Error Deleting Trove: ').db_error());
1774 $res = db_query_params('DELETE FROM trove_agg WHERE group_id=$1',
1775 array($this->getID()));
1777 $this->setError(_('Error Deleting Trove: ').db_error());
1785 $res = db_query_params('DELETE FROM project_sums_agg WHERE group_id=$1',
1786 array($this->getID()));
1788 $this->setError(_('Error Deleting Counters: ').db_error());
1793 $res = db_query_params('INSERT INTO deleted_groups (unix_group_name, delete_date, isdeleted) VALUES ($1, $2, $3)',
1794 array($this->getUnixName(),
1798 $this->setError(_('Error Deleting Project:').' '.db_error());
1803 // Delete entry in groups.
1804 $res = db_query_params('DELETE FROM groups WHERE group_id=$1',
1805 array($this->getID()));
1807 $this->setError(_('Error Deleting Project:').' '.db_error());
1814 $hook_params = array();
1815 $hook_params['group'] = $this;
1816 $hook_params['group_id'] = $this->getID();
1817 plugin_hook("group_delete", $hook_params);
1819 if (forge_get_config('upload_dir') != '' && $this->getUnixName()) {
1820 exec('/bin/rm -rf '.forge_get_config('upload_dir').'/'.$this->getUnixName().'/');
1822 if (forge_get_config('ftp_upload_dir') != '' && $this->getUnixName()) {
1823 exec('/bin/rm -rf '.forge_get_config('ftp_upload_dir').'/'.$this->getUnixName().'/');
1828 $res = db_query_params('DELETE FROM rep_group_act_monthly WHERE group_id=$1',
1829 array ($this->getID()));
1830 //echo 'rep_group_act_monthly'.db_error();
1831 $res = db_query_params('DELETE FROM rep_group_act_weekly WHERE group_id=$1',
1832 array ($this->getID()));
1833 //echo 'rep_group_act_weekly'.db_error();
1834 $res = db_query_params('DELETE FROM rep_group_act_daily WHERE group_id=$1',
1835 array ($this->getID()));
1836 //echo 'rep_group_act_daily'.db_error();
1837 unset($this->data_array);
1842 Basic functions to add/remove users to/from a group
1843 and update their permissions
1847 * addUser - controls adding a user to a group.
1849 * @param string Unix name of the user to add OR integer user_id.
1850 * @param int The role_id this user should have.
1851 * @return boolean success.
1854 function addUser($user_identifier,$role_id) {
1857 Admins can add users to groups
1860 if (!forge_check_perm ('project_admin', $this->getID())) {
1861 $this->setPermissionDeniedError();
1867 get user id for this user's unix_name
1869 if (is_int ($user_identifier)) { // user_id or user_name
1870 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_id=$1', array ($user_identifier)) ;
1872 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_name=$1', array ($user_identifier)) ;
1874 if (db_numrows($res_newuser) > 0) {
1876 // make sure user is active
1878 if (db_result($res_newuser,0,'status') != 'A') {
1879 $this->setError(_('User is not active. Only active users can be added.'));
1885 // user was found - set new user_id var
1887 $user_id = db_result($res_newuser,0,'user_id');
1889 $role = new Role($this, $role_id);
1890 if (!$role || !is_object($role)) {
1891 $this->setError(_('Error Getting Role Object'));
1894 } elseif ($role->isError()) {
1895 $this->setError('addUser::roleget::'.$role->getErrorMessage());
1900 $role->addUser(user_get_object($user_id)) ;
1901 if (!$SYS->sysCheckCreateGroup($this->getID())){
1902 $this->setError($SYS->getErrorMessage());
1906 if (!$SYS->sysCheckCreateUser($user_id)) {
1907 $this->setError($SYS->getErrorMessage());
1911 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
1912 $this->setError($SYS->getErrorMessage());
1918 // user doesn't exist
1920 $this->setError(_('ERROR: User does not exist'));
1925 $hook_params['group'] = $this;
1926 $hook_params['group_id'] = $this->getID();
1927 $hook_params['user'] = user_get_object($user_id);
1928 $hook_params['user_id'] = $user_id;
1929 plugin_hook ("group_adduser", $hook_params);
1934 $this->addHistory('Added User',$user_identifier);
1940 * removeUser - controls removing a user from a group.
1942 * Users can remove themselves.
1944 * @param int The ID of the user to remove.
1945 * @return boolean success.
1947 function removeUser($user_id) {
1950 if ($user_id != user_getid()
1951 && !forge_check_perm('project_admin', $this->getID())) {
1952 $this->setPermissionDeniedError();
1958 $user = user_get_object($user_id);
1959 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
1961 foreach ($roles as $role) {
1962 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
1963 $found_role = $role;
1967 if ($found_role == NULL) {
1968 $this->setError(sprintf(_('ERROR: User not removed: %s')));
1972 $found_role->removeUser($user);
1973 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
1974 $this->setError($SYS->getErrorMessage());
1980 // reassign open artifacts to id=100
1982 $res = db_query_params('UPDATE artifact SET assigned_to=100
1983 WHERE group_artifact_id
1984 IN (SELECT group_artifact_id
1985 FROM artifact_group_list
1986 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
1987 array($this->getID(),
1990 $this->setError(_('ERROR: DB: artifact:').' '.db_error());
1996 // reassign open tasks to id=100
1997 // first have to purge any assignments that would cause
1998 // conflict with existing assignment to 100
2000 $res = db_query_params('DELETE FROM project_assigned_to
2001 WHERE project_task_id IN (SELECT pt.project_task_id
2002 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2003 WHERE pt.group_project_id = pgl.group_project_id
2004 AND pat.project_task_id=pt.project_task_id
2005 AND pt.status_id=1 AND pgl.group_id=$1
2006 AND pat.assigned_to_id=$2)
2007 AND assigned_to_id=100',
2008 array($this->getID(),
2011 $this->setError(sprintf(_('ERROR: DB: project_assigned_to %d: %s'), 1, db_error()));
2015 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2016 WHERE project_task_id IN (SELECT pt.project_task_id
2017 FROM project_task pt, project_group_list pgl
2018 WHERE pt.group_project_id = pgl.group_project_id
2019 AND pt.status_id=1 AND pgl.group_id=$1)
2020 AND assigned_to_id=$2',
2021 array($this->getID(),
2024 $this->setError(sprintf(_('ERROR: DB: project_assigned_to %d: %s'), 2, db_error()));
2030 // Remove user from system
2032 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2033 $this->setError($SYS->getErrorMessage());
2038 $hook_params['group'] = $this;
2039 $hook_params['group_id'] = $this->getID();
2040 $hook_params['user'] = user_get_object($user_id);
2041 $hook_params['user_id'] = $user_id;
2042 plugin_hook ("group_removeuser", $hook_params);
2045 $this->addHistory('Removed User',$user_id);
2052 * updateUser - controls updating a user's role in this group.
2054 * @param int The ID of the user.
2055 * @param int The role_id to set this user to.
2056 * @return boolean success.
2058 function updateUser($user_id,$role_id) {
2060 if (!forge_check_perm ('project_admin', $this->getID())) {
2061 $this->setPermissionDeniedError();
2065 $newrole = RBACEngine::getInstance()->getRoleById ($role_id) ;
2066 if (!$newrole || !is_object($newrole)) {
2067 $this->setError(_('Could Not Get Role'));
2069 } elseif ($newrole->isError()) {
2070 $this->setError(sprintf(_('Role: %s'),$role->getErrorMessage()));
2072 } elseif ($newrole->getHomeProject() == NULL
2073 || $newrole->getHomeProject()->getID() != $this->getID()) {
2074 $this->setError(_('Wrong destination role'));
2077 $user = user_get_object ($user_id) ;
2078 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user) ;
2079 $found_role = NULL ;
2080 foreach ($roles as $role) {
2081 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2082 $found_role = $role ;
2086 if ($found_role == NULL) {
2087 $this->setError(sprintf(_('ERROR: User not removed: %s')));
2091 $found_role->removeUser ($user) ;
2092 $newrole->addUser ($user) ;
2094 $this->addHistory('Updated User',$user_id);
2099 * addHistory - Makes an audit trail entry for this project.
2101 * @param string The name of the field.
2102 * @param string The Old Value for this $field_name.
2103 * @return database result handle.
2106 function addHistory($field_name, $old_value) {
2107 return db_query_params ('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2108 VALUES ($1,$2,$3,$4,$5)',
2109 array ($this->getID(),
2117 * activateUsers - Make sure that group members have unix accounts.
2119 * Setup unix accounts for group members. Can be called even
2120 * if members are already active.
2124 function activateUsers() {
2126 Activate member(s) of the project
2129 $members = $this->getUsers (true) ;
2131 foreach ($members as $member) {
2133 foreach (RBACEngine::getInstance()->getAvailableRolesForUser ($member) as $role) {
2134 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2137 if (!$this->addUser($member->getUnixName(),$role->getID())) {
2148 * getMembers - returns array of User objects for this project
2150 * @return array of User objects for this group.
2152 function getMembers() {
2153 return $this->getUsers (true) ;
2157 * replaceTemplateStrings - fill-in some blanks with project name
2159 * @param string Template string
2160 * @return string String after replacements
2162 function replaceTemplateStrings($string) {
2163 $string = str_replace ('UNIXNAME', $this->getUnixName(), $string) ;
2164 $string = str_replace ('PUBLICNAME', $this->getPublicName(), $string) ;
2165 $string = str_replace ('DESCRIPTION', $this->getDescription(), $string) ;
2170 * approve - Approve pending project.
2172 * @param object The User object who is doing the updating.
2175 function approve(&$user) {
2176 global $gfcommon,$gfwww;
2177 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2179 if ($this->getStatus()=='A') {
2180 $this->setError(_("Group already active"));
2186 // Step 1: Activate group and create LDAP entries
2187 if (!$this->setStatus($user, 'A')) {
2192 // Switch to system language for item creation
2193 setup_gettext_from_sys_lang();
2195 // Create default roles
2196 $idadmin_group = NULL;
2197 foreach (get_group_join_requests ($this) as $gjr) {
2198 $idadmin_group = $gjr->getUserID();
2201 if ($idadmin_group == NULL) {
2202 $idadmin_group = $user->getID();
2205 $template = $this->getTemplateProject();
2206 $id_mappings = array();
2207 $seen_admin_role = false;
2209 // Copy roles from template project
2210 foreach($template->getRoles() as $oldrole) {
2211 if ($oldrole->getHomeProject() != NULL) {
2212 $role = new Role($this);
2214 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2215 $role->create('TEMPORARY ROLE NAME', $data, true);
2216 $role->setName($oldrole->getName());
2217 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2218 $seen_admin_role = true;
2222 $role->linkProject($this);
2224 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2225 // Reuse the project_admin permission
2226 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID())) ;
2230 if (!$seen_admin_role) {
2231 $role = new Role($this);
2232 $adminperms = array ('project_admin' => array ($this->getID() => 1)) ;
2233 $role_id = $role->create ('Admin', $adminperms, true) ;
2236 $roles = $this->getRoles() ;
2237 foreach ($roles as $r) {
2238 if ($r->getHomeProject() == NULL) {
2241 if ($r->getSetting ('project_admin', $this->getID())) {
2242 $r->addUser(user_get_object ($idadmin_group));
2246 // Temporarily switch to the submitter's identity
2247 $saved_session = session_get_user();
2248 session_set_internal($idadmin_group);
2251 if (forge_get_config('use_tracker')) {
2252 $this->setUseTracker ($template->usesTracker());
2253 if ($template->usesTracker()) {
2254 $oldatf = new ArtifactTypeFactory($template);
2255 foreach ($oldatf->getArtifactTypes() as $o) {
2256 $t = new ArtifactType ($this) ;
2257 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions()) ;
2258 $id_mappings['tracker'][$o->getID()] = $t->getID();
2259 $t->cloneFieldsFrom ($o->getID());
2264 if (forge_get_config('use_pm')) {
2265 $this->setUsePM ($template->usesPM());
2266 if ($template->usesPM()) {
2267 $oldpgf = new ProjectGroupFactory($template);
2268 foreach ($oldpgf->getProjectGroups() as $o) {
2269 $pg = new ProjectGroup($this);
2270 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2271 $id_mappings['pm'][$o->getID()] = $pg->getID();
2276 if (forge_get_config('use_forum')) {
2277 $this->setUseForum($template->usesForum()) ;
2278 if ($template->usesForum()) {
2279 $oldff = new ForumFactory($template) ;
2280 foreach ($oldff->getForums() as $o) {
2281 $f = new Forum($this);
2282 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),0,$o->getSendAllPostsTo(),1,0,0);
2283 $id_mappings['forum'][$o->getID()] = $f->getID();
2288 if (forge_get_config('use_docman')) {
2289 $this->setUseDocman($template->usesDocman());
2290 if ($template->usesDocman()) {
2291 $olddgf = new DocumentGroupFactory($template);
2292 // First pass: create all docgroups
2293 $id_mappings['docman_docgroup'][0] = 0;
2294 foreach ($olddgf->getDocumentGroups() as $o) {
2295 $ndgf = new DocumentGroup($this);
2296 // .trash is a reserved directory
2297 if ($o->getName() != '.trash' && $o->getParentID() == 0) {
2298 $ndgf->create($this->replaceTemplateStrings($o->getName()));
2299 $id_mappings['docman_docgroup'][$o->getID()] = $ndgf->getID();
2302 // Second pass: restore hierarchy links
2303 foreach ($olddgf->getDocumentGroups() as $o) {
2304 $ndgf = new DocumentGroup($this);
2305 if ($o->getName() != '.trash' && $o->getParentID() == 0) {
2306 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2307 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()]);
2313 if (forge_get_config('use_frs')) {
2314 $this->setUseFRS ($template->usesFRS());
2315 if ($template->usesFRS()) {
2316 foreach (get_frs_packages($template) as $o) {
2317 $newp = new FRSPackage($this);
2318 $nname = $this->replaceTemplateStrings($o->getName());
2319 $newp->create ($nname, $o->isPublic());
2324 if (forge_get_config('use_mail')) {
2325 $this->setUseMail($template->usesMail()) ;
2326 if ($template->usesMail()) {
2327 $oldmlf = new MailingListFactory($template);
2328 foreach ($oldmlf->getMailingLists() as $o) {
2329 $ml = new MailingList($this);
2330 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName()) ;
2332 $ndescription = $this->replaceTemplateStrings($o->getDescription()) ;
2333 $ml->create($nname, $ndescription, $o->isPublic());
2339 /* use SCM plugin from template group */
2340 $this->setUseSCM($template->usesSCM());
2342 foreach ($template->getPlugins() as
2343 $plugin_id => $plugin_name) {
2344 $this->setPluginUse($plugin_name);
2347 /* use SCM choice from registration page */
2349 foreach ($template->getPlugins() as
2350 $plugin_id => $plugin_name) {
2351 if (substr($plugin_name, 3) == 'scm' &&
2352 $plugin_name != 'scmhook') {
2353 /* skip copying scm plugins */
2356 /* enable other plugins though */
2357 $this->setPluginUse($plugin_name);
2361 foreach ($template->getRoles() as $oldrole) {
2362 $newrole = RBACEngine::getInstance()->getRoleById ($id_mappings['role'][$oldrole->getID()]) ;
2363 if ($oldrole->getHomeProject() != NULL
2364 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2365 $newrole->setPublic ($oldrole->isPublic()) ;
2367 $oldsettings = $oldrole->getSettingsForProject ($template) ;
2369 $sections = array ('project_read', 'project_admin', 'frs', 'scm', 'docman', 'tracker_admin', 'new_tracker', 'forum_admin', 'new_forum', 'pm_admin', 'new_pm') ;
2370 foreach ($sections as $section) {
2371 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]) ;
2374 $sections = array ('tracker', 'pm', 'forum') ;
2375 foreach ($sections as $section) {
2376 if (isset ($oldsettings[$section])) {
2377 foreach ($oldsettings[$section] as $k => $v) {
2378 // Only copy perms for tools that have been copied
2379 if (isset ($id_mappings[$section][$k])) {
2380 $newrole->setSetting ($section,
2381 $id_mappings[$section][$k],
2389 $lm = new WidgetLayoutManager();
2390 $lm->createDefaultLayoutForProject ($this->getID(), $template->getID()) ;
2392 $params = array () ;
2393 $params['template'] = $template ;
2394 $params['project'] = $this ;
2395 $params['id_mappings'] = $id_mappings ;
2396 plugin_hook_by_reference ('clone_project_from_template', $params) ;
2398 // Disable everything
2399 db_query_params ('UPDATE groups SET use_mail=0, use_survey=0, use_forum=0, use_pm=0, use_pm_depend_box=0, use_scm=0, use_news=0, use_docman=0, use_ftp=0, use_tracker=0, use_frs=0, use_stats=0 WHERE group_id=$1',
2400 array ($this->getID())) ;
2403 $this->normalizeAllRoles();
2404 $this->activateUsers();
2406 // Delete fake join request
2407 foreach (get_group_join_requests ($this) as $gjr) {
2408 $gjr->delete(true) ;
2411 // Switch back to user preference
2412 session_set_internal($saved_session->getID());
2413 setup_gettext_from_context();
2417 $this->sendApprovalEmail();
2418 $this->addHistory('Approved', 'x');
2421 // Plugin can make approve operation there
2423 $params[0] = $idadmin_group;
2424 $params[1] = $this->getID();
2425 plugin_hook('group_approved', $params);
2433 * sendApprovalEmail - Send new project email.
2435 * @return boolean success.
2438 function sendApprovalEmail() {
2439 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID()) ;
2441 if (count($admins) < 1) {
2442 $this->setError(_("Group does not have any administrators."));
2446 // send one email per admin
2447 foreach ($admins as $admin) {
2448 setup_gettext_for_user ($admin) ;
2450 $message=sprintf(_('Your project registration for %4$s has been approved.
2452 Project Full Name: %1$s
2453 Project Unix Name: %2$s
2455 Your DNS will take up to a day to become active on our site.
2456 Your web site is accessible through your shell account. Please read
2457 site documentation (see link below) about intended usage, available
2458 services, and directory layout of the account.
2461 own project page in %4$s while logged in, you will find
2462 additional menu functions to your left labeled \'Project Admin\'.
2464 We highly suggest that you now visit %4$s and create a public
2465 description for your project. This can be done by visiting your project
2466 page while logged in, and selecting \'Project Admin\' from the menus
2467 on the left (or by visiting %3$s
2470 Your project will also not appear in the Trove Software Map (primary
2471 list of projects hosted on %4$s which offers great flexibility in
2472 browsing and search) until you categorize it in the project administration
2473 screens. So that people can find your project, you should do this now.
2474 Visit your project while logged in, and select \'Project Admin\' from the
2477 Enjoy the system, and please tell others about %4$s. Let us know
2478 if there is anything we can do to help you.
2481 htmlspecialchars_decode($this->getPublicName()),
2482 $this->getUnixName(),
2483 util_make_url ('/project/admin/?group_id='.$this->getID()),
2484 forge_get_config ('forge_name'));
2486 util_send_message($admin->getEmail(), sprintf(_('%1$s Project Approved'), forge_get_config ('forge_name')), $message);
2488 setup_gettext_from_context();
2496 * sendRejectionEmail - Send project rejection email.
2498 * This function sends out a rejection message to a user who
2499 * registered a project.
2501 * @param int The id of the response to use.
2502 * @param string The rejection message.
2503 * @return boolean completion status.
2506 function sendRejectionEmail($response_id, $message="zxcv") {
2507 $submitters = array () ;
2508 foreach (get_group_join_requests ($this) as $gjr) {
2509 $submitters[] = user_get_object($gjr->getUserID());
2512 if (count ($submitters) < 1) {
2513 $this->setError(_("Group does not have any administrators."));
2517 foreach ($submitters as $admin) {
2518 setup_gettext_for_user($admin);
2520 $response=sprintf(_('Your project registration for %3$s has been denied.
2522 Project Full Name: %1$s
2523 Project Unix Name: %2$s
2525 Reasons for negative decision:
2527 '), $this->getPublicName(), $this->getUnixName(), forge_get_config('forge_name'));
2529 // Check to see if they want to send a custom rejection response
2530 if ($response_id == 0) {
2531 $response .= $message;
2533 $response .= db_result(
2534 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array ($response_id)),
2539 util_send_message($admin->getEmail(), sprintf(_('%1$s Project Denied'), forge_get_config ('forge_name')), $response);
2540 setup_gettext_from_context();
2547 * sendNewProjectNotificationEmail - Send new project notification email.
2549 * This function sends out a notification email to the
2550 * SourceForge admin user when a new project is
2553 * @return boolean success.
2556 function sendNewProjectNotificationEmail() {
2557 // Get the user who wants to register the project
2558 $submitters = array();
2559 foreach (get_group_join_requests ($this) as $gjr) {
2560 $submitters[] = user_get_object($gjr->getUserID());
2562 if (count ($submitters) < 1) {
2563 $this->setError(_("Could not find user who has submitted the project."));
2567 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('approve_projects', -1) ;
2569 if (count($admins) < 1) {
2570 $this->setError(_("There is no administrator to send the mail to."));
2574 foreach ($admins as $admin) {
2575 $admin_email = $admin->getEmail () ;
2576 setup_gettext_for_user ($admin) ;
2578 $message = sprintf(_('New %1$s Project Submitted
2580 Project Full Name: %2$s
2581 Submitted Description: %3$s
2583 forge_get_config ('forge_name'),
2584 htmlspecialchars_decode($this->getPublicName()),
2585 htmlspecialchars_decode($this->getRegistrationPurpose()));
2587 foreach ($submitters as $submitter) {
2588 $message .= sprintf(_('Submitter: %1$s (%2$s)
2590 $submitter->getRealName(),
2591 $submitter->getUnixName());
2594 $message .= sprintf (_('
2595 Please visit the following URL to approve or reject this project:
2597 util_make_url ('/admin/approve-pending.php')) ;
2598 util_send_message($admin_email, sprintf(_('New %1$s Project Submitted'), forge_get_config ('forge_name')), $message);
2599 setup_gettext_from_context();
2603 $email = $submitter->getEmail() ;
2604 setup_gettext_for_user ($submitter) ;
2606 $message=sprintf(_('New %1$s Project Submitted
2608 Project Full Name: %2$s
2609 Submitted Description: %3$s
2611 The %1$s admin team will now examine your project submission. You will be notified of their decision.'), forge_get_config ('forge_name'), $this->getPublicName(), util_unconvert_htmlspecialchars($this->getRegistrationPurpose()), forge_get_config('web_host'));
2613 util_send_message($email, sprintf(_('New %1$s Project Submitted'), forge_get_config ('forge_name')), $message);
2614 setup_gettext_from_context();
2623 * validateGroupName - Validate the group name
2625 * @param string Group name.
2627 * @return boolean an error false and set an error is the group name is invalide otherwise return true
2629 function validateGroupName($group_name) {
2630 if (strlen($group_name)<3) {
2631 $this->setError(_('Group name is too short'));
2633 } else if (strlen(htmlspecialchars($group_name))>50) {
2634 $this->setError(_('Group name is too long'));
2636 } else if (group_get_object_by_publicname($group_name)) {
2637 $this->setError(_('Group name already taken'));
2645 * getRolesId - Get Ids of the roles of the group.
2647 * @return array Role ids of this group.
2649 function getRolesId() {
2650 $role_ids = array();
2652 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2653 array($this->getID()));
2654 while ($arr = db_fetch_array($res)) {
2655 $role_ids[] = $arr['role_id'];
2657 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2658 array($this->getID()));
2659 while ($arr = db_fetch_array($res)) {
2660 $role_ids[] = $arr['role_id'];
2663 return array_unique($role_ids);
2667 * getRoles - Get the roles of the group.
2669 * @return array Roles of this group.
2671 function getRoles() {
2674 $roles = $this->getRolesId();
2675 $engine = RBACEngine::getInstance();
2676 foreach ($roles as $role_id) {
2677 $result[] = $engine->getRoleById ($role_id);
2683 function normalizeAllRoles() {
2684 $roles = $this->getRoles();
2686 foreach ($roles as $r) {
2687 $r->normalizeData();
2692 * getUnixStatus - Status of activation of unix account.
2694 * @return char (N)one, (A)ctive, (S)uspended or (D)eleted
2696 function getUnixStatus() {
2697 return $this->data_array['unix_status'];
2701 * setUnixStatus - Sets status of activation of unix account.
2703 * @param string The unix status.
2709 * @return boolean success.
2711 function setUnixStatus($status) {
2714 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
2719 $this->setError(sprintf(_('ERROR - Could Not Update Group Unix Status: %s'),db_error()));
2723 if ($status == 'A') {
2724 if (!$SYS->sysCheckCreateGroup($this->getID())) {
2725 $this->setError($SYS->getErrorMessage());
2730 if ($SYS->sysCheckGroup($this->getID())) {
2731 if (!$SYS->sysRemoveGroup($this->getID())) {
2732 $this->setError($SYS->getErrorMessage());
2739 $this->data_array['unix_status']=$status;
2746 * getUsers - Get the users of a group
2748 * @return array of user's objects.
2750 function getUsers($onlylocal = true) {
2751 if (!isset($this->membersArr)) {
2752 $this->membersArr = array () ;
2755 foreach ($this->getRoles() as $role) {
2757 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
2760 foreach ($role->getUsers() as $user) {
2761 $ids[] = $user->getID() ;
2764 $ids = array_unique ($ids) ;
2765 foreach ($ids as $id) {
2766 $u = user_get_object ($id) ;
2767 if ($u->isActive()) {
2768 $this->membersArr[] = $u ;
2772 return $this->membersArr;
2775 function setDocmanCreateOnlineStatus($status) {
2777 /* if we activate search engine, we probably want to reindex */
2778 $res = db_query_params('UPDATE groups SET use_docman_create_online=$1 WHERE group_id=$2',
2779 array($status, $this->getID()));
2782 $this->setError(sprintf(_('ERROR - Could Not Update Group DocmanCreateOnline Status: %s'),db_error()));
2786 $this->data_array['use_docman_create_online']=$status;
2792 function setDocmanWebdav($status) {
2794 /* if we activate search engine, we probably want to reindex */
2795 $res = db_query_params('UPDATE groups SET use_webdav=$1 WHERE group_id=$2',
2800 $this->setError(sprintf(_('ERROR - Could Not Update Group UseWebdab Status: %s'),db_error()));
2804 $this->data_array['use_webdav']=$status;
2810 function setDocmanSearchStatus($status) {
2812 /* if we activate search engine, we probably want to reindex */
2813 $res = db_query_params('UPDATE groups SET use_docman_search=$1, force_docman_reindex=$1 WHERE group_id=$2',
2818 $this->setError(sprintf(_('ERROR - Could Not Update Group UseDocmanSearch Status: %s'),db_error()));
2822 $this->data_array['use_docman_search']=$status;
2828 function setDocmanForceReindexSearch($status) {
2830 /* if we activate search engine, we probably want to reindex */
2831 $res = db_query_params('UPDATE groups SET force_docman_reindex=$1 WHERE group_id=$2',
2836 $this->setError(sprintf(_('ERROR - Could Not Update Group force_docman_reindex %s'),db_error()));
2840 $this->data_array['force_docman_reindex']=$status;
2849 * group_getname() - get the group name
2851 * @param int The group ID
2855 function group_getname ($group_id = 0) {
2856 $grp = group_get_object($group_id);
2858 return $grp->getPublicName();
2865 * group_getunixname() - get the unixname for a group
2867 * @param int The group ID
2871 function group_getunixname ($group_id) {
2872 $grp = group_get_object($group_id);
2874 return $grp->getUnixName();
2881 * group_get_result() - Get the group object result ID.
2883 * @param int The group ID
2887 function &group_get_result($group_id=0) {
2888 $grp = group_get_object($group_id);
2890 return $grp->getData();
2896 function getAllProjectTags($onlyvisible = true) {
2897 $res = db_query_params('SELECT project_tags.name, groups.group_id FROM groups, project_tags WHERE groups.group_id = project_tags.group_id AND groups.status = $1 ORDER BY project_tags.name, groups.group_id',
2900 if (!$res || db_numrows($res) == 0) {
2906 while ($arr = db_fetch_array($res)) {
2908 $group_id = $arr[1];
2909 if (!isset($result[$tag])) {
2910 $result[$tag] = array();
2913 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
2914 $p = group_get_object($group_id);
2915 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
2916 'group_id' => $group_id);
2924 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
2927 class ProjectComparator {
2928 var $criterion = 'name' ;
2930 function Compare ($a, $b) {
2931 switch ($this->criterion) {
2934 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName()) ;
2935 if ($namecmp != 0) {
2938 /* If several projects share a same public name */
2939 return strcoll ($a->getUnixName(), $b->getUnixName()) ;
2942 return strcmp ($a->getUnixName(), $b->getUnixName()) ;
2945 $aid = $a->getID() ;
2946 $bid = $b->getID() ;
2950 return ($a < $b) ? -1 : 1;
2956 function sortProjectList (&$list, $criterion='name') {
2957 $cmp = new ProjectComparator () ;
2958 $cmp->criterion = $criterion ;
2960 return usort ($list, array ($cmp, 'Compare')) ;
2965 // c-file-style: "bsd"