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-2017, Franck Villaume - TrivialDev
10 * Copyright 2013, French Ministry of National Education
11 * Copyright 2017, Stéphane-Eymeric Bredthauer - TrivialDev
12 * http://fusionforge.org
14 * This file is part of FusionForge. FusionForge is free software;
15 * you can redistribute it and/or modify it under the terms of the
16 * GNU General Public License as published by the Free Software
17 * Foundation; either version 2 of the Licence, or (at your option)
20 * FusionForge is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License along
26 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 require_once $gfcommon.'tracker/ArtifactTypes.class.php';
31 require_once $gfcommon.'tracker/ArtifactTypeFactory.class.php';
32 require_once $gfcommon.'tracker/RoadmapFactory.class.php';
33 require_once $gfcommon.'forum/Forum.class.php';
34 require_once $gfcommon.'forum/ForumFactory.class.php';
35 require_once $gfcommon.'pm/ProjectGroup.class.php';
36 require_once $gfcommon.'pm/ProjectGroupFactory.class.php';
37 require_once $gfcommon.'frs/FRSPackage.class.php';
38 require_once $gfcommon.'frs/FRSRelease.class.php';
39 require_once $gfcommon.'docman/DocumentGroup.class.php';
40 require_once $gfcommon.'docman/DocumentGroupFactory.class.php';
41 require_once $gfcommon.'mail/MailingList.class.php';
42 require_once $gfcommon.'mail/MailingListFactory.class.php';
43 require_once $gfcommon.'survey/SurveyFactory.class.php';
44 require_once $gfcommon.'survey/SurveyQuestionFactory.class.php';
45 require_once $gfcommon.'include/gettext.php';
46 require_once $gfcommon.'include/GroupJoinRequest.class.php';
47 require_once $gfcommon.'include/Role.class.php';
48 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
53 * group_get_object() - Get the group object.
55 * group_get_object() is useful so you can pool group objects/save database queries
56 * You should always use this instead of instantiating the object directly.
58 * You can now optionally pass in a db result handle. If you do, it re-uses that query
59 * to instantiate the objects.
61 * IMPORTANT! That db result must contain all fields
62 * from groups table or you will have problems
64 * @param int $group_id Required
65 * @param int|bool $res Result set handle ("SELECT * FROM groups WHERE group_id=xx")
66 * @return Group|bool A group object or false on failure
68 function &group_get_object($group_id, $res = false) {
69 //create a common set of group objects
70 //saves a little wear on the database
72 //automatically checks group_type and
73 //returns appropriate object
76 if (!isset($GROUP_OBJ["_".$group_id."_"])) {
78 //the db result handle was passed in
80 $res = db_query_params('SELECT * FROM groups WHERE group_id=$1', array($group_id));
82 if (!$res || db_numrows($res) < 1) {
83 $GROUP_OBJ["_".$group_id."_"]=false;
86 check group type and set up object
88 $GROUP_OBJ["_".$group_id."_"] = new Group($group_id, $res);
91 return $GROUP_OBJ["_".$group_id."_"];
94 function &group_get_objects($id_arr) {
97 // Note: if we don't do this, the result may be corrupted
101 foreach ($id_arr as $id) {
103 // See if this ID already has been fetched in the cache
105 if (!isset($GROUP_OBJ["_".$id."_"])) {
109 if (count($fetch) > 0) {
110 $res=db_query_params('SELECT * FROM groups WHERE group_id = ANY ($1)',
111 array(db_int_array_to_any_clause($fetch)));
112 while ($arr = db_fetch_array($res)) {
113 $GROUP_OBJ["_".$arr['group_id']."_"] = new Group($arr['group_id'],$arr);
116 foreach ($id_arr as $id) {
117 $return[] =& $GROUP_OBJ["_".$id."_"];
122 function &group_get_active_projects() {
123 $res = db_query_params('SELECT group_id FROM groups WHERE status=$1',
125 return group_get_objects(util_result_column_to_array($res,0));
128 function &group_get_all_projects() {
129 $res = db_query_params ('SELECT group_id FROM groups',
131 return group_get_objects(util_result_column_to_array($res,0));
134 function &group_get_template_projects() {
135 $res = db_query_params('SELECT group_id FROM groups WHERE is_template=1 AND status != $1',
137 return group_get_objects(util_result_column_to_array($res,0));
140 function &group_get_object_by_name($groupname) {
141 $res = db_query_params('SELECT * FROM groups WHERE unix_group_name=$1', array($groupname));
142 return group_get_object(db_result($res, 0, 'group_id'), $res);
145 function &group_get_objects_by_name($groupname_arr) {
146 $res = db_query_params('SELECT group_id FROM groups WHERE unix_group_name = ANY ($1)',
147 array(db_string_array_to_any_clause($groupname_arr)));
148 $arr =& util_result_column_to_array($res,0);
149 return group_get_objects($arr);
152 function group_get_object_by_publicname($groupname) {
153 $res = db_query_params('SELECT * FROM groups WHERE lower(group_name) LIKE $1',
154 array(htmlspecialchars(html_entity_decode(strtolower($groupname)))));
155 return group_get_object(db_result($res, 0, 'group_id'), $res);
158 function filter_groups_by_read_access($grps) {
159 $filteredgrps = array();
160 foreach ($grps as $g) {
161 if (forge_check_perm ('project_read', $g->getID())) {
162 $filteredgrps[] = $g;
165 return $filteredgrps;
169 * get_public_active_projects_asc() - Get a list of rows for public active projects (initially in trove/full_list)
171 * @param int $max_query_limit Optional Maximum number of rows to limit query length
172 * @param int $offset start to retrieve rows from offset value
173 * @return array List of public active projects
175 function group_get_public_active_projects_asc($max_query_limit = -1, $offset = 0) {
177 if (session_loggedin()) {
179 $userRoles = $LUSER->getRoles();
180 if (count($userRoles)) {
181 foreach ($userRoles as $r) {
182 $role_id .= ', '.$r->getID();
187 $res_grp = db_query_params ('
188 SELECT group_id, group_name, unix_group_name, short_description, register_time
190 WHERE status = $1 AND is_template=0 AND register_time > 0
191 AND group_id in (select ref_id FROM pfo_role_setting WHERE section_name = $2 and perm_val = 1 and role_id IN ('.$role_id.'))
192 ORDER BY group_name ASC
194 array('A', 'project_read'),
195 $max_query_limit, $offset);
197 while ($row_grp = db_fetch_array($res_grp)) {
198 $projects[] = $row_grp;
204 * group_get_readable_projects_using_tag_asc() - Get a list of group_id for active projects (initially in trove/tag_cloud)
206 * @param string $selected_tag Tag to search
207 * @param int $max_query_limit Optional Maximum number of rows to limit query length
208 * @param int $offset start to retrieve rows from offset value
209 * @return array List of public active projects
211 function group_get_readable_projects_using_tag_asc($selected_tag, $max_query_limit = -1, $offset = 0) {
213 if (session_loggedin()) {
215 $userRoles = $LUSER->getRoles();
216 if (count($userRoles)) {
217 foreach ($userRoles as $r) {
218 $role_id .= ', '.$r->getID();
223 $res_grp = db_query_params ('SELECT groups.group_id, group_name, unix_group_name, short_description, register_time
224 FROM project_tags, groups
225 WHERE LOWER(name) = $1
226 AND project_tags.group_id = groups.group_id
227 AND groups.status = $2 AND groups.is_template=0 AND groups.register_time > 0
228 AND groups.group_id in (select ref_id FROM pfo_role_setting WHERE section_name = $3 and perm_val = 1 and role_id IN ('.$role_id.'))
229 ORDER BY groups.group_name ASC',
230 array(strtolower($selected_tag), 'A', 'project_read'),
231 $max_query_limit, $offset);
233 while ($row_grp = db_fetch_array($res_grp)) {
234 $projects[] = $row_grp;
239 class Group extends FFError {
241 * Associative array of data from db.
243 * @var array $data_array.
248 * array of User objects.
250 * @var array $membersArr.
255 * Group - Group object constructor - use group_get_object() to instantiate.
257 * @param int|bool $id Required - Id of the group you want to instantiate.
258 * @param int|bool $res Database result from select query OR associative array of all columns.
260 function __construct($id = false, $res = false) {
261 parent::__construct();
263 //setting up an empty object
264 //probably going to call create()
268 if (!$this->fetchData($id)) {
273 // Assoc array was passed in
275 if (is_array($res)) {
276 $this->data_array =& $res;
278 if (db_numrows($res) < 1) {
279 //function in class we extended
280 $this->setError(_('Group Not Found'));
281 $this->data_array=array();
284 //set up an associative array for use by other functions
285 $this->data_array = db_fetch_array_by_row($res, 0);
293 * fetchData - May need to refresh database fields if an update occurred.
295 * @param int $group_id The group_id.
296 * @return bool success or not
298 function fetchData($group_id) {
299 $res = db_query_params ('SELECT * FROM groups WHERE group_id=$1',
301 if (!$res || db_numrows($res) < 1) {
302 $this->setError('fetchData()'._(': ').db_error());
305 $this->data_array = db_fetch_array($res);
310 * create - Create new group.
312 * This method should be called on empty Group object.
313 * It will add an entry for a pending group/project (status 'P')
315 * @param object $user The User object.
316 * @param string $group_name The full name of the user.
317 * @param string $unix_name The Unix name of the user.
318 * @param string $description The new group description.
319 * @param string $purpose The purpose of the group.
320 * @param string $unix_box
321 * @param string $scm_box
322 * @param bool $send_mail Whether to send an email or not
323 * @param int $built_from_template The id of the project this new project is based on
324 * @param int $createtimestamp The Time Stamp of creation to ease import.
325 * @return bool success or not
327 function create(&$user, $group_name, $unix_name, $description, $purpose, $unix_box = 'shell1',
328 $scm_box = 'cvs1', $send_mail = true, $built_from_template = 0, $createtimestamp = null) {
329 // $user is ignored - anyone can create pending group
332 if ($this->getID()!=0) {
333 $this->setError(_('Group object already exists.'));
335 } elseif (!$this->validateGroupName($group_name)) {
336 $this->setError(_('Invalid project name'));
338 } elseif (!account_groupnamevalid($unix_name)) {
339 $this->setError(_('Invalid Unix Name.'));
341 } elseif (!$SYS->sysUseUnixName($unix_name)) {
342 $this->setError(_('Unix name already taken.'));
344 } elseif (strlen($purpose)<10) {
345 $this->setError(_('Please describe your Registration Project Purpose and Summarization in a more comprehensive manner.'));
347 } elseif (strlen($purpose)>1500) {
348 $this->setError(_('The Registration Project Purpose and Summarization text is too long. Please make it smaller than 1500 characters.'));
350 } elseif (strlen($description)<10) {
351 $this->setError(_('Describe in a more comprehensive manner your project.'));
355 // Check if use_project_vhost for homepage
356 if (forge_get_config('use_project_vhost')) {
357 $homepage = $unix_name.'.'.forge_get_config('web_host');
359 $homepage = forge_get_config('web_host')."/www/".$unix_name."/";
363 $createtimestamp = (($createtimestamp) ? $createtimestamp : time());
364 $res = db_query_params('
379 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)',
380 array(htmlspecialchars($group_name),
382 htmlspecialchars($description),
388 htmlspecialchars($purpose),
390 md5(util_randbytes()),
391 $built_from_template));
392 if (!$res || db_affected_rows($res) < 1) {
393 $this->setError(_('Error')._(': ')._('Cannot create group')._(': ').db_error());
398 $id = db_insertid($res, 'groups', 'group_id');
400 $this->setError(_('Error')._(': ')._('Cannot get group id')._(': ').db_error());
405 if (!$this->fetchData($id)) {
410 $gjr = new GroupJoinRequest($this);
411 $gjr->create($user->getID(), 'Fake GroupJoinRequest to store the creator of a project', false);
413 $hook_params = array();
414 $hook_params['group'] = $this;
415 $hook_params['group_id'] = $this->getID();
416 $hook_params['group_name'] = $group_name;
417 $hook_params['unix_group_name'] = $unix_name;
418 $hook_params['createtimestamp'] = $createtimestamp;
419 plugin_hook("group_create", $hook_params);
423 $this->sendNewProjectNotificationEmail();
431 * updateAdmin - Update core properties of group object.
433 * This function require site admin privilege.
435 * @param object $user User requesting operation (for access control).
436 * @param string $unix_box Machine on which group's home directory located.
437 * @param string $http_domain Domain which serves group's WWW.
438 * @return bool status.
441 function updateAdmin(&$user, $unix_box, $http_domain) {
442 $perm =& $this->getPermission();
444 if (!$perm || !is_object($perm)) {
445 $this->setError(_('Could not get permission.'));
449 if (!$perm->isSuperUser()) {
450 $this->setError(_('Permission denied.'));
456 $res = db_query_params('
458 SET unix_box=$1, http_domain=$2
464 if (!$res || db_affected_rows($res) < 1) {
465 $this->setError(_('Error')._(': ')._('Cannot change group properties')._(': ').db_error());
470 // Log the audit trail
471 if ($unix_box != $this->data_array['unix_box']) {
472 $this->addHistory('unix_box', $this->data_array['unix_box']);
474 if ($http_domain != $this->data_array['http_domain']) {
475 $this->addHistory('http_domain', $this->data_array['http_domain']);
478 if (!$this->fetchData($this->getID())) {
487 * update - Update number of common properties.
489 * Unlike updateAdmin(), this function accessible to project admin.
491 * @param object $user User requesting operation (for access control).
492 * @param string $group_name
493 * @param string $homepage
494 * @param string $short_description
495 * @param bool $use_mail
496 * @param bool $use_survey
497 * @param bool $use_forum
498 * @param bool $use_pm
499 * @param bool $use_pm_depend_box
500 * @param bool $use_scm
501 * @param bool $use_news
502 * @param bool $use_docman
503 * @param string $new_doc_address
504 * @param bool $send_all_docs
505 * @param int $logo_image_id XXXX UNUSED XXXX -> see getLogoImageID function
506 * @param bool $use_ftp
507 * @param bool $use_tracker
508 * @param bool $use_frs
509 * @param bool $use_stats
510 * @param string $tags
511 * @param bool $use_activity
512 * @param bool $is_public group is publicly accessible
513 * @return int status.
516 function update(&$user, $group_name, $homepage, $short_description, $use_mail, $use_survey, $use_forum,
517 $use_pm, $use_pm_depend_box, $use_scm, $use_news, $use_docman,
518 $new_doc_address, $send_all_docs, $logo_image_id,
519 $use_ftp, $use_tracker, $use_frs, $use_stats, $tags, $use_activity, $is_public) {
521 $perm =& $this->getPermission();
523 if (!$perm || !is_object($perm)) {
524 $this->setError(_('Could not get permission.'));
528 if (!$perm->isAdmin()) {
529 $this->setError(_('Permission denied.'));
533 // Validate some values
534 if ($this->getPublicName() != htmlspecialchars($group_name)) {
535 if (!$this->validateGroupName($group_name)) {
540 if ($new_doc_address) {
541 $invalid_mails = validate_emails($new_doc_address);
542 if (count($invalid_mails) > 0) {
543 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
548 // in the database, these all default to '1',
549 // so we have to explicitly set 0
562 if (!$use_pm_depend_box) {
563 $use_pm_depend_box = 0;
586 if (!$use_activity) {
589 if (!$send_all_docs) {
593 $homepage = ltrim($homepage);
595 $homepage = util_make_url('/projects/'.$this->getUnixName().'/');
600 $res = db_query_params('UPDATE groups
603 short_description=$3,
608 use_pm_depend_box=$8,
619 array(htmlspecialchars($group_name),
621 htmlspecialchars($short_description),
638 if (!$res || db_affected_rows($res) < 1) {
639 $this->setError(_('Error updating project information')._(': ').db_error());
644 if (!$this->setUseDocman($use_docman)) {
645 $this->setError(_('Error updating project information use_docman')._(': ').db_error());
650 if ($this->setTags($tags) === false) {
655 // Log the audit trail
656 $this->addHistory('Changed Public Info', '');
658 if (!$this->fetchData($this->getID())) {
663 $hook_params = array();
664 $hook_params['group'] = $this;
665 $hook_params['group_id'] = $this->getID();
666 $hook_params['group_homepage'] = $homepage;
667 $hook_params['group_name'] = htmlspecialchars($group_name);
668 $hook_params['group_description'] = htmlspecialchars($short_description);
669 $hook_params['group_ispublic'] = $is_public;
670 if (!plugin_hook("group_update", $hook_params)) {
671 if (!$this->isError()) {
672 $this->setError(_('Error updating project information in plugin_hook group_update'));
683 * getID - Simply return the group_id for this object.
685 * @return int group_id.
688 return $this->data_array['group_id'];
692 * getStatus - the status code.
694 * Statuses char include I,H,A,D,P.
701 function getStatus() {
702 return $this->data_array['status'];
706 * setStatus - set the status code.
708 * Statuses include I,H,A,D,P.
715 * @param object $user User requesting operation (for access control).
716 * @param string $status Status value.
717 * @return bool success.
720 function setStatus(&$user, $status) {
723 if (!forge_check_global_perm_for_user($user, 'approve_projects')) {
724 $this->setPermissionDeniedError();
728 // Projects in 'A' status can only go to 'H' or 'D'
729 // Projects in 'D' status can only go to 'A'
730 // Projects in 'P' status can only go to 'A' OR 'D'
731 // Projects in 'I' status can only go to 'P'
732 // Projects in 'H' status can only go to 'A' OR 'D'
733 $allowed_status_changes = array(
734 'AH'=>1,'AD'=>1,'DA'=>1,'PA'=>1,'PD'=>1,
735 'IP'=>1,'HA'=>1,'HD'=>1
738 // Check that status transition is valid
739 if ($this->getStatus() != $status
740 && !array_key_exists($this->getStatus(). $status, $allowed_status_changes)) {
741 $this->setError(_('Invalid Status Change From')._(': ').$this->getStatus()._(' To ')._(': ').$status);
747 $res = db_query_params('UPDATE groups
749 WHERE group_id=$2', array($status, $this->getID()));
751 if (!$res || db_affected_rows($res) < 1) {
752 $this->setError(_('Error')._(': ')._('Cannot change group status')._(': ').db_error());
758 // Activate system group, if not yet
759 if (!$SYS->sysCheckGroup($this->getID())) {
760 if (!$SYS->sysCreateGroup($this->getID())) {
761 $this->setError($SYS->getErrorMessage());
766 if (!$this->activateUsers()) {
771 /* Otherwise, the group is not active, and make sure that
772 System group is not active either */
773 } elseif ($SYS->sysCheckGroup($this->getID())) {
774 if (!$SYS->sysRemoveGroup($this->getID())) {
775 $this->setError($SYS->getErrorMessage());
781 $hook_params = array();
782 $hook_params['group'] = $this;
783 $hook_params['group_id'] = $this->getID();
784 $hook_params['status'] = $status;
785 plugin_hook("group_setstatus", $hook_params);
789 // Log the audit trail
790 if ($status != $this->getStatus()) {
791 $this->addHistory(_('Status'), $this->getStatus());
794 $this->data_array['status'] = $status;
799 * isPublic - Wrapper around RBAC to check if a project is anonymously readable
801 * @return boo is_public.
803 function isPublic() {
804 $ra = RoleAnonymous::getInstance();
805 return $ra->hasPermission('project_read', $this->getID());
809 * isActive - Database field status of 'A' returns true.
811 * @return bool is_active.
813 function isActive() {
814 if ($this->getStatus() == 'A') {
822 * isTemplate - Simply returns the is_template flag from the database.
824 * @return bool is_template.
826 function isTemplate() {
827 return $this->data_array['is_template'];
831 * setAsTemplate - Set the template status of a project
833 * @param bool $booleanparam is_template.
836 function setAsTemplate($booleanparam) {
838 $booleanparam = $booleanparam ? 1 : 0;
839 $res = db_query_params('UPDATE groups SET is_template=$1 WHERE group_id=$2',
840 array($booleanparam, $this->getID()));
842 $this->data_array['is_template'] = $booleanparam;
852 * getTemplateProject - Return the project template this project is built from
854 * @return object The template project
856 function getTemplateProject() {
857 return group_get_object($this->data_array['built_from_template']);
861 * getUnixName - the unix_name
863 * @return string unix_name.
865 function getUnixName() {
866 return strtolower($this->data_array['unix_group_name']);
870 * getPublicName - the full-length public name.
872 * @return string The group_name.
874 function getPublicName() {
875 return $this->data_array['group_name'];
879 * getRegisterPurpose - the text description of the purpose of this project.
881 * @return string The description.
883 function getRegisterPurpose() {
884 return $this->data_array['register_purpose'];
888 * getDescription - the text description of this project.
890 * @return string The description.
892 function getDescription() {
893 return $this->data_array['short_description'];
897 * getStartDate - the unix time this project was registered.
899 * @return int (unix time) of registration.
901 function getStartDate() {
902 return $this->data_array['register_time'];
906 * getLogoImageID - the id of the logo in the database for this project.
908 * @return int The ID of logo image in db_images table (or 100 if none).
910 function getLogoImageID() {
911 if (!isset($this->data_array['logo_image_id'])) {
912 $res = db_query_params('select id from db_images where group_id = $1 and is_logo = $2',
913 array($this->getID(), 1));
914 if ($res && db_numrows($res)) {
915 $this->data_array['logo_image_id'] = db_result($res, 0, 'id');
917 $this->data_array['logo_image_id'] = null;
920 return $this->data_array['logo_image_id'];
924 * getUnixBox - the hostname of the unix box where this project is located.
926 * @return string The name of the unix machine for the group.
928 function getUnixBox() {
929 return $this->data_array['unix_box'];
933 * getSCMBox - the hostname of the scm box where this project is located.
935 * @return string The name of the unix machine for the group.
937 function getSCMBox() {
938 return $this->data_array['scm_box'];
941 * setSCMBox - the hostname of the scm box where this project is located.
943 * @param string $scm_box The name of the new SCM_BOX
946 function setSCMBox($scm_box) {
948 if ($scm_box == $this->data_array['scm_box']) {
953 $res = db_query_params('UPDATE groups SET scm_box=$1 WHERE group_id=$2', array($scm_box, $this->getID()));
955 $this->addHistory('scm_box', $this->data_array['scm_box']);
956 $this->data_array['scm_box'] = $scm_box;
961 $this->setError(_("Could not insert SCM_BOX to database"));
965 $this->setError(_("SCM Box cannot be empty"));
971 * getDomain - the hostname.domain where their web page is located.
973 * @return string The name of the group [web] domain.
975 function getDomain() {
976 return $this->data_array['http_domain'];
980 * getRegistrationPurpose - the text description of the purpose of this project.
982 * @return string The application for project hosting.
984 function getRegistrationPurpose() {
985 return $this->data_array['register_purpose'];
989 * getAdmins - Get array of Admin user objects.
991 * @return array Array of User objects.
993 function &getAdmins() {
994 $roles = RBACEngine::getInstance()->getRolesByAllowedAction ('project_admin', $this->getID());
998 foreach ($roles as $role) {
999 if (! ($role instanceof RoleExplicit)) {
1002 if ($role->getHomeProject() == NULL
1003 || $role->getHomeProject()->getID() != $this->getID()) {
1007 foreach ($role->getUsers() as $u) {
1008 $user_ids[] = $u->getID();
1011 $active_ids = array();
1012 $ids = array_unique ($user_ids);
1013 foreach ($ids as $id) {
1014 $u = user_get_object ($id);
1015 if ($u->isActive()) {
1023 Common Group preferences for tools
1027 * enableAnonSCM - whether or not this group has opted to enable Anonymous SCM.
1029 * @return boolean enable_scm.
1031 function enableAnonSCM() {
1032 $r = RoleAnonymous::getInstance();
1033 return $r->hasPermission('scm', $this->getID(), 'read');
1036 function SetUsesAnonSCM($booleanparam) {
1038 $booleanparam = $booleanparam ? 1 : 0;
1039 $r = RoleAnonymous::getInstance();
1040 $r->setSetting('scm', $this->getID(), $booleanparam);
1045 * enablePserver - whether or not this group has opted to enable Pserver.
1047 * @return bool enable_pserver.
1049 function enablePserver() {
1050 if ($this->usesSCM()) {
1051 return $this->data_array['enable_pserver'];
1057 function SetUsesPserver($booleanparam) {
1059 $booleanparam = $booleanparam ? 1 : 0;
1060 $res = db_query_params('UPDATE groups SET enable_pserver=$1 WHERE group_id=$2',
1061 array($booleanparam, $this->getID()));
1063 $this->data_array['enable_pserver'] = $booleanparam;
1073 * usesSCM - whether or not this group has opted to use SCM.
1075 * @return bool uses_scm.
1077 function usesSCM() {
1078 if (forge_get_config('use_scm')) {
1079 return $this->data_array['use_scm'];
1086 * setUseSCM - Set the SCM usage
1088 * @param bool $booleanparam enabled/disabled
1091 function setUseSCM($booleanparam) {
1093 $booleanparam = $booleanparam ? 1 : 0;
1094 $res = db_query_params('UPDATE groups SET use_scm=$1 WHERE group_id=$2',
1095 array($booleanparam, $this->getID()));
1097 $this->data_array['use_scm'] = $booleanparam;
1107 * usesMail - whether or not this group has opted to use mailing lists.
1109 * @return bool uses_mail.
1111 function usesMail() {
1112 if (forge_get_config('use_mail')) {
1113 return $this->data_array['use_mail'];
1118 $hook_params = array();
1119 $hook_params['group'] = $this;
1120 $hook_params['group_id'] = $this->getID();
1121 $hook_params['group_homepage'] = $this->getHomePage();
1122 $hook_params['group_name'] = $this->getPublicName();
1123 $hook_params['group_description'] = $this->getDescription();
1124 plugin_hook ("group_update", $hook_params);
1128 * setUseMail - Set the mailing-list usage
1130 * @param bool $booleanparam enabled/disabled
1133 function setUseMail($booleanparam) {
1135 $booleanparam = $booleanparam ? 1 : 0;
1136 $res = db_query_params('UPDATE groups SET use_mail=$1 WHERE group_id=$2',
1137 array($booleanparam, $this->getID()));
1139 $this->data_array['use_mail'] = $booleanparam;
1149 * usesNews - whether or not this group has opted to use news.
1151 * @return bool uses_news.
1153 function usesNews() {
1154 if (forge_get_config('use_news')) {
1155 return $this->data_array['use_news'];
1161 function setUseNews($booleanparam) {
1163 $booleanparam = $booleanparam ? 1 : 0;
1164 $res = db_query_params('UPDATE groups SET use_news=$1 WHERE group_id=$2',
1165 array($booleanparam, $this->getID()));
1167 $this->data_array['use_news'] = $booleanparam;
1177 * usesActivity - whether or not this group has opted to display Project Activities.
1179 * @return bool uses_activities.
1181 function usesActivity() {
1182 if (forge_get_config('use_activity')) {
1183 return $this->data_array['use_activity'];
1189 function setUseActivity($booleanparam) {
1191 $booleanparam = $booleanparam ? 1 : 0;
1192 $res = db_query_params('UPDATE groups SET use_activity=$1 WHERE group_id=$2',
1193 array($booleanparam, $this->getID()));
1195 $this->data_array['use_activity'] = $booleanparam;
1205 * usesForum - whether or not this group has opted to use discussion forums.
1207 * @return bool uses_forum.
1209 function usesForum() {
1210 if (forge_get_config('use_forum')) {
1211 return $this->data_array['use_forum'];
1218 * setUseForum - Set the forum usage
1220 * @param bool $booleanparam enabled/disabled
1223 function setUseForum($booleanparam) {
1225 $booleanparam = $booleanparam ? 1 : 0;
1226 $res = db_query_params('UPDATE groups SET use_forum=$1 WHERE group_id=$2',
1227 array($booleanparam, $this->getID()));
1229 $this->data_array['use_forum'] = $booleanparam;
1239 * usesStats - whether or not this group has opted to use stats.
1241 * @return bool uses_stats.
1243 function usesStats() {
1244 return $this->data_array['use_stats'];
1248 * usesFRS - whether or not this group has opted to use file release system.
1250 * @return bool uses_frs.
1252 function usesFRS() {
1253 if (forge_get_config('use_frs')) {
1254 return $this->data_array['use_frs'];
1261 * setUseFRS - Set the FRS usage
1263 * @param bool $booleanparam enabled/disabled
1266 function setUseFRS($booleanparam) {
1268 $booleanparam = $booleanparam ? 1 : 0;
1269 $res = db_query_params('UPDATE groups SET use_frs=$1 WHERE group_id=$2',
1270 array($booleanparam, $this->getID()));
1272 $this->data_array['use_frs']=$booleanparam;
1282 * usesTracker - whether or not this group has opted to use tracker.
1284 * @return bool uses_tracker.
1286 function usesTracker() {
1287 if (forge_get_config('use_tracker')) {
1288 return $this->data_array['use_tracker'];
1295 * setUseTracker - Set the tracker usage
1297 * @param bool $booleanparam enabled/disabled
1300 function setUseTracker($booleanparam) {
1302 $booleanparam = $booleanparam ? 1 : 0;
1303 $res = db_query_params ('UPDATE groups SET use_tracker=$1 WHERE group_id=$2',
1304 array($booleanparam, $this->getID()));
1306 $this->data_array['use_tracker']=$booleanparam;
1316 * useCreateOnline - whether or not this group has opted to use create online documents option.
1318 * @return bool use_docman_create_online.
1320 function useCreateOnline() {
1321 if (forge_get_config('use_docman')) {
1322 return $this->data_array['use_docman_create_online'];
1329 * usesDocman - whether or not this group has opted to use docman.
1331 * @return bool use_docman.
1333 function usesDocman() {
1334 if (forge_get_config('use_docman')) {
1335 return $this->data_array['use_docman'];
1342 * setUseDocman - Set the docman usage
1344 * @param bool $booleanparam enabled/disabled
1347 function setUseDocman($booleanparam) {
1349 $booleanparam = $booleanparam ? 1 : 0;
1350 $res = db_query_params('UPDATE groups SET use_docman = $1 WHERE group_id = $2',
1351 array($booleanparam, $this->getID()));
1353 // check if / doc_group exists, if not create it
1354 $trashdir = db_query_params('select groupname from doc_groups where groupname = $1 and group_id = $2',
1355 array('.trash', $this->getID()));
1356 if ($trashdir && db_numrows($trashdir) == 0) {
1357 $resinsert = db_query_params('insert into doc_groups (groupname, group_id, stateid) values ($1, $2, $3)',
1358 array('.trash', $this->getID(), '2'));
1364 $this->data_array['use_docman'] = $booleanparam;
1374 * useDocmanSearch - whether or not this group has opted to use docman search engine.
1376 * @return bool use_docman_search.
1378 function useDocmanSearch() {
1379 if (forge_get_config('use_docman')) {
1380 return $this->data_array['use_docman_search'];
1387 * useWebdav - whether or not this group has opted to use webdav interface.
1389 * @return bool use_docman_search.
1391 function useWebdav() {
1392 if (forge_get_config('use_webdav')) {
1393 return $this->data_array['use_webdav'];
1400 * usesFTP - whether or not this group has opted to use FTP.
1402 * @return bool uses_ftp.
1404 function usesFTP() {
1405 if (forge_get_config('use_ftp')) {
1406 return $this->data_array['use_ftp'];
1413 * usesSurvey - whether or not this group has opted to use surveys.
1415 * @return bool uses_survey.
1417 function usesSurvey() {
1418 if (forge_get_config('use_survey')) {
1419 return $this->data_array['use_survey'];
1426 * usesPM - whether or not this group has opted to Project Manager.
1428 * @return bool uses_projman.
1431 if (forge_get_config('use_pm')) {
1432 return $this->data_array['use_pm'];
1439 * setUsePM - Set the PM usage
1441 * @param bool $booleanparam enabled/disabled
1444 function setUsePM($booleanparam) {
1446 $booleanparam = $booleanparam ? 1 : 0;
1447 $res = db_query_params('UPDATE groups SET use_pm=$1 WHERE group_id=$2',
1448 array($booleanparam, $this->getID()));
1450 $this->data_array['use_pm']=$booleanparam;
1460 * getPlugins - get a list of all available group plugins
1462 * @return array array containing plugin_id => plugin_name
1464 function getPlugins() {
1465 if (!isset($this->plugins_data)) {
1466 $this->plugins_data = array();
1467 $res = db_query_params('SELECT group_plugin.plugin_id, plugins.plugin_name
1468 FROM group_plugin, plugins
1469 WHERE group_plugin.group_id=$1
1470 AND group_plugin.plugin_id=plugins.plugin_id', array($this->getID()));
1471 $rows = db_numrows($res);
1473 for ($i=0; $i<$rows; $i++) {
1474 $plugin_id = db_result($res, $i, 'plugin_id');
1475 $this->plugins_data[$plugin_id] = db_result($res, $i, 'plugin_name');
1478 return $this->plugins_data;
1482 * usesPlugin - returns true if the group uses a particular plugin
1484 * @param string $pluginname name of the plugin
1485 * @return bool whether plugin is being used or not
1487 function usesPlugin($pluginname) {
1488 $plugins_data = $this->getPlugins();
1489 foreach ($plugins_data as $p_id => $p_name) {
1490 if ($p_name == $pluginname) {
1498 * added for Codendi compatibility
1499 * usesServices - returns true if the group uses a particular plugin or feature
1501 * @param string $feature name of the plugin
1502 * @return bool whether plugin is being used or not
1504 function usesService($feature) {
1505 $plugins_data = $this->getPlugins();
1506 $pm = plugin_manager_get_object();
1507 foreach ($plugins_data as $p_id => $p_name) {
1508 if ($p_name == $feature) {
1511 if ($pm->getPluginByName($p_name)->provide($feature)) {
1519 * setPluginUse - enables/disables plugins for the group
1521 * @param string $pluginname name of the plugin
1522 * @param bool $val the new state
1523 * @return string database result
1525 function setPluginUse($pluginname, $val=true) {
1526 if ($val == $this->usesPlugin($pluginname)) {
1527 // State is already good, returning
1530 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1531 array($pluginname));
1532 $rows = db_numrows($res);
1534 // Error: no plugin by that name
1537 $plugin_id = db_result($res,0,'plugin_id');
1539 unset($this->plugins_data);
1541 $res = db_query_params('INSERT INTO group_plugin (group_id, plugin_id) VALUES ($1, $2)',
1542 array($this->getID(),
1545 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1 AND plugin_id=$2',
1546 array($this->getID(),
1549 $this->normalizeAllRoles();
1550 $hook_params = array();
1551 $hook_params['group_id'] = $this->getID();
1552 $hook_params['val'] = $val;
1553 plugin_hook("group_plugin_use", $hook_params);
1558 * getDocEmailAddress - get email address(es) to send doc notifications to.
1560 * @return string email address.
1562 function getDocEmailAddress() {
1563 return $this->data_array['new_doc_address'];
1566 function setDocEmailAddress($email) {
1567 $invalid_mails = validate_emails($email);
1568 if (count($invalid_mails) > 0) {
1569 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
1573 $res = db_query_params('UPDATE groups SET new_doc_address = $1 WHERE group_id = $2',
1574 array($email, $this->getID()));
1577 $this->setError(_('Error')._(': ')._('Cannot Update Group new_doc_address')._(': ').db_error());
1581 $this->data_array['new_doc_address'] = $email;
1588 * docEmailAll - whether or not this group has opted to use receive notices on all doc updates.
1590 * @return bool email_on_all_doc_updates.
1592 function docEmailAll() {
1593 return $this->data_array['send_all_docs'];
1596 function setDocEmailAll($status) {
1598 $res = db_query_params('UPDATE groups SET send_all_docs = $1 WHERE group_id = $2',
1599 array($status, $this->getID()));
1602 $this->setError(_('Error')._(': ')._('Cannot Update Group send_all_docs')._(': ').db_error());
1606 $this->data_array['send_all_docs'] = $status;
1613 * getFRSEmailAddress - get email address(es) to send FRS notifications to.
1615 * @return string email address.
1617 function getFRSEmailAddress() {
1618 return $this->data_array['new_frs_address'];
1622 * frsEmailAll - whether or not this group has opted to use receive notices on all frs updates.
1624 * @return bool email_on_all_frs_updates.
1626 function frsEmailAll() {
1627 return $this->data_array['send_all_frs'];
1631 * getHomePage - The URL for this project's home page.
1633 * @return string homepage URL.
1635 function getHomePage() {
1636 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9+.-]*:/",
1637 $this->data_array['homepage'])) {
1638 $this->data_array['homepage'] = 'http://' .
1639 $this->data_array['homepage'];
1641 return $this->data_array['homepage'];
1645 * setHomepage - the hostname of the website url where this project is located.
1647 * @param string $homepage The name of the new HOMEPAGE
1650 function setHomepage($homepage) {
1652 if ($homepage == $this->data_array['homepage']) {
1657 $res = db_query_params('UPDATE groups SET homepage=$1 WHERE group_id=$2', array($homepage, $this->getID()));
1659 $this->addHistory('homepage', $this->data_array['homepage']);
1660 $this->data_array['homepage'] = $homepage;
1665 $this->setError(_('Could not insert homepage to database'));
1669 $this->setError(_('Homepage cannot be empty'));
1675 * getTags - Tags of this project.
1677 * @return string List of tags. Comma separated
1679 function getTags() {
1680 $sql = 'SELECT name FROM project_tags WHERE group_id = $1';
1681 $res = db_query_params($sql, array($this->getID()));
1682 return join(', ', util_result_column_to_array($res));
1686 * setTags - Set tags of this project.
1688 * @param string $tags
1689 * @return string database result.
1691 function setTags($tags) {
1693 $sql = 'DELETE FROM project_tags WHERE group_id=$1';
1694 $res = db_query_params($sql, array($this->getID()));
1696 $this->setError(_('Deleting old tags')._(': ').db_error());
1700 $inserted = array();
1701 $tags_array = preg_split('/[;,]/', $tags);
1702 foreach ($tags_array as $tag) {
1703 $tag = preg_replace('/[\t\r\n]/', ' ', $tag);
1704 // Allowed caracteres: [A-Z][a-z][0-9] -_&'#+.
1705 if (preg_match('/[^[:alnum:]| |\-|_|\&|\'|#|\+|\.]/', $tag)) {
1706 $this->setError(_('Bad tag name, you only can use the following characters: [A-Z][a-z][0-9]-_&\'#+. and space'));
1711 if ($tag == '' || array_search($tag, $inserted) !== false) {
1714 $sql = 'INSERT INTO project_tags (group_id,name) VALUES ($1, $2)';
1715 $res = db_query_params($sql, array($this->getID(), $tag));
1717 $this->setError(_('Setting tags')._(': ').db_error());
1728 * getPermission - Return a Permission for this Group
1730 * @return object The Permission.
1732 function &getPermission() {
1733 return permission_get_object($this);
1736 function delete($sure, $really_sure, $really_really_sure) {
1737 if (!$sure || !$really_sure || !$really_really_sure) {
1738 $this->setMissingParamsError(_('Please tick all checkboxes.'));
1741 if ($this->getID() == forge_get_config('news_group') ||
1742 $this->getID() == 1 ||
1743 $this->getID() == forge_get_config('stats_group') ||
1744 $this->getID() == forge_get_config('peer_rating_group')) {
1745 $this->setError(_('Cannot Delete System Group'));
1748 $perm = $this->getPermission();
1749 if (!$perm || !is_object($perm)) {
1750 $this->setPermissionDeniedError();
1752 } elseif ($perm->isError() || !$perm->isSuperUser()) {
1753 $this->setPermissionDeniedError();
1759 // Remove all the members
1761 $members = $this->getMembers(false);
1762 foreach ($members as $i) {
1763 if(!$this->removeUser($i->getID())) {
1764 $this->setError(_('Could not properly remove member')._(': ').$i->getID());
1769 // unlink roles from this project
1770 foreach ($this->getRoles() as $r) {
1771 if ($r->getHomeProject() == NULL
1772 || $r->getHomeProject()->getID() != $this->getID()) {
1773 $r->unlinkProject($this);
1780 $atf = new ArtifactTypeFactory($this, true);
1781 $at_arr = $atf->getArtifactTypes();
1782 foreach ($at_arr as $i) {
1783 if (!is_object($i)) {
1786 if (!$i->delete(1,1)) {
1787 $this->setError(_('Could not properly delete the tracker')._(': ').$i->getErrorMessage());
1794 $rmf = new RoadmapFactory($this);
1795 $rm_arr = $rmf->getRoadmaps();
1796 foreach ($rm_arr as $i) {
1797 if (!is_object($i)) {
1800 if (!$i->delete()) {
1801 $this->setError(_('Could not properly delete the roadmap')._(': ').$i->getErrorMessage());
1809 $ff = new ForumFactory($this, true);
1810 $f_arr = $ff->getForums();
1811 foreach ($f_arr as $i) {
1812 if (!is_object($i)) {
1815 if(!$i->delete(1,1)) {
1816 $this->setError(_('Could not properly delete the forum')._(': ').$i->getErrorMessage());
1822 // Delete Subprojects
1824 $pgf = new ProjectGroupFactory($this, true);
1825 $pg_arr = $pgf->getProjectGroups();
1826 foreach ($pg_arr as $i) {
1827 if (!is_object($i)) {
1830 if (!$i->delete(1,1)) {
1831 $this->setError(_('Could not properly delete the ProjectGroup')._(': ').$i->getErrorMessage());
1837 // Delete FRS Packages
1839 $res = db_query_params('SELECT * FROM frs_package WHERE group_id=$1',
1840 array($this->getID()));
1842 $this->setError(_('Error FRS Packages')._(': ').db_error());
1847 while ($arr = db_fetch_array($res)) {
1848 $frsp=new FRSPackage($this, $arr['package_id'], $arr);
1849 if (!$frsp->delete(1, 1)) {
1850 $this->setError(_('Could not properly delete the FRSPackage')._(': ').$frsp->getErrorMessage());
1857 $news_group=group_get_object(forge_get_config('news_group'));
1858 $res = db_query_params('SELECT forum_id FROM news_bytes WHERE group_id=$1',
1859 array($this->getID()));
1861 $this->setError(_('Error Deleting News')._(': ').db_error());
1866 for ($i=0; $i<db_numrows($res); $i++) {
1867 $Forum = new Forum($news_group,db_result($res,$i,'forum_id'));
1868 if (!$Forum->delete(1,1)) {
1869 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1874 // Delete news forums in group itself
1875 for ($i = 0; $i < db_numrows($res); $i++) {
1876 $Forum = new Forum($this, db_result($res, $i, 'forum_id'));
1877 if (!$Forum->delete(1, 1)) {
1878 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1883 $res = db_query_params('DELETE FROM news_bytes WHERE group_id=$1',
1884 array($this->getID()));
1886 $this->setError(_('Error Deleting News')._(': ').db_error());
1894 $res = db_query_params('DELETE FROM doc_data WHERE group_id=$1',
1895 array($this->getID()));
1897 $this->setError(_('Error Deleting Documents')._(': ').db_error());
1902 $res = db_query_params('DELETE FROM doc_groups WHERE group_id=$1',
1903 array($this->getID()));
1905 $this->setError(_('Error Deleting Document Groups')._(': ').db_error());
1913 $res=db_query_params('DELETE FROM project_tags WHERE group_id=$1', array($this->getID()));
1915 $this->setError(_('Error Deleting Tags')._(': ').db_error());
1921 // Delete group history
1923 $res = db_query_params('DELETE FROM group_history WHERE group_id=$1',
1924 array($this->getID()));
1926 $this->setError(_('Error Deleting Project History')._(': ').db_error());
1932 // Delete group plugins
1934 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1',
1935 array($this->getID()));
1937 $this->setError(_('Error Deleting Project Plugins')._(': ').db_error());
1943 // Delete group cvs stats
1945 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE group_id=$1',
1946 array($this->getID()));
1948 $this->setError(_('Error Deleting SCM Statistics')._(': ').db_error());
1956 $sf = new SurveyFactory($this, true);
1957 $s_arr =& $sf->getSurveys();
1958 foreach ($s_arr as $i) {
1959 if (!is_object($i)) {
1962 if (!$i->delete()) {
1963 $this->setError(_('Could not properly delete the survey'));
1968 // Delete SurveyQuestions
1970 $sqf = new SurveyQuestionFactory($this);
1971 $sq_arr = $sqf->getSurveyQuestions();
1972 if (is_array($sq_arr)) {
1973 foreach ($sq_arr as $i) {
1974 if (!is_object($i)) {
1977 if (!$i->delete()) {
1978 $this->setError(_('Could not properly delete the survey questions'));
1986 // Delete Mailing List Factory
1988 $mlf = new MailingListFactory($this, true);
1989 $ml_arr = $mlf->getMailingLists();
1990 foreach ($ml_arr as $i) {
1991 if (!is_object($i)) {
1994 if (!$i->delete(1,1)) {
1995 $this->setError(_('Could not properly delete the mailing list'));
2003 $res = db_query_params('DELETE FROM trove_group_link WHERE group_id=$1',
2004 array($this->getID()));
2006 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2011 $res = db_query_params('DELETE FROM trove_agg WHERE group_id=$1',
2012 array($this->getID()));
2014 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2022 $res = db_query_params('DELETE FROM project_sums_agg WHERE group_id=$1',
2023 array($this->getID()));
2025 $this->setError(_('Error Deleting Counters')._(': ').db_error());
2030 $res = db_query_params('INSERT INTO deleted_groups (unix_group_name, delete_date, isdeleted) VALUES ($1, $2, $3)',
2031 array($this->getUnixName(),
2035 $this->setError(_('Error Deleting Project')._(': ').db_error());
2040 // Remove users & delete roles from this project
2041 $members = $this->getMembers();
2042 foreach ($members as $userObject) {
2043 $this->removeUser($userObject->getID());
2045 $localRolesId = $this->getRolesId(false);
2046 foreach ($localRolesId as $localRoleId) {
2047 $roleObject = new Role($this, $localRoleId);
2048 $roleObject->delete();
2050 // Delete entry in groups.
2051 $res = db_query_params('DELETE FROM groups WHERE group_id=$1',
2052 array($this->getID()));
2054 $this->setError(_('Error Deleting Project')._(': ').db_error());
2061 $hook_params = array();
2062 $hook_params['group'] = $this;
2063 $hook_params['group_id'] = $this->getID();
2064 plugin_hook("group_delete", $hook_params);
2066 if (forge_get_config('upload_dir') != '' && $this->getUnixName()) {
2067 exec('/bin/rm -rf '.forge_get_config('upload_dir').'/'.$this->getUnixName().'/');
2069 if (forge_get_config('ftp_upload_dir') != '' && $this->getUnixName()) {
2070 exec('/bin/rm -rf '.forge_get_config('ftp_upload_dir').'/'.$this->getUnixName().'/');
2075 db_query_params('DELETE FROM rep_group_act_monthly WHERE group_id=$1',
2076 array($this->getID()));
2077 //echo 'rep_group_act_monthly'.db_error();
2078 db_query_params('DELETE FROM rep_group_act_weekly WHERE group_id=$1',
2079 array($this->getID()));
2080 //echo 'rep_group_act_weekly'.db_error();
2081 db_query_params('DELETE FROM rep_group_act_daily WHERE group_id=$1',
2082 array($this->getID()));
2083 //echo 'rep_group_act_daily'.db_error();
2084 unset($this->data_array);
2089 Basic functions to add/remove users to/from a group
2090 and update their permissions
2094 * addUser - controls adding a user to a group.
2096 * @param string $user_identifier Unix name of the user to add OR integer user_id.
2097 * @param int $role_id The role_id this user should have.
2098 * @return bool success.
2101 function addUser($user_identifier, $role_id) {
2104 Admins can add users to groups
2107 if (!forge_check_perm ('project_admin', $this->getID())) {
2108 $this->setPermissionDeniedError();
2114 get user id for this user's unix_name
2116 if (is_int ($user_identifier)) { // user_id or user_name
2117 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_id=$1', array($user_identifier));
2119 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_name=$1', array($user_identifier));
2121 if (db_numrows($res_newuser) > 0) {
2123 // make sure user is active
2125 if (db_result($res_newuser,0,'status') != 'A') {
2126 $this->setError(_('User is not active. Only active users can be added.'));
2132 // user was found - set new user_id var
2134 $user_id = db_result($res_newuser,0,'user_id');
2136 $role = new Role($this, $role_id);
2137 if (!$role || !is_object($role)) {
2138 $this->setError(_('Error Getting Role Object'));
2141 } elseif ($role->isError()) {
2142 $this->setError('addUser::roleget::'.$role->getErrorMessage());
2147 $role->addUser(user_get_object($user_id));
2148 if (!$SYS->sysCheckCreateGroup($this->getID())){
2149 $this->setError($SYS->getErrorMessage());
2153 if (!$SYS->sysCheckCreateUser($user_id)) {
2154 $this->setError($SYS->getErrorMessage());
2158 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2159 $this->setError($SYS->getErrorMessage());
2165 // user doesn't exist
2167 $this->setError(_('That user does not exist.'));
2172 $hook_params['group'] = $this;
2173 $hook_params['group_id'] = $this->getID();
2174 $hook_params['user'] = user_get_object($user_id);
2175 $hook_params['user_id'] = $user_id;
2176 plugin_hook ("group_adduser", $hook_params);
2181 $this->addHistory(_('Added User'), $user_identifier);
2187 $add_u = user_get_object($user_id);
2189 foreach ($this->membersArr as $u) {
2190 if ($u->getID() == $add_u->getID()) {
2196 $this->membersArr[] = $add_u;
2202 * removeUser - controls removing a user from a group.
2204 * Users can remove themselves.
2206 * @param int $user_id The ID of the user to remove.
2207 * @return bool success.
2209 function removeUser($user_id) {
2212 if ($user_id != user_getid()
2213 && !forge_check_perm('project_admin', $this->getID())) {
2214 $this->setPermissionDeniedError();
2220 $user = user_get_object($user_id);
2221 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
2222 $found_roles = array();
2223 foreach ($roles as $role) {
2224 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2225 $found_roles[] = $role;
2228 if (count($found_roles) == 0) {
2229 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2233 foreach ($found_roles as $found_role) {
2234 $found_role->removeUser($user);
2235 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
2236 $this->setError($SYS->getErrorMessage());
2243 // reassign open artifacts to id=100
2245 $res = db_query_params('UPDATE artifact SET assigned_to=100
2246 WHERE group_artifact_id
2247 IN (SELECT group_artifact_id
2248 FROM artifact_group_list
2249 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
2250 array($this->getID(),
2253 $this->setError(_('Error')._(': ')._('artifact')._(': ').db_error());
2259 // reassign open tasks to id=100
2260 // first have to purge any assignments that would cause
2261 // conflict with existing assignment to 100
2263 $res = db_query_params('DELETE FROM project_assigned_to
2264 WHERE project_task_id IN (SELECT pt.project_task_id
2265 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2266 WHERE pt.group_project_id = pgl.group_project_id
2267 AND pat.project_task_id=pt.project_task_id
2268 AND pt.status_id=1 AND pgl.group_id=$1
2269 AND pat.assigned_to_id=$2)
2270 AND assigned_to_id=100',
2271 array($this->getID(),
2274 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 1, db_error()));
2278 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2279 WHERE project_task_id IN (SELECT pt.project_task_id
2280 FROM project_task pt, project_group_list pgl
2281 WHERE pt.group_project_id = pgl.group_project_id
2282 AND pt.status_id=1 AND pgl.group_id=$1)
2283 AND assigned_to_id=$2',
2284 array($this->getID(),
2287 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 2, db_error()));
2293 // Remove user from system
2295 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2296 $this->setError($SYS->getErrorMessage());
2301 $hook_params['group'] = $this;
2302 $hook_params['group_id'] = $this->getID();
2303 $hook_params['user'] = user_get_object($user_id);
2304 $hook_params['user_id'] = $user_id;
2305 plugin_hook("group_removeuser", $hook_params);
2308 $this->addHistory(_('Removed User'), $user_id);
2315 $del_u = user_get_object($user_id);
2316 foreach ($this->membersArr as $k => $u) {
2317 if ($u->getID() == $del_u->getID()) {
2318 unset($this->membersArr[$k]);
2327 * updateUser - controls updating a user's role in this group.
2329 * @param int $user_id The ID of the user.
2330 * @param int $role_id The role_id to set this user to.
2331 * @return bool success.
2333 function updateUser($user_id, $role_id) {
2335 if (!forge_check_perm ('project_admin', $this->getID())) {
2336 $this->setPermissionDeniedError();
2340 $newrole = RBACEngine::getInstance()->getRoleById ($role_id);
2341 if (!$newrole || !is_object($newrole)) {
2342 $this->setError(_('Could Not Get Role'));
2344 } elseif ($newrole->isError()) {
2345 $this->setError(_('Role')._(': ').$role->getErrorMessage());
2347 } elseif ($newrole->getHomeProject() == NULL
2348 || $newrole->getHomeProject()->getID() != $this->getID()) {
2349 $this->setError(_('Wrong destination role'));
2352 $user = user_get_object ($user_id);
2353 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user);
2355 foreach ($roles as $role) {
2356 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2357 $found_role = $role;
2361 if ($found_role == NULL) {
2362 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2366 $found_role->removeUser ($user);
2367 $newrole->addUser ($user);
2369 $this->addHistory(_('Updated User'), $user_id);
2374 * addHistory - Makes an audit trail entry for this project.
2376 * @param string $field_name The name of the field.
2377 * @param string $old_value The Old Value for this $field_name.
2378 * @return resource database result handle.
2381 function addHistory($field_name, $old_value) {
2382 if ($old_value == NULL) {
2386 return db_query_params('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2387 VALUES ($1,$2,$3,$4,$5)',
2388 array($this->getID(),
2396 * activateUsers - Make sure that group members have unix accounts.
2398 * Setup unix accounts for group members. Can be called even
2399 * if members are already active.
2403 function activateUsers() {
2405 Activate member(s) of the project
2410 $members = $this->getUsers(true);
2412 foreach ($members as $member) {
2413 $user_id = $member->getID();
2415 if (!$SYS->sysCheckCreateGroup($this->getID())){
2416 $this->setError($SYS->getErrorMessage());
2420 if (!$SYS->sysCheckCreateUser($user_id)) {
2421 $this->setError($SYS->getErrorMessage());
2425 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2426 $this->setError($SYS->getErrorMessage());
2436 * getMembers - returns array of User objects for this project
2438 * @param boolean $onlyactive Only users with state active, or all users of group
2439 * @return array of User objects for this group.
2441 function getMembers($onlyactive = true) {
2442 return $this->getUsers(true, $onlyactive);
2446 * replaceTemplateStrings - fill-in some blanks with project name
2448 * @param string $string Template string
2449 * @return string String after replacements
2451 function replaceTemplateStrings($string) {
2452 $string = str_replace('UNIXNAME', $this->getUnixName(), $string);
2453 $string = str_replace('PUBLICNAME', $this->getPublicName(), $string);
2454 $string = str_replace('DESCRIPTION', $this->getDescription(), $string);
2459 * approve - Approve pending project.
2461 * @param object $user The User object who is doing the updating.
2465 function approve(&$user) {
2466 global $gfcommon,$gfwww;
2467 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2469 if ($this->getStatus()=='A') {
2470 $this->setError(_('Group already active'));
2476 // Step 1: Activate group and create LDAP entries
2477 if (!$this->setStatus($user, 'A')) {
2484 // Switch to system language for item creation
2485 setup_gettext_from_sys_lang();
2487 // Create default roles
2488 $idadmin_group = NULL;
2489 foreach (get_group_join_requests ($this) as $gjr) {
2490 $idadmin_group = $gjr->getUserID();
2493 if ($idadmin_group == NULL) {
2494 $idadmin_group = $user->getID();
2497 $template = $this->getTemplateProject();
2498 $id_mappings = array();
2499 $seen_admin_role = false;
2501 // Copy roles from template project
2502 foreach($template->getRoles() as $oldrole) {
2503 if ($oldrole->getHomeProject() != NULL) {
2504 $role = new Role($this);
2506 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2507 $role->create('TEMPORARY ROLE NAME', $data, true);
2508 $role->setName($oldrole->getName());
2509 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2510 $seen_admin_role = true;
2514 $role->linkProject($this);
2516 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2517 // Reuse the project_admin permission
2518 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID()));
2522 if (!$seen_admin_role) {
2523 $role = new Role($this);
2524 $adminperms = array('project_admin' => array ($this->getID() => 1));
2525 $role_id = $role->create ('Admin', $adminperms, true);
2528 $roles = $this->getRoles();
2529 foreach ($roles as $r) {
2530 if ($r->getHomeProject() == NULL) {
2533 if ($r->getSetting ('project_admin', $this->getID())) {
2534 $r->addUser(user_get_object ($idadmin_group));
2538 // Temporarily switch to the submitter's identity
2539 $saved_session = session_get_user();
2540 session_set_internal($idadmin_group);
2543 if (forge_get_config('use_tracker')) {
2544 $this->setUseTracker ($template->usesTracker());
2545 if ($template->usesTracker()) {
2546 $oldatf = new ArtifactTypeFactory($template);
2547 foreach ($oldatf->getArtifactTypes() as $o) {
2548 $t = new ArtifactType ($this);
2549 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions());
2550 $id_mappings['tracker'][$o->getID()] = $t->getID();
2555 if (forge_get_config('use_pm')) {
2556 $this->setUsePM ($template->usesPM());
2557 if ($template->usesPM()) {
2558 $oldpgf = new ProjectGroupFactory($template);
2559 foreach ($oldpgf->getProjectGroups() as $o) {
2560 $pg = new ProjectGroup($this);
2561 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2562 $id_mappings['pm'][$o->getID()] = $pg->getID();
2567 if (forge_get_config('use_forum')) {
2568 $this->setUseForum($template->usesForum());
2569 if ($template->usesForum()) {
2570 $oldff = new ForumFactory($template);
2571 foreach ($oldff->getForums() as $o) {
2572 $f = new Forum($this);
2573 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo(),1);
2574 $id_mappings['forum'][$o->getID()] = $f->getID();
2579 if (forge_get_config('use_docman')) {
2580 $this->setUseDocman($template->usesDocman());
2581 if ($template->usesDocman()) {
2582 $olddgf = new DocumentGroupFactory($template);
2583 // First pass: create all docgroups
2584 $id_mappings['docman_docgroup'][0] = 0;
2585 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2586 $ndg = new DocumentGroup($this);
2587 // .trash is a reserved directory
2588 if ($o->getName() != '.trash') {
2589 $ndg->create($this->replaceTemplateStrings($o->getName()), 0, 1, null, true);
2590 $id_mappings['docman_docgroup'][$o->getID()] = $ndg->getID();
2593 // Second pass: restore hierarchy links & stateid
2594 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2595 $ndgf = new DocumentGroup($this);
2596 if ($o->getName() != '.trash') {
2597 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2598 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()], 0, $o->getState());
2604 if (forge_get_config('use_frs')) {
2605 $this->setUseFRS ($template->usesFRS());
2606 if ($template->usesFRS()) {
2607 foreach (get_frs_packages($template) as $o) {
2608 $newp = new FRSPackage($this);
2609 $nname = $this->replaceTemplateStrings($o->getName());
2610 $newp->create($nname, $o->isPublic());
2611 $id_mappings['frs'][$o->getID()] = $newp->getID();
2612 foreach(get_frs_releases($o) as $or) {
2613 $newr = new FRSRelease($newp);
2614 $newr->create($this->replaceTemplateStrings($or->getName()), $this->replaceTemplateStrings($or->getNotes()), $this->replaceTemplateStrings($or->getChanges()), $or->getPreformatted());
2615 $id_mappings['frs_release'][$or->getID()] = $newr->getID();
2621 if (forge_get_config('use_mail')) {
2622 $this->setUseMail($template->usesMail());
2623 if ($template->usesMail()) {
2624 $oldmlf = new MailingListFactory($template);
2625 foreach ($oldmlf->getMailingLists() as $o) {
2626 $ml = new MailingList($this);
2627 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName());
2629 $ndescription = $this->replaceTemplateStrings($o->getDescription());
2630 $ml->create($nname, $ndescription, $o->isPublic());
2636 /* use SCM plugin from template group */
2637 $this->setUseSCM($template->usesSCM());
2639 foreach ($template->getPlugins() as
2640 $plugin_id => $plugin_name) {
2641 $this->setPluginUse($plugin_name);
2644 /* use SCM choice from registration page */
2645 foreach ($template->getPlugins() as $plugin_id => $plugin_name) {
2646 if (substr($plugin_name, 3) == 'scm' &&
2647 $plugin_name != 'scmhook') {
2648 /* skip copying scm plugins */
2651 /* enable other plugins though */
2652 $this->setPluginUse($plugin_name);
2656 foreach ($template->getRoles() as $oldrole) {
2657 $newrole = RBACEngine::getInstance()->getRoleById($id_mappings['role'][$oldrole->getID()]);
2658 if ($oldrole->getHomeProject() != NULL
2659 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2660 $newrole->setPublic ($oldrole->isPublic());
2662 $oldsettings = $oldrole->getSettingsForProject ($template);
2664 $sections = array('project_read', 'project_admin', 'scm', 'docman', 'tracker_admin', 'new_tracker', 'forum_admin', 'new_forum', 'pm_admin', 'new_pm', 'frs_admin', 'new_frs');
2665 foreach ($sections as $section) {
2666 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]);
2669 $sections = array('tracker', 'pm', 'forum', 'frs');
2670 foreach ($sections as $section) {
2671 if (isset ($oldsettings[$section])) {
2672 foreach ($oldsettings[$section] as $k => $v) {
2673 // Only copy perms for tools that have been copied
2674 if (isset ($id_mappings[$section][$k])) {
2675 $newrole->setSetting ($section,
2676 $id_mappings[$section][$k],
2684 $lm = new WidgetLayoutManager();
2685 $lm->createDefaultLayoutForProject($this->getID(), $template->getID());
2687 // second computation to clone fields and workflow
2688 if (forge_get_config('use_tracker')) {
2689 if ($template->usesTracker()) {
2690 $oldatf = new ArtifactTypeFactory($template);
2691 foreach ($oldatf->getArtifactTypes() as $o) {
2692 $t = artifactType_get_object($id_mappings['tracker'][$o->getID()]);
2693 $id_mappings['tracker'][$o->getID()] = $t->getID();
2694 $newEFIds = $t->cloneFieldsFrom($o->getID(), $id_mappings);
2695 if (forge_get_config('use_tracker_widget_display')) {
2696 $lm->createDefaultLayoutForTracker($t->getID(), $o->getID(), $newEFIds);
2703 $params['template'] = $template;
2704 $params['project'] = $this;
2705 $params['id_mappings'] = $id_mappings;
2706 plugin_hook_by_reference ('clone_project_from_template', $params);
2708 // Disable everything - except use_scm (manually set in the registration page)
2709 db_query_params ('UPDATE groups SET use_mail = 0, use_survey = 0, use_forum = 0, use_pm = 0, use_pm_depend_box = 0, use_news = 0,
2710 use_docman = 0, use_ftp = 0, use_tracker = 0, use_frs = 0, use_stats = 0 WHERE group_id = $1',
2711 array($this->getID()));
2714 $this->normalizeAllRoles();
2715 // empty members cache because the group creator is not yet in cache.
2716 unset($this->membersArr);
2717 $this->activateUsers();
2719 // Delete fake join request
2720 foreach (get_group_join_requests ($this) as $gjr) {
2724 // Switch back to user preference
2725 session_set_internal($saved_session->getID());
2726 setup_gettext_from_context();
2728 $this->sendApprovalEmail();
2729 $this->addHistory(_('Approved'), 'x');
2732 // Plugin can make approve operation there
2735 $params['group'] = $this;
2736 $params['group_id'] = $this->getID();
2737 plugin_hook('group_approved', $params);
2743 * sendApprovalEmail - Send new project email.
2745 * @return bool success.
2748 function sendApprovalEmail() {
2749 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID());
2751 if (count($admins) < 1) {
2752 $this->setError(_('Group does not have any administrators.'));
2756 // send one email per admin
2757 foreach ($admins as $admin) {
2758 setup_gettext_for_user ($admin);
2760 $message = sprintf(_('Your project registration for %4$s has been approved.
2762 Project Full Name: %1$s
2763 Project Unix Name: %2$s
2765 Your DNS will take up to a day to become active on our site.
2766 Your web site is accessible through your shell account. Please read
2767 site documentation (see link below) about intended usage, available
2768 services, and directory layout of the account.
2771 own project page in %4$s while logged in, you will find
2772 additional menu functions to your left labeled \'Project Admin\'.
2774 We highly suggest that you now visit %4$s and create a public
2775 description for your project. This can be done by visiting your project
2776 page while logged in, and selecting \'Project Admin\' from the menus
2777 on the left (or by visiting %3$s
2780 Your project will also not appear in the Trove Software Map (primary
2781 list of projects hosted on %4$s which offers great flexibility in
2782 browsing and search) until you categorize it in the project administration
2783 screens. So that people can find your project, you should do this now.
2784 Visit your project while logged in, and select \'Project Admin\' from the
2787 Enjoy the system, and please tell others about %4$s. Let us know
2788 if there is anything we can do to help you.
2791 htmlspecialchars_decode($this->getPublicName()),
2792 $this->getUnixName(),
2793 util_make_url ('/project/admin/?group_id='.$this->getID()),
2794 forge_get_config ('forge_name'));
2796 util_send_message($admin->getEmail(), sprintf(_('%s Project Approved'), forge_get_config ('forge_name')), $message);
2798 setup_gettext_from_context();
2805 * sendRejectionEmail - Send project rejection email.
2807 * This function sends out a rejection message to a user who
2808 * registered a project.
2810 * @param int $response_id The id of the response to use.
2811 * @param string $message The rejection message.
2812 * @return bool completion status.
2815 function sendRejectionEmail($response_id, $message = 'zxcv') {
2816 $submitters = array();
2817 foreach (get_group_join_requests ($this) as $gjr) {
2818 $submitters[] = user_get_object($gjr->getUserID());
2821 if (count ($submitters) < 1) {
2822 $this->setError(_('Group does not have any administrators.'));
2826 foreach ($submitters as $admin) {
2827 setup_gettext_for_user($admin);
2829 $response = sprintf(_('Your project registration for %s has been denied.'), forge_get_config('forge_name')) . "\n\n"
2830 . _('Project Full Name')._(': '). $this->getPublicName() . "\n"
2831 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2832 . _('Reasons for negative decision')._(': ') . "\n\n";
2834 // Check to see if they want to send a custom rejection response
2835 if ($response_id == 0) {
2836 $response .= $message;
2838 $response .= db_result(
2839 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array($response_id)),
2844 util_send_message($admin->getEmail(), sprintf(_('%s Project Denied'), forge_get_config('forge_name')), $response);
2845 setup_gettext_from_context();
2852 * sendNewProjectNotificationEmail - Send new project notification email.
2854 * This function sends out a notification email to the
2855 * SourceForge admin user when a new project is
2858 * @return bool success.
2861 function sendNewProjectNotificationEmail() {
2862 // Get the user who wants to register the project
2863 $submitters = array();
2864 foreach (get_group_join_requests ($this) as $gjr) {
2865 $submitters[] = user_get_object($gjr->getUserID());
2867 if (count ($submitters) < 1) {
2868 $this->setError(_('Could not find user who has submitted the project.'));
2872 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('approve_projects', -1);
2874 if (count($admins) < 1) {
2875 $this->setError(_('There is no administrator to send the mail to.'));
2879 foreach ($admins as $admin) {
2880 $admin_email = $admin->getEmail();
2881 setup_gettext_for_user ($admin);
2883 $message = sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')) . "\n\n"
2884 . _('Project Full Name')._(': ').htmlspecialchars_decode($this->getPublicName()) . "\n"
2885 . _('Submitted Description')._(': ').htmlspecialchars_decode($this->getRegistrationPurpose()) . "\n";
2887 foreach ($submitters as $submitter) {
2888 $message .= _('Submitter')._(': ').$submitter->getRealName().' ('.$submitter->getUnixName().')' . "\n\n";
2892 . _('Please visit the following URL to approve or reject this project')._(': '). "\n"
2893 . util_make_url('/admin/approve-pending.php');
2894 util_send_message($admin_email, sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')), $message);
2895 setup_gettext_from_context();
2898 $email = $submitter->getEmail();
2899 setup_gettext_for_user ($submitter);
2901 $message = sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')) . "\n\n"
2902 . _('Project Full Name')._(': ') . $this->getPublicName() . "\n"
2903 . _('Submitted Description')._(': ') . util_unconvert_htmlspecialchars($this->getRegistrationPurpose()) . "\n\n"
2904 . sprintf(_('The %s admin team will now examine your project submission. You will be notified of their decision.'),
2905 forge_get_config ('web_host'));
2907 util_send_message($email, sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')), $message);
2908 setup_gettext_from_context();
2914 * validateGroupName - Validate the group name
2916 * @param string $group_name Project name.
2918 * @return bool an error false and set an error is the group name is invalid otherwise return true
2920 function validateGroupName($group_name) {
2921 if (strlen($group_name)<3) {
2922 $this->setError(_('Project name is too short'));
2924 } elseif (strlen(htmlspecialchars($group_name))>40) {
2925 $this->setError(_('Project name is too long'));
2927 } elseif (group_get_object_by_publicname($group_name)) {
2928 $this->setError(_('Project name already taken'));
2935 * getRolesId - Get Ids of the roles of the group.
2937 * @param bool all role ids or local role ids only. Default is all role ids
2938 * @return array Role ids of this group.
2940 function getRolesId($global = true) {
2941 $role_ids = array();
2943 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2944 array($this->getID()));
2945 while ($arr = db_fetch_array($res)) {
2946 $role_ids[] = $arr['role_id'];
2949 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2950 array($this->getID()));
2951 while ($arr = db_fetch_array($res)) {
2952 $role_ids[] = $arr['role_id'];
2956 return array_unique($role_ids);
2960 * getRoles - Get the roles of the group.
2962 * @param bool all roles or local roles only. Default is all roles
2963 * @return array Roles of this group.
2965 function getRoles($global = true) {
2968 $roles = $this->getRolesId($global);
2969 $engine = RBACEngine::getInstance();
2970 foreach ($roles as $role_id) {
2971 $result[] = $engine->getRoleById($role_id);
2977 function normalizeAllRoles() {
2978 $roles = $this->getRoles();
2980 foreach ($roles as $r) {
2981 $r->normalizeData();
2986 * getUnixStatus - Status of activation of unix account.
2988 * @return string Values: (N)one, (A)ctive, (S)uspended or (D)eleted
2990 function getUnixStatus() {
2991 return $this->data_array['unix_status'];
2995 * setUnixStatus - Sets status of activation of unix account.
2997 * @param string $status The unix status.
3003 * @return bool success.
3005 function setUnixStatus($status) {
3008 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
3013 $this->setError(_('Error')._(': ')._('Cannot Update Group Unix Status')._(': ').db_error());
3017 if ($status == 'A') {
3018 if (!$SYS->sysCheckCreateGroup($this->getID())) {
3019 $this->setError($SYS->getErrorMessage());
3024 if ($SYS->sysCheckGroup($this->getID())) {
3025 if (!$SYS->sysRemoveGroup($this->getID())) {
3026 $this->setError($SYS->getErrorMessage());
3033 $this->data_array['unix_status'] = $status;
3040 * getUsers - Get the users of a group
3042 * @param bool $onlylocal
3043 * @param boolean $onlyactive Only users with state active, or all users of group
3044 * @return array user's objects.
3046 function getUsers($onlylocal = true, $onlyactive = true) {
3047 if (!isset($this->membersArr)) {
3048 $this->membersArr = array();
3051 foreach ($this->getRoles() as $role) {
3053 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
3056 foreach ($role->getUsers() as $user) {
3057 $ids[] = $user->getID();
3060 $ids = array_unique ($ids);
3061 foreach ($ids as $id) {
3062 $u = user_get_object ($id);
3063 if (!$onlyactive || $u->isActive()) {
3064 $this->membersArr[] = $u;
3068 return $this->membersArr;
3071 function setDocmanCreateOnlineStatus($status) {
3073 $res = db_query_params('UPDATE groups SET use_docman_create_online = $1 WHERE group_id = $2',
3074 array($status, $this->getID()));
3077 $this->setError(_('Error')._(': ')._('Cannot Update Group DocmanCreateOnline Status')._(': ').db_error());
3081 $this->data_array['use_docman_create_online'] = $status;
3087 function setDocmanWebdav($status) {
3089 $res = db_query_params('UPDATE groups SET use_webdav = $1 WHERE group_id = $2',
3094 $this->setError(_('Error')._(': ')._('Cannot Update Group UseWebdav Status')._(': ').db_error());
3098 $this->data_array['use_webdav'] = $status;
3104 function setDocmanSearchStatus($status) {
3106 /* if we activate search engine, we probably want to reindex */
3107 $res = db_query_params('UPDATE groups SET use_docman_search = $1, force_docman_reindex = $1 WHERE group_id = $2',
3108 array($status, $this->getID()));
3111 $this->setError(_('Error')._(': ')._('Cannot Update Group UseDocmanSearch Status')._(': ').db_error());
3115 $this->data_array['use_docman_search'] = $status;
3121 function setDocmanForceReindexSearch($status) {
3123 $res = db_query_params('UPDATE groups SET force_docman_reindex = $1 WHERE group_id = $2',
3124 array($status, $this->getID()));
3127 $this->setError(_('Error')._(': ')._('Cannot Update Group force_docman_reindex')._(': ').db_error());
3131 $this->data_array['force_docman_reindex'] = $status;
3139 * @param integer $unit_set_id the effort unit set id
3142 function setEffortUnitSet($unit_set_id) {
3144 $res = db_query_params ('UPDATE groups SET unit_set_id=$1 WHERE group_id=$2',
3145 array($unit_set_id, $this->getID()));
3147 $this->data_array['unit_set_id'] = $unit_set_id;
3157 * getEffortUnitSet - Get the effort unit set id.
3159 * @return integer The id of the effort unit set.
3161 function getEffortUnitSet() {
3162 return $this->data_array['unit_set_id'];
3165 function getWidgetLayoutConfig() {
3166 $lm = new WidgetLayoutManager();
3167 return $lm->getLayout($this->getID(), WidgetLayoutManager::OWNER_TYPE_GROUP);
3172 * group_getname() - get the group name
3174 * @param int $group_id The group ID
3179 function group_getname ($group_id = 0) {
3180 $grp = group_get_object($group_id);
3182 return $grp->getPublicName();
3189 * group_getunixname() - get the unixname for a group
3191 * @param int $group_id The group ID
3196 function group_getunixname ($group_id) {
3197 $grp = group_get_object($group_id);
3199 return $grp->getUnixName();
3206 * group_get_result() - Get the group object result ID.
3208 * @param int $group_id The group ID
3213 function &group_get_result($group_id=0) {
3214 $grp = group_get_object($group_id);
3216 return $grp->getData();
3222 function getAllProjectTags($onlyvisible = true) {
3223 $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',
3226 if (!$res || db_numrows($res) == 0) {
3232 while ($arr = db_fetch_array($res)) {
3234 $group_id = $arr[1];
3235 if (!isset($result[$tag])) {
3236 $result[$tag] = array();
3239 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
3240 $p = group_get_object($group_id);
3241 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
3242 'group_id' => $group_id);
3250 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
3253 class ProjectComparator {
3254 var $criterion = 'name';
3256 function Compare ($a, $b) {
3257 switch ($this->criterion) {
3260 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName());
3261 if ($namecmp != 0) {
3264 /* If several projects share a same public name */
3265 return strcoll ($a->getUnixName(), $b->getUnixName());
3267 return strcmp ($a->getUnixName(), $b->getUnixName());
3274 return ($aid < $bid) ? -1 : 1;
3279 function sortProjectList (&$list, $criterion='name') {
3280 $cmp = new ProjectComparator();
3281 $cmp->criterion = $criterion;
3283 return usort ($list, array($cmp, 'Compare'));
3288 // c-file-style: "bsd"