5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2013, Roland Mas
7 * Copyright 2010-2011, Franck Villaume - Capgemini
8 * Copyright 2010-2012, Alain Peyrat - Alcatel-Lucent
9 * Copyright 2012-2013, Franck Villaume - TrivialDev
10 * Copyright 2013, French Ministry of National Education
11 * http://fusionforge.org
13 * This file is part of FusionForge. FusionForge is free software;
14 * you can redistribute it and/or modify it under the terms of the
15 * GNU General Public License as published by the Free Software
16 * Foundation; either version 2 of the Licence, or (at your option)
19 * FusionForge is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License along
25 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
26 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 require_once $gfcommon.'tracker/ArtifactTypes.class.php';
30 require_once $gfcommon.'tracker/ArtifactTypeFactory.class.php';
31 require_once $gfcommon.'forum/Forum.class.php';
32 require_once $gfcommon.'forum/ForumFactory.class.php';
33 require_once $gfcommon.'pm/ProjectGroup.class.php';
34 require_once $gfcommon.'pm/ProjectGroupFactory.class.php';
35 require_once $gfcommon.'include/Role.class.php';
36 require_once $gfcommon.'frs/FRSPackage.class.php';
37 require_once $gfcommon.'docman/DocumentGroup.class.php';
38 require_once $gfcommon.'docman/DocumentGroupFactory.class.php';
39 require_once $gfcommon.'mail/MailingList.class.php';
40 require_once $gfcommon.'mail/MailingListFactory.class.php';
41 require_once $gfcommon.'survey/SurveyFactory.class.php';
42 require_once $gfcommon.'survey/SurveyQuestionFactory.class.php';
43 require_once $gfcommon.'include/gettext.php';
44 require_once $gfcommon.'include/GroupJoinRequest.class.php';
49 * group_get_object() - Get the group object.
51 * group_get_object() is useful so you can pool group objects/save database queries
52 * You should always use this instead of instantiating the object directly.
54 * You can now optionally pass in a db result handle. If you do, it re-uses that query
55 * to instantiate the objects.
57 * IMPORTANT! That db result must contain all fields
58 * from groups table or you will have problems
60 * @param int $group_id Required
61 * @param int|bool $res Result set handle ("SELECT * FROM groups WHERE group_id=xx")
62 * @return Group|bool A group object or false on failure
64 function &group_get_object($group_id, $res = false) {
65 //create a common set of group objects
66 //saves a little wear on the database
68 //automatically checks group_type and
69 //returns appropriate object
72 if (!isset($GROUP_OBJ["_".$group_id."_"])) {
74 //the db result handle was passed in
76 $res = db_query_params('SELECT * FROM groups WHERE group_id=$1', array($group_id));
78 if (!$res || db_numrows($res) < 1) {
79 $GROUP_OBJ["_".$group_id."_"]=false;
82 check group type and set up object
84 if (db_result($res,0,'type_id') == 1) {
86 $GROUP_OBJ["_".$group_id."_"] = new Group($group_id, $res);
89 $GROUP_OBJ["_".$group_id."_"] = false;
93 return $GROUP_OBJ["_".$group_id."_"];
96 function &group_get_objects($id_arr) {
99 // Note: if we don't do this, the result may be corrupted
103 foreach ($id_arr as $id) {
105 // See if this ID already has been fetched in the cache
107 if (!isset($GROUP_OBJ["_".$id."_"])) {
111 if (count($fetch) > 0) {
112 $res=db_query_params('SELECT * FROM groups WHERE group_id = ANY ($1)',
113 array(db_int_array_to_any_clause($fetch)));
114 while ($arr = db_fetch_array($res)) {
115 $GROUP_OBJ["_".$arr['group_id']."_"] = new Group($arr['group_id'],$arr);
118 foreach ($id_arr as $id) {
119 $return[] =& $GROUP_OBJ["_".$id."_"];
124 function &group_get_active_projects() {
125 $res = db_query_params('SELECT group_id FROM groups WHERE status=$1',
127 return group_get_objects(util_result_column_to_array($res,0));
130 function &group_get_all_projects() {
131 $res = db_query_params ('SELECT group_id FROM groups',
133 return group_get_objects(util_result_column_to_array($res,0));
136 function &group_get_template_projects() {
137 $res = db_query_params('SELECT group_id FROM groups WHERE is_template=1 AND status != $1',
139 return group_get_objects(util_result_column_to_array($res,0));
142 function &group_get_object_by_name($groupname) {
143 $res = db_query_params('SELECT * FROM groups WHERE unix_group_name=$1', array($groupname));
144 return group_get_object(db_result($res, 0, 'group_id'), $res);
147 function &group_get_objects_by_name($groupname_arr) {
148 $res = db_query_params('SELECT group_id FROM groups WHERE unix_group_name = ANY ($1)',
149 array(db_string_array_to_any_clause($groupname_arr)));
150 $arr =& util_result_column_to_array($res,0);
151 return group_get_objects($arr);
154 function group_get_object_by_publicname($groupname) {
155 $res = db_query_params('SELECT * FROM groups WHERE lower(group_name) LIKE $1',
156 array(htmlspecialchars(strtolower($groupname))));
157 return group_get_object(db_result($res, 0, 'group_id'), $res);
161 * get_public_active_projects_asc() - Get a list of rows for public active projects (initially in trove/full_list)
163 * @param int Opional Maximum number of rows to limit query length
165 function get_public_active_projects_asc($max_query_limit = -1) {
167 $res_grp = db_query_params ('
168 SELECT group_id, group_name, unix_group_name, short_description, register_time
170 WHERE status = $1 AND type_id=1 AND is_template=0 AND register_time > 0
171 ORDER BY group_name ASC
176 while ($row_grp = db_fetch_array($res_grp)) {
177 if (!forge_check_perm ('project_read', $row_grp['group_id'])) {
180 $projects[] = $row_grp;
186 class Group extends Error {
188 * Associative array of data from db.
190 * @var array $data_array.
195 * array of User objects.
197 * @var array $membersArr.
202 * Whether the use is an admin/super user of this project.
204 * @var bool $is_admin.
209 * Artifact types result handle.
211 * @var int $types_res.
216 * Associative array of data for plugins.
218 * @var array $plugins_data.
224 * Associative array of data for the group menu.
226 * @var array $menu_data.
231 * Group - Group object constructor - use group_get_object() to instantiate.
233 * @param int|bool $id Required - Id of the group you want to instantiate.
234 * @param int|bool $res Database result from select query OR associative array of all columns.
236 function __construct($id = false, $res = false) {
239 //setting up an empty object
240 //probably going to call create()
244 if (!$this->fetchData($id)) {
249 // Assoc array was passed in
251 if (is_array($res)) {
252 $this->data_array =& $res;
254 if (db_numrows($res) < 1) {
255 //function in class we extended
256 $this->setError(_('Group Not Found'));
257 $this->data_array=array();
260 //set up an associative array for use by other functions
261 $this->data_array = db_fetch_array_by_row($res, 0);
269 * fetchData - May need to refresh database fields if an update occurred.
271 * @param int $group_id The group_id.
272 * @return boolean success or not
274 function fetchData($group_id) {
275 $res = db_query_params ('SELECT * FROM groups WHERE group_id=$1',
277 if (!$res || db_numrows($res) < 1) {
278 $this->setError(sprintf('fetchData():: %s', db_error()));
281 $this->data_array = db_fetch_array($res);
286 * create - Create new group.
288 * This method should be called on empty Group object.
289 * It will add an entry for a pending group/project (status 'P')
291 * @param object $user The User object.
292 * @param string $group_name The full name of the user.
293 * @param string $unix_name The Unix name of the user.
294 * @param string $description The new group description.
295 * @param string $purpose The purpose of the group.
296 * @param string $unix_box
297 * @param string $scm_box
298 * @param bool $is_public
299 * @param bool $send_mail Whether to send an email or not
300 * @param int $built_from_template The id of the project this new project is based on
301 * @return boolean success or not
303 function create(&$user, $group_name, $unix_name, $description, $purpose, $unix_box = 'shell1',
304 $scm_box = 'cvs1', $is_public = true, $send_mail = true, $built_from_template = 0) {
305 // $user is ignored - anyone can create pending group
308 if ($this->getID()!=0) {
309 $this->setError(_('Group object already exists'));
311 } elseif (!$this->validateGroupName($group_name)) {
313 } elseif (!account_groupnamevalid($unix_name)) {
314 $this->setError(_('Invalid Unix Name.'));
316 } elseif (!$SYS->sysUseUnixName($unix_name)) {
317 $this->setError(_('Unix name already taken'));
319 } elseif (db_numrows(db_query_params('SELECT group_id FROM groups WHERE unix_group_name=$1',
320 array($unix_name))) > 0) {
321 $this->setError(_('Unix name already taken'));
323 } elseif (strlen($purpose)<10) {
324 $this->setError(_('Please describe your Registration Purpose in a more comprehensive manner'));
326 } elseif (strlen($purpose)>1500) {
327 $this->setError(_('The Registration Purpose text is too long. Please make it smaller than 1500 bytes.'));
329 } elseif (strlen($description)<10) {
330 $this->setError(_('Describe in a more comprehensive manner your project.'));
334 // Check if sys_use_project_vhost for homepage
335 if (forge_get_config('use_project_vhost')) {
336 $homepage = $unix_name.".".forge_get_config('web_host');
338 $homepage = forge_get_config('web_host')."/www/".$unix_name."/";
343 $res = db_query_params('
358 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)',
359 array(htmlspecialchars($group_name),
361 htmlspecialchars($description),
367 htmlspecialchars($purpose),
369 md5(util_randbytes()),
370 $built_from_template));
371 if (!$res || db_affected_rows($res) < 1) {
372 $this->setError(sprintf(_('Error: Cannot create group: %s'),db_error()));
377 $id = db_insertid($res, 'groups', 'group_id');
379 $this->setError(sprintf(_('Error: Cannot get group id: %s'),db_error()));
384 if (!$this->fetchData($id)) {
389 $gjr = new GroupJoinRequest($this);
390 $gjr->create($user->getID(),
391 'Fake GroupJoinRequest to store the creator of a project',
394 $hook_params = array();
395 $hook_params['group'] = $this;
396 $hook_params['group_id'] = $this->getID();
397 $hook_params['group_name'] = $group_name;
398 $hook_params['unix_group_name'] = $unix_name;
399 plugin_hook("group_create", $hook_params);
403 $this->sendNewProjectNotificationEmail();
411 * updateAdmin - Update core properties of group object.
413 * This function require site admin privilege.
415 * @param object $user User requesting operation (for access control).
416 * @param int $type_id Group type (1-project, 2-foundry).
417 * @param string $unix_box Machine on which group's home directory located.
418 * @param string $http_domain Domain which serves group's WWW.
419 * @return bool status.
422 function updateAdmin(&$user, $type_id, $unix_box, $http_domain) {
423 $perm =& $this->getPermission();
425 if (!$perm || !is_object($perm)) {
426 $this->setError(_('Could not get permission.'));
430 if (!$perm->isSuperUser()) {
431 $this->setError(_('Permission denied.'));
437 $res = db_query_params('
439 SET type_id=$1, unix_box=$2, http_domain=$3
446 if (!$res || db_affected_rows($res) < 1) {
447 $this->setError(_('Error: Cannot change group properties: %s'),db_error());
452 // Log the audit trail
453 if ($type_id != $this->data_array['type_id']) {
454 $this->addHistory('type_id', $this->data_array['type_id']);
456 if ($unix_box != $this->data_array['unix_box']) {
457 $this->addHistory('unix_box', $this->data_array['unix_box']);
459 if ($http_domain != $this->data_array['http_domain']) {
460 $this->addHistory('http_domain', $this->data_array['http_domain']);
463 if (!$this->fetchData($this->getID())) {
472 * update - Update number of common properties.
474 * Unlike updateAdmin(), this function accessible to project admin.
476 * @param object $user User requesting operation (for access control).
477 * @param string $group_name
478 * @param string $homepage
479 * @param string $short_description
480 * @param bool $use_mail
481 * @param bool $use_survey
482 * @param bool $use_forum
483 * @param bool $use_pm
484 * @param bool $use_pm_depend_box
485 * @param bool $use_scm
486 * @param bool $use_news
487 * @param bool $use_docman
488 * @param string $new_doc_address
489 * @param bool $send_all_docs
490 * @param int $logo_image_id
491 * @param bool $use_ftp
492 * @param bool $use_tracker
493 * @param bool $use_frs
494 * @param bool $use_stats
496 * @param bool $use_activity
497 * @param bool $is_public group is publicly accessible
498 * @return int status.
501 function update(&$user, $group_name, $homepage, $short_description, $use_mail, $use_survey, $use_forum,
502 $use_pm, $use_pm_depend_box, $use_scm, $use_news, $use_docman,
503 $new_doc_address, $send_all_docs, $logo_image_id,
504 $use_ftp, $use_tracker, $use_frs, $use_stats, $tags, $use_activity, $is_public) {
506 $perm =& $this->getPermission();
508 if (!$perm || !is_object($perm)) {
509 $this->setError(_('Could not get permission.'));
513 if (!$perm->isAdmin()) {
514 $this->setError(_('Permission denied.'));
518 // Validate some values
519 if ($this->getPublicName() != $group_name) {
520 if (!$this->validateGroupName($group_name)) {
525 if ($new_doc_address) {
526 $invalid_mails = validate_emails($new_doc_address);
527 if (count($invalid_mails) > 0) {
528 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
533 // in the database, these all default to '1',
534 // so we have to explicitly set 0
547 if (!$use_pm_depend_box) {
548 $use_pm_depend_box = 0;
571 if (!$use_activity) {
574 if (!$send_all_docs) {
578 $homepage = ltrim($homepage);
580 $homepage = util_make_url('/projects/' . $this->getUnixName() . '/');
583 if (strlen(htmlspecialchars($short_description))<10) {
584 $this->setError(_('Describe in a more comprehensive manner your project.'));
590 //XXX not yet actived logo_image_id='$logo_image_id',
591 $res = db_query_params('UPDATE groups
594 short_description=$3,
599 use_pm_depend_box=$8,
610 array(htmlspecialchars($group_name),
612 htmlspecialchars($short_description),
629 if (!$res || db_affected_rows($res) < 1) {
630 $this->setError(sprintf(_('Error updating project information: %s'), db_error()));
635 if (!$this->setUseDocman($use_docman)) {
636 $this->setError(sprintf(_('Error updating project information: use_docman %s'), db_error()));
641 if ($this->setTags($tags) === false) {
646 // Log the audit trail
647 $this->addHistory('Changed Public Info', '');
649 if (!$this->fetchData($this->getID())) {
654 $hook_params = array();
655 $hook_params['group'] = $this;
656 $hook_params['group_id'] = $this->getID();
657 $hook_params['group_homepage'] = $homepage;
658 $hook_params['group_name'] = htmlspecialchars($group_name);
659 $hook_params['group_description'] = htmlspecialchars($short_description);
660 $hook_params['group_ispublic'] = $is_public;
661 if (!plugin_hook("group_update", $hook_params)) {
662 if (!$this->isError()) {
663 $this->setError(_('Error updating project information in plugin_hook group_update'));
674 * getID - Simply return the group_id for this object.
676 * @return int group_id.
679 return $this->data_array['group_id'];
683 * getType() - Foundry, project, etc.
685 * @return int The type flag from the database.
688 return $this->data_array['type_id'];
693 * getStatus - the status code.
695 * Statuses char include I,H,A,D,P.
702 function getStatus() {
703 return $this->data_array['status'];
707 * setStatus - set the status code.
709 * Statuses include I,H,A,D,P.
716 * @param object User requesting operation (for access control).
717 * @param string Status value.
718 * @return boolean success.
721 function setStatus(&$user, $status) {
724 if (!forge_check_global_perm_for_user($user, 'approve_projects')) {
725 $this->setPermissionDeniedError();
729 // Projects in 'A' status can only go to 'H' or 'D'
730 // Projects in 'D' status can only go to 'A'
731 // Projects in 'P' status can only go to 'A' OR 'D'
732 // Projects in 'I' status can only go to 'P'
733 // Projects in 'H' status can only go to 'A' OR 'D'
734 $allowed_status_changes = array(
735 'AH'=>1,'AD'=>1,'DA'=>1,'PA'=>1,'PD'=>1,
736 'IP'=>1,'HA'=>1,'HD'=>1
739 // Check that status transition is valid
740 if ($this->getStatus() != $status
741 && !array_key_exists($this->getStatus(). $status, $allowed_status_changes)) {
742 $this->setError(_('Invalid Status Change From: ').$this->getStatus(). _(' To: '.$status));
748 $res = db_query_params('UPDATE groups
750 WHERE group_id=$2', array($status, $this->getID()));
752 if (!$res || db_affected_rows($res) < 1) {
753 $this->setError(sprintf(_('Error: Cannot change group status: %s'),db_error()));
759 // Activate system group, if not yet
760 if (!$SYS->sysCheckGroup($this->getID())) {
761 if (!$SYS->sysCreateGroup($this->getID())) {
762 $this->setError($SYS->getErrorMessage());
767 if (!$this->activateUsers()) {
772 /* Otherwise, the group is not active, and make sure that
773 System group is not active either */
774 } elseif ($SYS->sysCheckGroup($this->getID())) {
775 if (!$SYS->sysRemoveGroup($this->getID())) {
776 $this->setError($SYS->getErrorMessage());
782 $hook_params = array();
783 $hook_params['group'] = $this;
784 $hook_params['group_id'] = $this->getID();
785 $hook_params['status'] = $status;
786 plugin_hook("group_setstatus", $hook_params);
790 // Log the audit trail
791 if ($status != $this->getStatus()) {
792 $this->addHistory(_('Status'), $this->getStatus());
795 $this->data_array['status'] = $status;
800 * isProject - Simple boolean test to see if it's a project or not.
802 * @return boolean is_project.
804 function isProject() {
805 if ($this->getType()==1) {
813 * isPublic - Wrapper around RBAC to check if a project is anonymously readable
815 * @return boolean is_public.
817 function isPublic() {
818 $ra = RoleAnonymous::getInstance();
819 return $ra->hasPermission('project_read', $this->getID());
823 * isActive - Database field status of 'A' returns true.
825 * @return boolean is_active.
827 function isActive() {
828 if ($this->getStatus()=='A') {
836 * isTemplate - Simply returns the is_template flag from the database.
838 * @return boolean is_template.
840 function isTemplate() {
841 return $this->data_array['is_template'];
845 * setAsTemplate - Set the template status of a project
847 * @param boolean is_template.
850 function setAsTemplate($booleanparam) {
852 $booleanparam = $booleanparam ? 1 : 0;
853 $res = db_query_params('UPDATE groups SET is_template=$1 WHERE group_id=$2',
854 array($booleanparam, $this->getID()));
856 $this->data_array['is_template']=$booleanparam;
866 * getTemplateProject - Return the project template this project is built from
868 * @return object The template project
870 function getTemplateProject() {
871 return group_get_object($this->data_array['built_from_template']);
875 * getUnixName - the unix_name
877 * @return string unix_name.
879 function getUnixName() {
880 return strtolower($this->data_array['unix_group_name']);
884 * getPublicName - the full-length public name.
886 * @return string The group_name.
888 function getPublicName() {
889 return $this->data_array['group_name'];
893 * getRegisterPurpose - the text description of the purpose of this project.
895 * @return string The description.
897 function getRegisterPurpose() {
898 return $this->data_array['register_purpose'];
902 * getDescription - the text description of this project.
904 * @return string The description.
906 function getDescription() {
907 return $this->data_array['short_description'];
911 * getStartDate - the unix time this project was registered.
913 * @return int (unix time) of registration.
915 function getStartDate() {
916 return $this->data_array['register_time'];
920 * getLogoImageID - the id of the logo in the database for this project.
922 * @return int The ID of logo image in db_images table (or 100 if none).
924 function getLogoImageID() {
925 return $this->data_array['logo_image_id'];
929 * getUnixBox - the hostname of the unix box where this project is located.
931 * @return string The name of the unix machine for the group.
933 function getUnixBox() {
934 return $this->data_array['unix_box'];
938 * getSCMBox - the hostname of the scm box where this project is located.
940 * @return string The name of the unix machine for the group.
942 function getSCMBox() {
943 return $this->data_array['scm_box'];
946 * setSCMBox - the hostname of the scm box where this project is located.
948 * @param string The name of the new SCM_BOX
951 function setSCMBox($scm_box) {
953 if ($scm_box == $this->data_array['scm_box']) {
958 $res = db_query_params('UPDATE groups SET scm_box=$1 WHERE group_id=$2', array($scm_box, $this->getID()));
960 $this->addHistory('scm_box', $this->data_array['scm_box']);
961 $this->data_array['scm_box'] = $scm_box;
966 $this->setError(_("Could not insert SCM_BOX to database"));
970 $this->setError(_("SCM Box cannot be empty"));
976 * getDomain - the hostname.domain where their web page is located.
978 * @return string The name of the group [web] domain.
980 function getDomain() {
981 return $this->data_array['http_domain'];
985 * getRegistrationPurpose - the text description of the purpose of this project.
987 * @return string The application for project hosting.
989 function getRegistrationPurpose() {
990 return $this->data_array['register_purpose'];
995 * getAdmins() - Get array of Admin user objects.
997 * @return array Array of User objects.
999 function &getAdmins() {
1000 $roles = RBACEngine::getInstance()->getRolesByAllowedAction ('project_admin', $this->getID());
1002 $user_ids = array();
1004 foreach ($roles as $role) {
1005 if (! ($role instanceof RoleExplicit)) {
1008 if ($role->getHomeProject() == NULL
1009 || $role->getHomeProject()->getID() != $this->getID()) {
1013 foreach ($role->getUsers() as $u) {
1014 $user_ids[] = $u->getID();
1017 return user_get_objects(array_unique($user_ids));
1021 Common Group preferences for tools
1025 * enableAnonSCM - whether or not this group has opted to enable Anonymous SCM.
1027 * @return boolean enable_scm.
1029 function enableAnonSCM() {
1030 $r = RoleAnonymous::getInstance();
1031 return $r->hasPermission('scm', $this->getID(), 'read');
1034 function SetUsesAnonSCM($booleanparam) {
1036 $booleanparam = $booleanparam ? 1 : 0;
1037 $r = RoleAnonymous::getInstance();
1038 $r->setSetting('scm', $this->getID(), $booleanparam);
1043 * enablePserver - whether or not this group has opted to enable Pserver.
1045 * @return boolean enable_pserver.
1047 function enablePserver() {
1048 if ($this->usesSCM()) {
1049 return $this->data_array['enable_pserver'];
1055 function SetUsesPserver($booleanparam) {
1057 $booleanparam = $booleanparam ? 1 : 0;
1058 $res = db_query_params('UPDATE groups SET enable_pserver=$1 WHERE group_id=$2',
1059 array($booleanparam, $this->getID()));
1061 $this->data_array['enable_pserver'] = $booleanparam;
1070 * usesSCM - whether or not this group has opted to use SCM.
1072 * @return boolean uses_scm.
1074 function usesSCM() {
1075 if (forge_get_config('use_scm')) {
1076 return $this->data_array['use_scm'];
1083 * setUseSCM - Set the SCM usage
1085 * @param boolean enabled/disabled
1088 function setUseSCM($booleanparam) {
1090 $booleanparam = $booleanparam ? 1 : 0;
1091 $res = db_query_params('UPDATE groups SET use_scm=$1 WHERE group_id=$2',
1092 array($booleanparam, $this->getID()));
1094 $this->data_array['use_scm']=$booleanparam;
1104 * usesMail - whether or not this group has opted to use mailing lists.
1106 * @return boolean uses_mail.
1108 function usesMail() {
1109 if (forge_get_config('use_mail')) {
1110 return $this->data_array['use_mail'];
1115 $hook_params = array();
1116 $hook_params['group'] = $this;
1117 $hook_params['group_id'] = $this->getID();
1118 $hook_params['group_homepage'] = $this->getHomePage();
1119 $hook_params['group_name'] = $this->getPublicName();
1120 $hook_params['group_description'] = $this->getDescription();
1121 plugin_hook ("group_update", $hook_params);
1125 * setUseMail - Set the mailing-list usage
1127 * @param boolean enabled/disabled
1130 function setUseMail($booleanparam) {
1132 $booleanparam = $booleanparam ? 1 : 0;
1133 $res = db_query_params('UPDATE groups SET use_mail=$1 WHERE group_id=$2',
1134 array($booleanparam, $this->getID()));
1136 $this->data_array['use_mail']=$booleanparam;
1146 * usesNews - whether or not this group has opted to use news.
1148 * @return boolean uses_news.
1150 function usesNews() {
1151 if (forge_get_config('use_news')) {
1152 return $this->data_array['use_news'];
1159 * usesActivity - whether or not this group has opted to display Project Activities.
1161 * @return boolean uses_activities.
1163 function usesActivity() {
1164 if (forge_get_config('use_activity')) {
1165 return $this->data_array['use_activity'];
1172 * usesForum - whether or not this group has opted to use discussion forums.
1174 * @return boolean uses_forum.
1176 function usesForum() {
1177 if (forge_get_config('use_forum')) {
1178 return $this->data_array['use_forum'];
1185 * setUseForum - Set the forum usage
1187 * @param boolean enabled/disabled
1190 function setUseForum($booleanparam) {
1192 $booleanparam = $booleanparam ? 1 : 0;
1193 $res = db_query_params('UPDATE groups SET use_forum=$1 WHERE group_id=$2',
1194 array($booleanparam, $this->getID()));
1196 $this->data_array['use_forum']=$booleanparam;
1206 * usesStats - whether or not this group has opted to use stats.
1208 * @return boolean uses_stats.
1210 function usesStats() {
1211 return $this->data_array['use_stats'];
1215 * usesFRS - whether or not this group has opted to use file release system.
1217 * @return boolean uses_frs.
1219 function usesFRS() {
1220 if (forge_get_config('use_frs')) {
1221 return $this->data_array['use_frs'];
1228 * setUseFRS - Set the FRS usage
1230 * @param boolean enabled/disabled
1233 function setUseFRS($booleanparam) {
1235 $booleanparam = $booleanparam ? 1 : 0;
1236 $res = db_query_params('UPDATE groups SET use_frs=$1 WHERE group_id=$2',
1237 array($booleanparam, $this->getID()));
1239 $this->data_array['use_frs']=$booleanparam;
1249 * usesTracker - whether or not this group has opted to use tracker.
1251 * @return boolean uses_tracker.
1253 function usesTracker() {
1254 if (forge_get_config('use_tracker')) {
1255 return $this->data_array['use_tracker'];
1262 * setUseTracker - Set the tracker usage
1264 * @param boolean enabled/disabled
1267 function setUseTracker ($booleanparam) {
1269 $booleanparam = $booleanparam ? 1 : 0;
1270 $res = db_query_params ('UPDATE groups SET use_tracker=$1 WHERE group_id=$2',
1271 array($booleanparam, $this->getID()));
1273 $this->data_array['use_tracker']=$booleanparam;
1283 * useCreateOnline - whether or not this group has opted to use create online documents option.
1285 * @return boolean use_docman_create_online.
1287 function useCreateOnline() {
1288 if (forge_get_config('use_docman')) {
1289 return $this->data_array['use_docman_create_online'];
1296 * usesDocman - whether or not this group has opted to use docman.
1298 * @return boolean use_docman.
1300 function usesDocman() {
1301 if (forge_get_config('use_docman')) {
1302 return $this->data_array['use_docman'];
1309 * setUseDocman - Set the docman usage
1311 * @param boolean enabled/disabled
1314 function setUseDocman($booleanparam) {
1316 $booleanparam = $booleanparam ? 1 : 0;
1317 $res = db_query_params('UPDATE groups SET use_docman = $1 WHERE group_id = $2',
1318 array($booleanparam, $this->getID()));
1320 // check if / doc_group exists, if not create it
1321 $trashdir = db_query_params('select groupname from doc_groups where groupname = $1 and group_id = $2',
1322 array('.trash', $this->getID()));
1323 if ($trashdir && db_numrows($trashdir) == 0) {
1324 $resinsert = db_query_params('insert into doc_groups (groupname, group_id, stateid) values ($1, $2, $3)',
1325 array('.trash', $this->getID(), '2'));
1331 $this->data_array['use_docman'] = $booleanparam;
1341 * useDocmanSearch - whether or not this group has opted to use docman search engine.
1343 * @return boolean use_docman_search.
1345 function useDocmanSearch() {
1346 if (forge_get_config('use_docman')) {
1347 return $this->data_array['use_docman_search'];
1354 * useWebdav - whether or not this group has opted to use webdav interface.
1356 * @return boolean use_docman_search.
1358 function useWebdav() {
1359 if (forge_get_config('use_webdav')) {
1360 return $this->data_array['use_webdav'];
1367 * usesFTP - whether or not this group has opted to use FTP.
1369 * @return boolean uses_ftp.
1371 function usesFTP() {
1372 if (forge_get_config('use_ftp')) {
1373 return $this->data_array['use_ftp'];
1380 * usesSurvey - whether or not this group has opted to use surveys.
1382 * @return boolean uses_survey.
1384 function usesSurvey() {
1385 if (forge_get_config('use_survey')) {
1386 return $this->data_array['use_survey'];
1393 * usesPM - whether or not this group has opted to Project Manager.
1395 * @return boolean uses_projman.
1398 if (forge_get_config('use_pm')) {
1399 return $this->data_array['use_pm'];
1406 * setUsePM - Set the PM usage
1408 * @param boolean enabled/disabled
1411 function setUsePM($booleanparam) {
1413 $booleanparam = $booleanparam ? 1 : 0;
1414 $res = db_query_params('UPDATE groups SET use_pm=$1 WHERE group_id=$2',
1415 array($booleanparam, $this->getID()));
1417 $this->data_array['use_pm']=$booleanparam;
1427 * getPlugins - get a list of all available group plugins
1429 * @return array array containing plugin_id => plugin_name
1431 function getPlugins() {
1432 if (!isset($this->plugins_data)) {
1433 $this->plugins_data = array();
1434 $res = db_query_params('SELECT group_plugin.plugin_id, plugins.plugin_name
1435 FROM group_plugin, plugins
1436 WHERE group_plugin.group_id=$1
1437 AND group_plugin.plugin_id=plugins.plugin_id', array($this->getID()));
1438 $rows = db_numrows($res);
1440 for ($i=0; $i<$rows; $i++) {
1441 $plugin_id = db_result($res, $i, 'plugin_id');
1442 $this->plugins_data[$plugin_id] = db_result($res, $i, 'plugin_name');
1445 return $this->plugins_data;
1449 * usesPlugin - returns true if the group uses a particular plugin
1451 * @param string $pluginname name of the plugin
1452 * @return boolean whether plugin is being used or not
1454 function usesPlugin($pluginname) {
1455 $plugins_data = $this->getPlugins();
1456 foreach ($plugins_data as $p_id => $p_name) {
1457 if ($p_name == $pluginname) {
1465 * added for Codendi compatibility
1466 * usesServices - returns true if the group uses a particular plugin or feature
1468 * @param string name of the plugin
1469 * @return boolean whether plugin is being used or not
1471 function usesService($feature) {
1472 $plugins_data = $this->getPlugins();
1473 $pm = plugin_manager_get_object();
1474 foreach ($plugins_data as $p_id => $p_name) {
1475 if ($p_name == $feature) {
1478 if ($pm->getPluginByName($p_name)->provide($feature)) {
1486 * setPluginUse - enables/disables plugins for the group
1488 * @param string name of the plugin
1489 * @param boolean the new state
1490 * @return string database result
1492 function setPluginUse($pluginname, $val=true) {
1493 if ($val == $this->usesPlugin($pluginname)) {
1494 // State is already good, returning
1497 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1498 array($pluginname));
1499 $rows = db_numrows($res);
1501 // Error: no plugin by that name
1504 $plugin_id = db_result($res,0,'plugin_id');
1506 unset($this->plugins_data);
1508 $res = db_query_params('INSERT INTO group_plugin (group_id, plugin_id) VALUES ($1, $2)',
1509 array($this->getID(),
1513 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1 AND plugin_id=$2',
1514 array($this->getID(),
1518 $this->normalizeAllRoles();
1522 * getDocEmailAddress - get email address(es) to send doc notifications to.
1524 * @return string email address.
1526 function getDocEmailAddress() {
1527 return $this->data_array['new_doc_address'];
1531 * DocEmailAll - whether or not this group has opted to use receive notices on all doc updates.
1533 * @return boolean email_on_all_doc_updates.
1535 function docEmailAll() {
1536 return $this->data_array['send_all_docs'];
1541 * getHomePage - The URL for this project's home page.
1543 * @return string homepage URL.
1545 function getHomePage() {
1546 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9+.-]*:/",
1547 $this->data_array['homepage'])) {
1548 $this->data_array['homepage'] = util_url_prefix() .
1549 $this->data_array['homepage'];
1551 return $this->data_array['homepage'];
1555 * getTags - Tags of this project.
1557 * @return string List of tags. Comma separated
1559 function getTags() {
1560 $sql = 'SELECT name FROM project_tags WHERE group_id = $1';
1561 $res = db_query_params($sql, array($this->getID()));
1562 return join(', ', util_result_column_to_array($res));
1566 * setTags - Set tags of this project.
1568 * @param string $tags
1569 * @return string database result.
1571 function setTags($tags) {
1573 $sql = 'DELETE FROM project_tags WHERE group_id=$1';
1574 $res = db_query_params($sql, array($this->getID()));
1576 $this->setError('Deleting old tags: '.db_error());
1580 $inserted = array();
1581 $tags_array = preg_split('/[;,]/', $tags);
1582 foreach ($tags_array as $tag) {
1583 $tag = preg_replace('/[\t\r\n]/', ' ', $tag);
1584 // Allowed caracteres: [A-Z][a-z][0-9] -_&'#+.
1585 if (preg_match('/[^[:alnum:]| |\-|_|\&|\'|#|\+|\.]/', $tag)) {
1586 $this->setError(_('Bad tag name, you only can use the following characters: [A-Z][a-z][0-9]-_&\'#+. and space'));
1591 if ($tag == '' || array_search($tag, $inserted) !== false) continue;
1592 $sql = 'INSERT INTO project_tags (group_id,name) VALUES ($1, $2)';
1593 $res = db_query_params($sql, array($this->getID(), $tag));
1595 $this->setError(_('Setting tags:') . ' ' .
1607 * getPermission - Return a Permission for this Group
1609 * @return object The Permission.
1611 function &getPermission() {
1612 return permission_get_object($this);
1616 function delete($sure, $really_sure, $really_really_sure) {
1617 if (!$sure || !$really_sure || !$really_really_sure) {
1618 $this->setMissingParamsError(_('Please tick all checkboxes.'));
1621 if ($this->getID() == forge_get_config('news_group') ||
1622 $this->getID() == 1 ||
1623 $this->getID() == forge_get_config('stats_group') ||
1624 $this->getID() == forge_get_config('peer_rating_group')) {
1625 $this->setError(_('Cannot Delete System Group'));
1628 $perm = $this->getPermission();
1629 if (!$perm || !is_object($perm)) {
1630 $this->setPermissionDeniedError();
1632 } elseif ($perm->isError()) {
1633 $this->setPermissionDeniedError();
1635 } elseif (!$perm->isSuperUser()) {
1636 $this->setPermissionDeniedError();
1642 // Remove all the members
1644 $members = $this->getMembers();
1645 foreach ($members as $i) {
1646 if(!$this->removeUser($i->getID())) {
1647 $this->setError(_('Could not properly remove member:').' '.$i->getID());
1652 // unlink roles from this project
1653 foreach ($this->getRoles() as $r) {
1654 if ($r->getHomeProject() == NULL
1655 || $r->getHomeProject()->getID() != $this->getID()) {
1656 $r->unlinkProject($this);
1663 if ($this->usesTracker()) {
1664 $atf = new ArtifactTypeFactory($this);
1665 $at_arr = $atf->getArtifactTypes();
1666 foreach ($at_arr as $i) {
1667 if (!is_object($i)) {
1670 if (!$i->delete(1,1)) {
1671 $this->setError(_('Could not properly delete the tracker:').' '.$i->getErrorMessage());
1680 if ($this->usesForum()) {
1681 $ff = new ForumFactory($this);
1682 $f_arr = $ff->getForums();
1683 foreach ($f_arr as $i) {
1684 if (!is_object($i)) {
1687 if(!$i->delete(1,1)) {
1688 $this->setError(_('Could not properly delete the forum:').' '.$i->getErrorMessage());
1694 // Delete Subprojects
1696 if ($this->usesPM()) {
1697 $pgf = new ProjectGroupFactory($this);
1698 $pg_arr = $pgf->getProjectGroups();
1699 foreach ($pg_arr as $i) {
1700 if (!is_object($i)) {
1703 if (!$i->delete(1,1)) {
1704 $this->setError(_('Could not properly delete the ProjectGroup:').' '.$i->getErrorMessage());
1710 // Delete FRS Packages
1712 $res = db_query_params('SELECT * FROM frs_package WHERE group_id=$1',
1713 array($this->getID()));
1715 $this->setError(_('Error FRS Packages: ').db_error());
1720 while ($arr = db_fetch_array($res)) {
1721 $frsp=new FRSPackage($this, $arr['package_id'], $arr);
1722 if (!$frsp->delete(1, 1)) {
1723 $this->setError(_('Could not properly delete the FRSPackage:').' '.$frsp->getErrorMessage());
1730 $news_group=group_get_object(forge_get_config('news_group'));
1731 $res = db_query_params('SELECT forum_id FROM news_bytes WHERE group_id=$1',
1732 array($this->getID()));
1734 $this->setError(_('Error Deleting News: ').db_error());
1739 for ($i=0; $i<db_numrows($res); $i++) {
1740 $Forum = new Forum($news_group,db_result($res,$i,'forum_id'));
1741 if (!$Forum->delete(1,1)) {
1742 $this->setError(_("Could Not Delete News Forum: %d"),$Forum->getID());
1746 $res = db_query_params('DELETE FROM news_bytes WHERE group_id=$1',
1747 array($this->getID()));
1749 $this->setError(_('Error Deleting News: ').db_error());
1757 $res = db_query_params('DELETE FROM doc_data WHERE group_id=$1',
1758 array($this->getID()));
1760 $this->setError(_('Error Deleting Documents: ').db_error());
1765 $res = db_query_params('DELETE FROM doc_groups WHERE group_id=$1',
1766 array($this->getID()));
1768 $this->setError(_('Error Deleting Documents: ').db_error());
1776 $res=db_query_params('DELETE FROM project_tags WHERE group_id=$1', array($this->getID()));
1778 $this->setError(_('Error Deleting Tags: ').db_error());
1784 // Delete group history
1786 $res = db_query_params('DELETE FROM group_history WHERE group_id=$1',
1787 array($this->getID()));
1789 $this->setError(_('Error Deleting Project History: ').db_error());
1795 // Delete group plugins
1797 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1',
1798 array($this->getID()));
1800 $this->setError(_('Error Deleting Project Plugins: ').db_error());
1806 // Delete group cvs stats
1808 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE group_id=$1',
1809 array($this->getID()));
1811 $this->setError(_('Error Deleting SCM Statistics: ').db_error());
1819 if ($this->usesSurvey()) {
1820 $sf = new SurveyFactory($this);
1821 $s_arr =& $sf->getSurveys();
1822 foreach ($s_arr as $i) {
1823 if (!is_object($i)) {
1826 if (!$i->delete()) {
1827 $this->setError(_('Could not properly delete the survey'));
1833 // Delete SurveyQuestions
1835 $sqf = new SurveyQuestionFactory($this);
1836 $sq_arr = $sqf->getSurveyQuestions();
1837 if (is_array($sq_arr)) {
1838 foreach ($sq_arr as $i) {
1839 if (!is_object($i)) {
1842 if (!$i->delete()) {
1843 $this->setError(_('Could not properly delete the survey questions'));
1851 // Delete Mailing List Factory
1853 if ($this->usesMail()) {
1854 $mlf = new MailingListFactory($this);
1855 $ml_arr = $mlf->getMailingLists();
1856 foreach ($ml_arr as $i) {
1857 if (!is_object($i)) {
1860 if (!$i->delete(1,1)) {
1861 $this->setError(_('Could not properly delete the mailing list'));
1870 $res = db_query_params('DELETE FROM trove_group_link WHERE group_id=$1',
1871 array($this->getID()));
1873 $this->setError(_('Error Deleting Trove: ').db_error());
1878 $res = db_query_params('DELETE FROM trove_agg WHERE group_id=$1',
1879 array($this->getID()));
1881 $this->setError(_('Error Deleting Trove: ').db_error());
1889 $res = db_query_params('DELETE FROM project_sums_agg WHERE group_id=$1',
1890 array($this->getID()));
1892 $this->setError(_('Error Deleting Counters: ').db_error());
1897 $res = db_query_params('INSERT INTO deleted_groups (unix_group_name, delete_date, isdeleted) VALUES ($1, $2, $3)',
1898 array($this->getUnixName(),
1902 $this->setError(_('Error Deleting Project:').' '.db_error());
1907 // Delete entry in groups.
1908 $res = db_query_params('DELETE FROM groups WHERE group_id=$1',
1909 array($this->getID()));
1911 $this->setError(_('Error Deleting Project:').' '.db_error());
1918 $hook_params = array();
1919 $hook_params['group'] = $this;
1920 $hook_params['group_id'] = $this->getID();
1921 plugin_hook("group_delete", $hook_params);
1923 if (forge_get_config('upload_dir') != '' && $this->getUnixName()) {
1924 exec('/bin/rm -rf '.forge_get_config('upload_dir').'/'.$this->getUnixName().'/');
1926 if (forge_get_config('ftp_upload_dir') != '' && $this->getUnixName()) {
1927 exec('/bin/rm -rf '.forge_get_config('ftp_upload_dir').'/'.$this->getUnixName().'/');
1932 $res = db_query_params('DELETE FROM rep_group_act_monthly WHERE group_id=$1',
1933 array($this->getID()));
1934 //echo 'rep_group_act_monthly'.db_error();
1935 $res = db_query_params('DELETE FROM rep_group_act_weekly WHERE group_id=$1',
1936 array($this->getID()));
1937 //echo 'rep_group_act_weekly'.db_error();
1938 $res = db_query_params('DELETE FROM rep_group_act_daily WHERE group_id=$1',
1939 array($this->getID()));
1940 //echo 'rep_group_act_daily'.db_error();
1941 unset($this->data_array);
1946 Basic functions to add/remove users to/from a group
1947 and update their permissions
1951 * addUser - controls adding a user to a group.
1953 * @param string Unix name of the user to add OR integer user_id.
1954 * @param int The role_id this user should have.
1955 * @return boolean success.
1958 function addUser($user_identifier,$role_id) {
1961 Admins can add users to groups
1964 if (!forge_check_perm ('project_admin', $this->getID())) {
1965 $this->setPermissionDeniedError();
1971 get user id for this user's unix_name
1973 if (is_int ($user_identifier)) { // user_id or user_name
1974 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_id=$1', array($user_identifier));
1976 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_name=$1', array($user_identifier));
1978 if (db_numrows($res_newuser) > 0) {
1980 // make sure user is active
1982 if (db_result($res_newuser,0,'status') != 'A') {
1983 $this->setError(_('User is not active. Only active users can be added.'));
1989 // user was found - set new user_id var
1991 $user_id = db_result($res_newuser,0,'user_id');
1993 $role = new Role($this, $role_id);
1994 if (!$role || !is_object($role)) {
1995 $this->setError(_('Error Getting Role Object'));
1998 } elseif ($role->isError()) {
1999 $this->setError('addUser::roleget::'.$role->getErrorMessage());
2004 $role->addUser(user_get_object($user_id));
2005 if (!$SYS->sysCheckCreateGroup($this->getID())){
2006 $this->setError($SYS->getErrorMessage());
2010 if (!$SYS->sysCheckCreateUser($user_id)) {
2011 $this->setError($SYS->getErrorMessage());
2015 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2016 $this->setError($SYS->getErrorMessage());
2022 // user doesn't exist
2024 $this->setError(_('Error: User does not exist'));
2029 $hook_params['group'] = $this;
2030 $hook_params['group_id'] = $this->getID();
2031 $hook_params['user'] = user_get_object($user_id);
2032 $hook_params['user_id'] = $user_id;
2033 plugin_hook ("group_adduser", $hook_params);
2038 $this->addHistory('Added User',$user_identifier);
2044 * removeUser - controls removing a user from a group.
2046 * Users can remove themselves.
2048 * @param int The ID of the user to remove.
2049 * @return boolean success.
2051 function removeUser($user_id) {
2054 if ($user_id != user_getid()
2055 && !forge_check_perm('project_admin', $this->getID())) {
2056 $this->setPermissionDeniedError();
2062 $user = user_get_object($user_id);
2063 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
2065 foreach ($roles as $role) {
2066 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2067 $found_role = $role;
2071 if ($found_role == NULL) {
2072 $this->setError(sprintf(_('Error: User not removed: %s')));
2076 $found_role->removeUser($user);
2077 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
2078 $this->setError($SYS->getErrorMessage());
2084 // reassign open artifacts to id=100
2086 $res = db_query_params('UPDATE artifact SET assigned_to=100
2087 WHERE group_artifact_id
2088 IN (SELECT group_artifact_id
2089 FROM artifact_group_list
2090 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
2091 array($this->getID(),
2094 $this->setError(_('Error: artifact:').' '.db_error());
2100 // reassign open tasks to id=100
2101 // first have to purge any assignments that would cause
2102 // conflict with existing assignment to 100
2104 $res = db_query_params('DELETE FROM project_assigned_to
2105 WHERE project_task_id IN (SELECT pt.project_task_id
2106 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2107 WHERE pt.group_project_id = pgl.group_project_id
2108 AND pat.project_task_id=pt.project_task_id
2109 AND pt.status_id=1 AND pgl.group_id=$1
2110 AND pat.assigned_to_id=$2)
2111 AND assigned_to_id=100',
2112 array($this->getID(),
2115 $this->setError(sprintf(_('Error: project_assigned_to %d: %s'), 1, db_error()));
2119 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2120 WHERE project_task_id IN (SELECT pt.project_task_id
2121 FROM project_task pt, project_group_list pgl
2122 WHERE pt.group_project_id = pgl.group_project_id
2123 AND pt.status_id=1 AND pgl.group_id=$1)
2124 AND assigned_to_id=$2',
2125 array($this->getID(),
2128 $this->setError(sprintf(_('Error: project_assigned_to %d: %s'), 2, db_error()));
2134 // Remove user from system
2136 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2137 $this->setError($SYS->getErrorMessage());
2142 $hook_params['group'] = $this;
2143 $hook_params['group_id'] = $this->getID();
2144 $hook_params['user'] = user_get_object($user_id);
2145 $hook_params['user_id'] = $user_id;
2146 plugin_hook ("group_removeuser", $hook_params);
2149 $this->addHistory('Removed User',$user_id);
2156 * updateUser - controls updating a user's role in this group.
2158 * @param int The ID of the user.
2159 * @param int The role_id to set this user to.
2160 * @return boolean success.
2162 function updateUser($user_id,$role_id) {
2164 if (!forge_check_perm ('project_admin', $this->getID())) {
2165 $this->setPermissionDeniedError();
2169 $newrole = RBACEngine::getInstance()->getRoleById ($role_id);
2170 if (!$newrole || !is_object($newrole)) {
2171 $this->setError(_('Could Not Get Role'));
2173 } elseif ($newrole->isError()) {
2174 $this->setError(sprintf(_('Role: %s'),$role->getErrorMessage()));
2176 } elseif ($newrole->getHomeProject() == NULL
2177 || $newrole->getHomeProject()->getID() != $this->getID()) {
2178 $this->setError(_('Wrong destination role'));
2181 $user = user_get_object ($user_id);
2182 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user);
2184 foreach ($roles as $role) {
2185 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2186 $found_role = $role;
2190 if ($found_role == NULL) {
2191 $this->setError(sprintf(_('Error: User not removed: %s')));
2195 $found_role->removeUser ($user);
2196 $newrole->addUser ($user);
2198 $this->addHistory('Updated User',$user_id);
2203 * addHistory - Makes an audit trail entry for this project.
2205 * @param string The name of the field.
2206 * @param string The Old Value for this $field_name.
2207 * @return database result handle.
2210 function addHistory($field_name, $old_value) {
2211 return db_query_params ('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2212 VALUES ($1,$2,$3,$4,$5)',
2213 array($this->getID(),
2221 * activateUsers - Make sure that group members have unix accounts.
2223 * Setup unix accounts for group members. Can be called even
2224 * if members are already active.
2228 function activateUsers() {
2230 Activate member(s) of the project
2233 $members = $this->getUsers (true);
2235 foreach ($members as $member) {
2237 foreach (RBACEngine::getInstance()->getAvailableRolesForUser ($member) as $role) {
2238 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2242 foreach ($roles as $role) {
2243 if (!$this->addUser($member->getUnixName(),$role->getID())) {
2254 * getMembers - returns array of User objects for this project
2256 * @return array of User objects for this group.
2258 function getMembers() {
2259 return $this->getUsers (true);
2263 * replaceTemplateStrings - fill-in some blanks with project name
2265 * @param string Template string
2266 * @return string String after replacements
2268 function replaceTemplateStrings($string) {
2269 $string = str_replace ('UNIXNAME', $this->getUnixName(), $string);
2270 $string = str_replace ('PUBLICNAME', $this->getPublicName(), $string);
2271 $string = str_replace ('DESCRIPTION', $this->getDescription(), $string);
2276 * approve - Approve pending project.
2278 * @param User $user The User object who is doing the updating.
2282 function approve(&$user) {
2283 global $gfcommon,$gfwww;
2284 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2286 if ($this->getStatus()=='A') {
2287 $this->setError(_("Group already active"));
2293 // Step 1: Activate group and create LDAP entries
2294 if (!$this->setStatus($user, 'A')) {
2299 // Switch to system language for item creation
2300 setup_gettext_from_sys_lang();
2302 // Create default roles
2303 $idadmin_group = NULL;
2304 foreach (get_group_join_requests ($this) as $gjr) {
2305 $idadmin_group = $gjr->getUserID();
2308 if ($idadmin_group == NULL) {
2309 $idadmin_group = $user->getID();
2312 $template = $this->getTemplateProject();
2313 $id_mappings = array();
2314 $seen_admin_role = false;
2316 // Copy roles from template project
2317 foreach($template->getRoles() as $oldrole) {
2318 if ($oldrole->getHomeProject() != NULL) {
2319 $role = new Role($this);
2321 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2322 $role->create('TEMPORARY ROLE NAME', $data, true);
2323 $role->setName($oldrole->getName());
2324 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2325 $seen_admin_role = true;
2329 $role->linkProject($this);
2331 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2332 // Reuse the project_admin permission
2333 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID()));
2337 if (!$seen_admin_role) {
2338 $role = new Role($this);
2339 $adminperms = array('project_admin' => array ($this->getID() => 1));
2340 $role_id = $role->create ('Admin', $adminperms, true);
2343 $roles = $this->getRoles();
2344 foreach ($roles as $r) {
2345 if ($r->getHomeProject() == NULL) {
2348 if ($r->getSetting ('project_admin', $this->getID())) {
2349 $r->addUser(user_get_object ($idadmin_group));
2353 // Temporarily switch to the submitter's identity
2354 $saved_session = session_get_user();
2355 session_set_internal($idadmin_group);
2358 if (forge_get_config('use_tracker')) {
2359 $this->setUseTracker ($template->usesTracker());
2360 if ($template->usesTracker()) {
2361 $oldatf = new ArtifactTypeFactory($template);
2362 foreach ($oldatf->getArtifactTypes() as $o) {
2363 $t = new ArtifactType ($this);
2364 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions());
2365 $id_mappings['tracker'][$o->getID()] = $t->getID();
2366 $t->cloneFieldsFrom ($o->getID());
2371 if (forge_get_config('use_pm')) {
2372 $this->setUsePM ($template->usesPM());
2373 if ($template->usesPM()) {
2374 $oldpgf = new ProjectGroupFactory($template);
2375 foreach ($oldpgf->getProjectGroups() as $o) {
2376 $pg = new ProjectGroup($this);
2377 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2378 $id_mappings['pm'][$o->getID()] = $pg->getID();
2383 if (forge_get_config('use_forum')) {
2384 $this->setUseForum($template->usesForum());
2385 if ($template->usesForum()) {
2386 $oldff = new ForumFactory($template);
2387 foreach ($oldff->getForums() as $o) {
2388 $f = new Forum($this);
2389 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo(),1);
2390 $id_mappings['forum'][$o->getID()] = $f->getID();
2395 if (forge_get_config('use_docman')) {
2396 $this->setUseDocman($template->usesDocman());
2397 if ($template->usesDocman()) {
2398 $olddgf = new DocumentGroupFactory($template);
2399 // First pass: create all docgroups
2400 $id_mappings['docman_docgroup'][0] = 0;
2401 foreach ($olddgf->getDocumentGroups() as $o) {
2402 $ndgf = new DocumentGroup($this);
2403 // .trash is a reserved directory
2404 if ($o->getName() != '.trash' && $o->getParentID() == 0) {
2405 $ndgf->create($this->replaceTemplateStrings($o->getName()));
2406 $id_mappings['docman_docgroup'][$o->getID()] = $ndgf->getID();
2409 // Second pass: restore hierarchy links
2410 foreach ($olddgf->getDocumentGroups() as $o) {
2411 $ndgf = new DocumentGroup($this);
2412 if ($o->getName() != '.trash' && $o->getParentID() == 0) {
2413 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2414 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()]);
2420 if (forge_get_config('use_frs')) {
2421 $this->setUseFRS ($template->usesFRS());
2422 if ($template->usesFRS()) {
2423 foreach (get_frs_packages($template) as $o) {
2424 $newp = new FRSPackage($this);
2425 $nname = $this->replaceTemplateStrings($o->getName());
2426 $newp->create ($nname, $o->isPublic());
2431 if (forge_get_config('use_mail')) {
2432 $this->setUseMail($template->usesMail());
2433 if ($template->usesMail()) {
2434 $oldmlf = new MailingListFactory($template);
2435 foreach ($oldmlf->getMailingLists() as $o) {
2436 $ml = new MailingList($this);
2437 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName());
2439 $ndescription = $this->replaceTemplateStrings($o->getDescription());
2440 $ml->create($nname, $ndescription, $o->isPublic());
2446 /* use SCM plugin from template group */
2447 $this->setUseSCM($template->usesSCM());
2449 foreach ($template->getPlugins() as
2450 $plugin_id => $plugin_name) {
2451 $this->setPluginUse($plugin_name);
2454 /* use SCM choice from registration page */
2456 foreach ($template->getPlugins() as
2457 $plugin_id => $plugin_name) {
2458 if (substr($plugin_name, 3) == 'scm' &&
2459 $plugin_name != 'scmhook') {
2460 /* skip copying scm plugins */
2463 /* enable other plugins though */
2464 $this->setPluginUse($plugin_name);
2468 foreach ($template->getRoles() as $oldrole) {
2469 $newrole = RBACEngine::getInstance()->getRoleById ($id_mappings['role'][$oldrole->getID()]);
2470 if ($oldrole->getHomeProject() != NULL
2471 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2472 $newrole->setPublic ($oldrole->isPublic());
2474 $oldsettings = $oldrole->getSettingsForProject ($template);
2476 $sections = array('project_read', 'project_admin', 'frs', 'scm', 'docman', 'tracker_admin', 'new_tracker', 'forum_admin', 'new_forum', 'pm_admin', 'new_pm');
2477 foreach ($sections as $section) {
2478 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]);
2481 $sections = array('tracker', 'pm', 'forum');
2482 foreach ($sections as $section) {
2483 if (isset ($oldsettings[$section])) {
2484 foreach ($oldsettings[$section] as $k => $v) {
2485 // Only copy perms for tools that have been copied
2486 if (isset ($id_mappings[$section][$k])) {
2487 $newrole->setSetting ($section,
2488 $id_mappings[$section][$k],
2496 $lm = new WidgetLayoutManager();
2497 $lm->createDefaultLayoutForProject ($this->getID(), $template->getID());
2500 $params['template'] = $template;
2501 $params['project'] = $this;
2502 $params['id_mappings'] = $id_mappings;
2503 plugin_hook_by_reference ('clone_project_from_template', $params);
2505 // Disable everything
2506 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',
2507 array($this->getID()));
2510 $this->normalizeAllRoles();
2511 // empty members cache because the group creator is not yet in cache.
2512 unset($this->membersArr);
2513 $this->activateUsers();
2515 // Delete fake join request
2516 foreach (get_group_join_requests ($this) as $gjr) {
2520 // Switch back to user preference
2521 session_set_internal($saved_session->getID());
2522 setup_gettext_from_context();
2526 $this->sendApprovalEmail();
2527 $this->addHistory(_('Approved'), 'x');
2530 // Plugin can make approve operation there
2533 $params['group'] = $this;
2534 $params['group_id'] = $this->getID();
2535 plugin_hook('group_approved', $params);
2541 * sendApprovalEmail - Send new project email.
2543 * @return boolean success.
2546 function sendApprovalEmail() {
2547 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID());
2549 if (count($admins) < 1) {
2550 $this->setError(_("Group does not have any administrators."));
2554 // send one email per admin
2555 foreach ($admins as $admin) {
2556 setup_gettext_for_user ($admin);
2558 $message=sprintf(_('Your project registration for %4$s has been approved.
2560 Project Full Name: %1$s
2561 Project Unix Name: %2$s
2563 Your DNS will take up to a day to become active on our site.
2564 Your web site is accessible through your shell account. Please read
2565 site documentation (see link below) about intended usage, available
2566 services, and directory layout of the account.
2569 own project page in %4$s while logged in, you will find
2570 additional menu functions to your left labeled \'Project Admin\'.
2572 We highly suggest that you now visit %4$s and create a public
2573 description for your project. This can be done by visiting your project
2574 page while logged in, and selecting \'Project Admin\' from the menus
2575 on the left (or by visiting %3$s
2578 Your project will also not appear in the Trove Software Map (primary
2579 list of projects hosted on %4$s which offers great flexibility in
2580 browsing and search) until you categorize it in the project administration
2581 screens. So that people can find your project, you should do this now.
2582 Visit your project while logged in, and select \'Project Admin\' from the
2585 Enjoy the system, and please tell others about %4$s. Let us know
2586 if there is anything we can do to help you.
2589 htmlspecialchars_decode($this->getPublicName()),
2590 $this->getUnixName(),
2591 util_make_url ('/project/admin/?group_id='.$this->getID()),
2592 forge_get_config ('forge_name'));
2594 util_send_message($admin->getEmail(), sprintf(_('%1$s Project Approved'), forge_get_config ('forge_name')), $message);
2596 setup_gettext_from_context();
2603 * sendRejectionEmail - Send project rejection email.
2605 * This function sends out a rejection message to a user who
2606 * registered a project.
2608 * @param int The id of the response to use.
2609 * @param string The rejection message.
2610 * @return boolean completion status.
2613 function sendRejectionEmail($response_id, $message="zxcv") {
2614 $submitters = array();
2615 foreach (get_group_join_requests ($this) as $gjr) {
2616 $submitters[] = user_get_object($gjr->getUserID());
2619 if (count ($submitters) < 1) {
2620 $this->setError(_("Group does not have any administrators."));
2624 foreach ($submitters as $admin) {
2625 setup_gettext_for_user($admin);
2627 $response=sprintf(_('Your project registration for %3$s has been denied.
2629 Project Full Name: %1$s
2630 Project Unix Name: %2$s
2632 Reasons for negative decision:
2634 '), $this->getPublicName(), $this->getUnixName(), forge_get_config('forge_name'));
2636 // Check to see if they want to send a custom rejection response
2637 if ($response_id == 0) {
2638 $response .= $message;
2640 $response .= db_result(
2641 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array($response_id)),
2646 util_send_message($admin->getEmail(), sprintf(_('%s Project Denied'), forge_get_config ('forge_name')), $response);
2647 setup_gettext_from_context();
2654 * sendNewProjectNotificationEmail - Send new project notification email.
2656 * This function sends out a notification email to the
2657 * SourceForge admin user when a new project is
2660 * @return boolean success.
2663 function sendNewProjectNotificationEmail() {
2664 // Get the user who wants to register the project
2665 $submitters = array();
2666 foreach (get_group_join_requests ($this) as $gjr) {
2667 $submitters[] = user_get_object($gjr->getUserID());
2669 if (count ($submitters) < 1) {
2670 $this->setError(_("Could not find user who has submitted the project."));
2674 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('approve_projects', -1);
2676 if (count($admins) < 1) {
2677 $this->setError(_("There is no administrator to send the mail to."));
2681 foreach ($admins as $admin) {
2682 $admin_email = $admin->getEmail();
2683 setup_gettext_for_user ($admin);
2685 $message = sprintf(_('New %1$s Project Submitted
2687 Project Full Name: %2$s
2688 Submitted Description: %3$s
2690 forge_get_config ('forge_name'),
2691 htmlspecialchars_decode($this->getPublicName()),
2692 htmlspecialchars_decode($this->getRegistrationPurpose()));
2694 foreach ($submitters as $submitter) {
2695 $message .= sprintf(_('Submitter: %1$s (%2$s)
2697 $submitter->getRealName(),
2698 $submitter->getUnixName());
2701 $message .= sprintf (_('
2702 Please visit the following URL to approve or reject this project:
2704 util_make_url ('/admin/approve-pending.php'));
2705 util_send_message($admin_email, sprintf(_('New %1$s Project Submitted'), forge_get_config ('forge_name')), $message);
2706 setup_gettext_from_context();
2709 $email = $submitter->getEmail();
2710 setup_gettext_for_user ($submitter);
2712 $message = sprintf(_('New %1$s Project Submitted
2714 Project Full Name: %2$s
2715 Submitted Description: %3$s
2717 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'));
2719 util_send_message($email, sprintf(_('New %1$s Project Submitted'), forge_get_config ('forge_name')), $message);
2720 setup_gettext_from_context();
2726 * validateGroupName - Validate the group name
2728 * @param string Group name.
2730 * @return boolean an error false and set an error is the group name is invalid otherwise return true
2732 function validateGroupName($group_name) {
2733 if (strlen($group_name)<3) {
2734 $this->setError(_('Group name is too short'));
2736 } elseif (strlen(htmlspecialchars($group_name))>50) {
2737 $this->setError(_('Group name is too long'));
2739 } elseif (group_get_object_by_publicname($group_name)) {
2740 $this->setError(_('Group name already taken'));
2748 * getRolesId - Get Ids of the roles of the group.
2750 * @return array Role ids of this group.
2752 function getRolesId() {
2753 $role_ids = array();
2755 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2756 array($this->getID()));
2757 while ($arr = db_fetch_array($res)) {
2758 $role_ids[] = $arr['role_id'];
2760 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2761 array($this->getID()));
2762 while ($arr = db_fetch_array($res)) {
2763 $role_ids[] = $arr['role_id'];
2766 return array_unique($role_ids);
2770 * getRoles - Get the roles of the group.
2772 * @return array Roles of this group.
2774 function getRoles() {
2777 $roles = $this->getRolesId();
2778 $engine = RBACEngine::getInstance();
2779 foreach ($roles as $role_id) {
2780 $result[] = $engine->getRoleById ($role_id);
2786 function normalizeAllRoles() {
2787 $roles = $this->getRoles();
2789 foreach ($roles as $r) {
2790 $r->normalizeData();
2795 * getUnixStatus - Status of activation of unix account.
2797 * @return string Values: (N)one, (A)ctive, (S)uspended or (D)eleted
2799 function getUnixStatus() {
2800 return $this->data_array['unix_status'];
2804 * setUnixStatus - Sets status of activation of unix account.
2806 * @param string $status The unix status.
2812 * @return boolean success.
2814 function setUnixStatus($status) {
2817 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
2822 $this->setError(sprintf(_('Error: Cannot Update Group Unix Status: %s'),db_error()));
2826 if ($status == 'A') {
2827 if (!$SYS->sysCheckCreateGroup($this->getID())) {
2828 $this->setError($SYS->getErrorMessage());
2833 if ($SYS->sysCheckGroup($this->getID())) {
2834 if (!$SYS->sysRemoveGroup($this->getID())) {
2835 $this->setError($SYS->getErrorMessage());
2842 $this->data_array['unix_status']=$status;
2849 * getUsers - Get the users of a group
2851 * @return array of user's objects.
2853 function getUsers($onlylocal = true) {
2854 if (!isset($this->membersArr)) {
2855 $this->membersArr = array();
2858 foreach ($this->getRoles() as $role) {
2860 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
2863 foreach ($role->getUsers() as $user) {
2864 $ids[] = $user->getID();
2867 $ids = array_unique ($ids);
2868 foreach ($ids as $id) {
2869 $u = user_get_object ($id);
2870 if ($u->isActive()) {
2871 $this->membersArr[] = $u;
2875 return $this->membersArr;
2878 function setDocmanCreateOnlineStatus($status) {
2880 /* if we activate search engine, we probably want to reindex */
2881 $res = db_query_params('UPDATE groups SET use_docman_create_online=$1 WHERE group_id=$2',
2882 array($status, $this->getID()));
2885 $this->setError(sprintf(_('Error: Cannot Update Group DocmanCreateOnline Status: %s'),db_error()));
2889 $this->data_array['use_docman_create_online']=$status;
2895 function setDocmanWebdav($status) {
2897 /* if we activate search engine, we probably want to reindex */
2898 $res = db_query_params('UPDATE groups SET use_webdav=$1 WHERE group_id=$2',
2903 $this->setError(sprintf(_('Error: Cannot Update Group UseWebdab Status: %s'),db_error()));
2907 $this->data_array['use_webdav']=$status;
2913 function setDocmanSearchStatus($status) {
2915 /* if we activate search engine, we probably want to reindex */
2916 $res = db_query_params('UPDATE groups SET use_docman_search=$1, force_docman_reindex=$1 WHERE group_id=$2',
2921 $this->setError(sprintf(_('Error: Cannot Update Group UseDocmanSearch Status: %s'),db_error()));
2925 $this->data_array['use_docman_search']=$status;
2931 function setDocmanForceReindexSearch($status) {
2933 /* if we activate search engine, we probably want to reindex */
2934 $res = db_query_params('UPDATE groups SET force_docman_reindex=$1 WHERE group_id=$2',
2939 $this->setError(sprintf(_('Error: Cannot Update Group force_docman_reindex %s'),db_error()));
2943 $this->data_array['force_docman_reindex']=$status;
2951 * group_getname() - get the group name
2953 * @param int The group ID
2958 function group_getname ($group_id = 0) {
2959 $grp = group_get_object($group_id);
2961 return $grp->getPublicName();
2968 * group_getunixname() - get the unixname for a group
2970 * @param int The group ID
2975 function group_getunixname ($group_id) {
2976 $grp = group_get_object($group_id);
2978 return $grp->getUnixName();
2985 * group_get_result() - Get the group object result ID.
2987 * @param int The group ID
2992 function &group_get_result($group_id=0) {
2993 $grp = group_get_object($group_id);
2995 return $grp->getData();
3001 function getAllProjectTags($onlyvisible = true) {
3002 $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',
3005 if (!$res || db_numrows($res) == 0) {
3011 while ($arr = db_fetch_array($res)) {
3013 $group_id = $arr[1];
3014 if (!isset($result[$tag])) {
3015 $result[$tag] = array();
3018 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
3019 $p = group_get_object($group_id);
3020 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
3021 'group_id' => $group_id);
3029 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
3032 class ProjectComparator {
3033 var $criterion = 'name';
3035 function Compare ($a, $b) {
3036 switch ($this->criterion) {
3039 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName());
3040 if ($namecmp != 0) {
3043 /* If several projects share a same public name */
3044 return strcoll ($a->getUnixName(), $b->getUnixName());
3047 return strcmp ($a->getUnixName(), $b->getUnixName());
3055 return ($a < $b) ? -1 : 1;
3061 function sortProjectList (&$list, $criterion='name') {
3062 $cmp = new ProjectComparator();
3063 $cmp->criterion = $criterion;
3065 return usort ($list, array($cmp, 'Compare'));
3070 // c-file-style: "bsd"