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;
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 if (is_array($this->membersArr)) {
2190 foreach ($this->membersArr as $u) {
2191 if ($u->getID() == $add_u->getID()) {
2197 $this->membersArr[] = $add_u;
2205 * removeUser - controls removing a user from a group.
2207 * Users can remove themselves.
2209 * @param int $user_id The ID of the user to remove.
2210 * @return bool success.
2212 function removeUser($user_id) {
2215 if ($user_id != user_getid()
2216 && !forge_check_perm('project_admin', $this->getID())) {
2217 $this->setPermissionDeniedError();
2223 $user = user_get_object($user_id);
2224 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
2225 $found_roles = array();
2226 foreach ($roles as $role) {
2227 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2228 $found_roles[] = $role;
2231 if (count($found_roles) == 0) {
2232 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2236 foreach ($found_roles as $found_role) {
2237 $found_role->removeUser($user);
2238 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
2239 $this->setError($SYS->getErrorMessage());
2246 // reassign open artifacts to id=100
2248 $res = db_query_params('UPDATE artifact SET assigned_to=100
2249 WHERE group_artifact_id
2250 IN (SELECT group_artifact_id
2251 FROM artifact_group_list
2252 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
2253 array($this->getID(),
2256 $this->setError(_('Error')._(': ')._('artifact')._(': ').db_error());
2262 // reassign open tasks to id=100
2263 // first have to purge any assignments that would cause
2264 // conflict with existing assignment to 100
2266 $res = db_query_params('DELETE FROM project_assigned_to
2267 WHERE project_task_id IN (SELECT pt.project_task_id
2268 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2269 WHERE pt.group_project_id = pgl.group_project_id
2270 AND pat.project_task_id=pt.project_task_id
2271 AND pt.status_id=1 AND pgl.group_id=$1
2272 AND pat.assigned_to_id=$2)
2273 AND assigned_to_id=100',
2274 array($this->getID(),
2277 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 1, db_error()));
2281 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2282 WHERE project_task_id IN (SELECT pt.project_task_id
2283 FROM project_task pt, project_group_list pgl
2284 WHERE pt.group_project_id = pgl.group_project_id
2285 AND pt.status_id=1 AND pgl.group_id=$1)
2286 AND assigned_to_id=$2',
2287 array($this->getID(),
2290 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 2, db_error()));
2296 // Remove user from system
2298 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2299 $this->setError($SYS->getErrorMessage());
2304 $hook_params['group'] = $this;
2305 $hook_params['group_id'] = $this->getID();
2306 $hook_params['user'] = user_get_object($user_id);
2307 $hook_params['user_id'] = $user_id;
2308 plugin_hook("group_removeuser", $hook_params);
2311 $this->addHistory(_('Removed User'), $user_id);
2318 $del_u = user_get_object($user_id);
2319 foreach ($this->membersArr as $k => $u) {
2320 if ($u->getID() == $del_u->getID()) {
2321 unset($this->membersArr[$k]);
2330 * updateUser - controls updating a user's role in this group.
2332 * @param int $user_id The ID of the user.
2333 * @param int $role_id The role_id to set this user to.
2334 * @return bool success.
2336 function updateUser($user_id, $role_id) {
2338 if (!forge_check_perm ('project_admin', $this->getID())) {
2339 $this->setPermissionDeniedError();
2343 $newrole = RBACEngine::getInstance()->getRoleById ($role_id);
2344 if (!$newrole || !is_object($newrole)) {
2345 $this->setError(_('Could Not Get Role'));
2347 } elseif ($newrole->isError()) {
2348 $this->setError(_('Role')._(': ').$role->getErrorMessage());
2350 } elseif ($newrole->getHomeProject() == NULL
2351 || $newrole->getHomeProject()->getID() != $this->getID()) {
2352 $this->setError(_('Wrong destination role'));
2355 $user = user_get_object ($user_id);
2356 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user);
2358 foreach ($roles as $role) {
2359 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2360 $found_role = $role;
2364 if ($found_role == NULL) {
2365 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2369 $found_role->removeUser ($user);
2370 $newrole->addUser ($user);
2372 $this->addHistory(_('Updated User'), $user_id);
2377 * addHistory - Makes an audit trail entry for this project.
2379 * @param string $field_name The name of the field.
2380 * @param string $old_value The Old Value for this $field_name.
2381 * @return resource database result handle.
2384 function addHistory($field_name, $old_value) {
2385 if ($old_value == NULL) {
2389 return db_query_params('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2390 VALUES ($1,$2,$3,$4,$5)',
2391 array($this->getID(),
2399 * activateUsers - Make sure that group members have unix accounts.
2401 * Setup unix accounts for group members. Can be called even
2402 * if members are already active.
2406 function activateUsers() {
2408 Activate member(s) of the project
2413 $members = $this->getUsers(true);
2415 foreach ($members as $member) {
2416 $user_id = $member->getID();
2418 if (!$SYS->sysCheckCreateGroup($this->getID())){
2419 $this->setError($SYS->getErrorMessage());
2423 if (!$SYS->sysCheckCreateUser($user_id)) {
2424 $this->setError($SYS->getErrorMessage());
2428 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2429 $this->setError($SYS->getErrorMessage());
2439 * getMembers - returns array of User objects for this project
2441 * @param boolean $onlyactive Only users with state active, or all users of group
2442 * @return array of User objects for this group.
2444 function getMembers($onlyactive = true) {
2445 return $this->getUsers(true, $onlyactive);
2449 * replaceTemplateStrings - fill-in some blanks with project name
2451 * @param string $string Template string
2452 * @return string String after replacements
2454 function replaceTemplateStrings($string) {
2455 $string = str_replace('UNIXNAME', $this->getUnixName(), $string);
2456 $string = str_replace('PUBLICNAME', $this->getPublicName(), $string);
2457 $string = str_replace('DESCRIPTION', $this->getDescription(), $string);
2462 * approve - Approve pending project.
2464 * @param object $user The User object who is doing the updating.
2468 function approve(&$user) {
2469 global $gfcommon,$gfwww;
2470 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2472 if ($this->getStatus()=='A') {
2473 $this->setError(_('Group already active'));
2479 // Step 1: Activate group and create LDAP entries
2480 if (!$this->setStatus($user, 'A')) {
2487 // Switch to system language for item creation
2488 setup_gettext_from_sys_lang();
2490 // Create default roles
2491 $idadmin_group = NULL;
2492 foreach (get_group_join_requests ($this) as $gjr) {
2493 $idadmin_group = $gjr->getUserID();
2496 if ($idadmin_group == NULL) {
2497 $idadmin_group = $user->getID();
2500 $template = $this->getTemplateProject();
2501 $id_mappings = array();
2502 $seen_admin_role = false;
2504 // Copy roles from template project
2505 foreach($template->getRoles() as $oldrole) {
2506 if ($oldrole->getHomeProject() != NULL) {
2507 $role = new Role($this);
2509 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2510 $role->create('TEMPORARY ROLE NAME', $data, true);
2511 $role->setName($oldrole->getName());
2512 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2513 $seen_admin_role = true;
2517 $role->linkProject($this);
2519 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2520 // Reuse the project_admin permission
2521 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID()));
2525 if (!$seen_admin_role) {
2526 $role = new Role($this);
2527 $adminperms = array('project_admin' => array ($this->getID() => 1));
2528 $role_id = $role->create ('Admin', $adminperms, true);
2531 $roles = $this->getRoles();
2532 foreach ($roles as $r) {
2533 if ($r->getHomeProject() == NULL) {
2536 if ($r->getSetting ('project_admin', $this->getID())) {
2537 $r->addUser(user_get_object ($idadmin_group));
2541 // Temporarily switch to the submitter's identity
2542 $saved_session = session_get_user();
2543 session_set_internal($idadmin_group);
2546 if (forge_get_config('use_tracker')) {
2547 $this->setUseTracker ($template->usesTracker());
2548 if ($template->usesTracker()) {
2549 $oldatf = new ArtifactTypeFactory($template);
2550 foreach ($oldatf->getArtifactTypes() as $o) {
2551 $t = new ArtifactType ($this);
2552 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions());
2553 $id_mappings['tracker'][$o->getID()] = $t->getID();
2558 if (forge_get_config('use_pm')) {
2559 $this->setUsePM ($template->usesPM());
2560 if ($template->usesPM()) {
2561 $oldpgf = new ProjectGroupFactory($template);
2562 foreach ($oldpgf->getProjectGroups() as $o) {
2563 $pg = new ProjectGroup($this);
2564 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2565 $id_mappings['pm'][$o->getID()] = $pg->getID();
2570 if (forge_get_config('use_forum')) {
2571 $this->setUseForum($template->usesForum());
2572 if ($template->usesForum()) {
2573 $oldff = new ForumFactory($template);
2574 foreach ($oldff->getForums() as $o) {
2575 $f = new Forum($this);
2576 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo(),1);
2577 $id_mappings['forum'][$o->getID()] = $f->getID();
2582 if (forge_get_config('use_docman')) {
2583 $this->setUseDocman($template->usesDocman());
2584 if ($template->usesDocman()) {
2585 $olddgf = new DocumentGroupFactory($template);
2586 // First pass: create all docgroups
2587 $id_mappings['docman_docgroup'][0] = 0;
2588 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2589 $ndg = new DocumentGroup($this);
2590 // .trash is a reserved directory
2591 if ($o->getName() != '.trash') {
2592 $ndg->create($this->replaceTemplateStrings($o->getName()), 0, 1, null, true);
2593 $id_mappings['docman_docgroup'][$o->getID()] = $ndg->getID();
2596 // Second pass: restore hierarchy links & stateid
2597 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2598 $ndgf = new DocumentGroup($this);
2599 if ($o->getName() != '.trash') {
2600 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2601 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()], 0, $o->getState());
2607 if (forge_get_config('use_frs')) {
2608 $this->setUseFRS ($template->usesFRS());
2609 if ($template->usesFRS()) {
2610 foreach (get_frs_packages($template) as $o) {
2611 $newp = new FRSPackage($this);
2612 $nname = $this->replaceTemplateStrings($o->getName());
2613 $newp->create($nname, $o->isPublic());
2614 $id_mappings['frs'][$o->getID()] = $newp->getID();
2615 foreach(get_frs_releases($o) as $or) {
2616 $newr = new FRSRelease($newp);
2617 $newr->create($this->replaceTemplateStrings($or->getName()), $this->replaceTemplateStrings($or->getNotes()), $this->replaceTemplateStrings($or->getChanges()), $or->getPreformatted());
2618 $id_mappings['frs_release'][$or->getID()] = $newr->getID();
2624 if (forge_get_config('use_mail')) {
2625 $this->setUseMail($template->usesMail());
2626 if ($template->usesMail()) {
2627 $oldmlf = new MailingListFactory($template);
2628 foreach ($oldmlf->getMailingLists() as $o) {
2629 $ml = new MailingList($this);
2630 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName());
2632 $ndescription = $this->replaceTemplateStrings($o->getDescription());
2633 $ml->create($nname, $ndescription, $o->isPublic());
2639 /* use SCM plugin from template group */
2640 $this->setUseSCM($template->usesSCM());
2642 foreach ($template->getPlugins() as
2643 $plugin_id => $plugin_name) {
2644 $this->setPluginUse($plugin_name);
2647 /* use SCM choice from registration page */
2648 foreach ($template->getPlugins() as $plugin_id => $plugin_name) {
2649 if (substr($plugin_name, 3) == 'scm' &&
2650 $plugin_name != 'scmhook') {
2651 /* skip copying scm plugins */
2654 /* enable other plugins though */
2655 $this->setPluginUse($plugin_name);
2659 foreach ($template->getRoles() as $oldrole) {
2660 $newrole = RBACEngine::getInstance()->getRoleById($id_mappings['role'][$oldrole->getID()]);
2661 if ($oldrole->getHomeProject() != NULL
2662 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2663 $newrole->setPublic ($oldrole->isPublic());
2665 $oldsettings = $oldrole->getSettingsForProject ($template);
2667 $sections = array('project_read', 'project_admin', 'scm', 'docman', 'tracker_admin', 'new_tracker', 'forum_admin', 'new_forum', 'pm_admin', 'new_pm', 'frs_admin', 'new_frs');
2668 foreach ($sections as $section) {
2669 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]);
2672 $sections = array('tracker', 'pm', 'forum', 'frs');
2673 foreach ($sections as $section) {
2674 if (isset ($oldsettings[$section])) {
2675 foreach ($oldsettings[$section] as $k => $v) {
2676 // Only copy perms for tools that have been copied
2677 if (isset ($id_mappings[$section][$k])) {
2678 $newrole->setSetting ($section,
2679 $id_mappings[$section][$k],
2687 $lm = new WidgetLayoutManager();
2688 $lm->createDefaultLayoutForProject($this->getID(), $template->getID());
2690 // second computation to clone fields and workflow
2691 if (forge_get_config('use_tracker')) {
2692 if ($template->usesTracker()) {
2693 $oldatf = new ArtifactTypeFactory($template);
2694 foreach ($oldatf->getArtifactTypes() as $o) {
2695 $t = artifactType_get_object($id_mappings['tracker'][$o->getID()]);
2696 $id_mappings['tracker'][$o->getID()] = $t->getID();
2697 $newEFIds = $t->cloneFieldsFrom($o->getID(), $id_mappings);
2698 if (forge_get_config('use_tracker_widget_display')) {
2699 $lm->createDefaultLayoutForTracker($t->getID(), $o->getID(), $newEFIds);
2706 $params['template'] = $template;
2707 $params['project'] = $this;
2708 $params['id_mappings'] = $id_mappings;
2709 plugin_hook_by_reference ('clone_project_from_template', $params);
2711 // Disable everything - except use_scm (manually set in the registration page)
2712 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,
2713 use_docman = 0, use_ftp = 0, use_tracker = 0, use_frs = 0, use_stats = 0 WHERE group_id = $1',
2714 array($this->getID()));
2717 $this->normalizeAllRoles();
2718 // empty members cache because the group creator is not yet in cache.
2719 unset($this->membersArr);
2720 $this->activateUsers();
2722 // Delete fake join request
2723 foreach (get_group_join_requests ($this) as $gjr) {
2727 // Switch back to user preference
2728 session_set_internal($saved_session->getID());
2729 setup_gettext_from_context();
2731 $this->sendApprovalEmail();
2732 $this->addHistory(_('Approved'), 'x');
2735 // Plugin can make approve operation there
2738 $params['group'] = $this;
2739 $params['group_id'] = $this->getID();
2740 plugin_hook('group_approved', $params);
2746 * sendApprovalEmail - Send new project email.
2748 * @return bool success.
2751 function sendApprovalEmail() {
2752 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID());
2754 if (count($admins) < 1) {
2755 $this->setError(_('Group does not have any administrators.'));
2759 // send one email per admin
2760 foreach ($admins as $admin) {
2761 setup_gettext_for_user ($admin);
2763 $message = sprintf(_('Your project registration for %4$s has been approved.
2765 Project Full Name: %1$s
2766 Project Unix Name: %2$s
2768 Your DNS will take up to a day to become active on our site.
2769 Your web site is accessible through your shell account. Please read
2770 site documentation (see link below) about intended usage, available
2771 services, and directory layout of the account.
2774 own project page in %4$s while logged in, you will find
2775 additional menu functions to your left labeled \'Project Admin\'.
2777 We highly suggest that you now visit %4$s and create a public
2778 description for your project. This can be done by visiting your project
2779 page while logged in, and selecting \'Project Admin\' from the menus
2780 on the left (or by visiting %3$s
2783 Your project will also not appear in the Trove Software Map (primary
2784 list of projects hosted on %4$s which offers great flexibility in
2785 browsing and search) until you categorize it in the project administration
2786 screens. So that people can find your project, you should do this now.
2787 Visit your project while logged in, and select \'Project Admin\' from the
2790 Enjoy the system, and please tell others about %4$s. Let us know
2791 if there is anything we can do to help you.
2794 htmlspecialchars_decode($this->getPublicName()),
2795 $this->getUnixName(),
2796 util_make_url ('/project/admin/?group_id='.$this->getID()),
2797 forge_get_config ('forge_name'));
2799 util_send_message($admin->getEmail(), sprintf(_('%s Project Approved'), forge_get_config ('forge_name')), $message);
2801 setup_gettext_from_context();
2808 * sendRejectionEmail - Send project rejection email.
2810 * This function sends out a rejection message to a user who
2811 * registered a project.
2813 * @param int $response_id The id of the response to use.
2814 * @param string $message The rejection message.
2815 * @return bool completion status.
2818 function sendRejectionEmail($response_id, $message = 'zxcv') {
2819 $submitters = array();
2820 foreach (get_group_join_requests ($this) as $gjr) {
2821 $submitters[] = user_get_object($gjr->getUserID());
2824 if (count ($submitters) < 1) {
2825 $this->setError(_('Group does not have any administrators.'));
2829 foreach ($submitters as $admin) {
2830 setup_gettext_for_user($admin);
2832 $response = sprintf(_('Your project registration for %s has been denied.'), forge_get_config('forge_name')) . "\n\n"
2833 . _('Project Full Name')._(': '). $this->getPublicName() . "\n"
2834 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2835 . _('Reasons for negative decision')._(': ') . "\n\n";
2837 // Check to see if they want to send a custom rejection response
2838 if ($response_id == 0) {
2839 $response .= $message;
2841 $response .= db_result(
2842 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array($response_id)),
2847 util_send_message($admin->getEmail(), sprintf(_('%s Project Denied'), forge_get_config('forge_name')), $response);
2848 setup_gettext_from_context();
2855 * sendNewProjectNotificationEmail - Send new project notification email.
2857 * This function sends out a notification email to the
2858 * SourceForge admin user when a new project is
2861 * @return bool success.
2864 function sendNewProjectNotificationEmail() {
2865 // Get the user who wants to register the project
2866 $submitters = array();
2867 foreach (get_group_join_requests ($this) as $gjr) {
2868 $submitters[] = user_get_object($gjr->getUserID());
2870 if (count ($submitters) < 1) {
2871 $this->setError(_('Could not find user who has submitted the project.'));
2875 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('approve_projects', -1);
2877 if (count($admins) < 1) {
2878 $this->setError(_('There is no administrator to send the mail to.'));
2882 foreach ($admins as $admin) {
2883 $admin_email = $admin->getEmail();
2884 setup_gettext_for_user ($admin);
2886 $message = sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')) . "\n\n"
2887 . _('Project Full Name')._(': ').htmlspecialchars_decode($this->getPublicName()) . "\n"
2888 . _('Submitted Description')._(': ').htmlspecialchars_decode($this->getRegistrationPurpose()) . "\n";
2890 foreach ($submitters as $submitter) {
2891 $message .= _('Submitter')._(': ').$submitter->getRealName().' ('.$submitter->getUnixName().')' . "\n\n";
2895 . _('Please visit the following URL to approve or reject this project')._(': '). "\n"
2896 . util_make_url('/admin/approve-pending.php');
2897 util_send_message($admin_email, sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')), $message);
2898 setup_gettext_from_context();
2901 $email = $submitter->getEmail();
2902 setup_gettext_for_user ($submitter);
2904 $message = sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')) . "\n\n"
2905 . _('Project Full Name')._(': ') . $this->getPublicName() . "\n"
2906 . _('Submitted Description')._(': ') . util_unconvert_htmlspecialchars($this->getRegistrationPurpose()) . "\n\n"
2907 . sprintf(_('The %s admin team will now examine your project submission. You will be notified of their decision.'),
2908 forge_get_config ('web_host'));
2910 util_send_message($email, sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')), $message);
2911 setup_gettext_from_context();
2917 * validateGroupName - Validate the group name
2919 * @param string $group_name Project name.
2921 * @return bool an error false and set an error is the group name is invalid otherwise return true
2923 function validateGroupName($group_name) {
2924 if (strlen($group_name)<3) {
2925 $this->setError(_('Project name is too short'));
2927 } elseif (strlen(htmlspecialchars($group_name))>40) {
2928 $this->setError(_('Project name is too long'));
2930 } elseif (group_get_object_by_publicname($group_name)) {
2931 $this->setError(_('Project name already taken'));
2938 * getRolesId - Get Ids of the roles of the group.
2940 * @param bool all role ids or local role ids only. Default is all role ids
2941 * @return array Role ids of this group.
2943 function getRolesId($global = true) {
2944 $role_ids = array();
2946 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2947 array($this->getID()));
2948 while ($arr = db_fetch_array($res)) {
2949 $role_ids[] = $arr['role_id'];
2952 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2953 array($this->getID()));
2954 while ($arr = db_fetch_array($res)) {
2955 $role_ids[] = $arr['role_id'];
2959 return array_unique($role_ids);
2963 * getRoles - Get the roles of the group.
2965 * @param bool all roles or local roles only. Default is all roles
2966 * @return array Roles of this group.
2968 function getRoles($global = true) {
2971 $roles = $this->getRolesId($global);
2972 $engine = RBACEngine::getInstance();
2973 foreach ($roles as $role_id) {
2974 $result[] = $engine->getRoleById($role_id);
2980 function normalizeAllRoles() {
2981 $roles = $this->getRoles();
2983 foreach ($roles as $r) {
2984 $r->normalizeData();
2989 * getUnixStatus - Status of activation of unix account.
2991 * @return string Values: (N)one, (A)ctive, (S)uspended or (D)eleted
2993 function getUnixStatus() {
2994 return $this->data_array['unix_status'];
2998 * setUnixStatus - Sets status of activation of unix account.
3000 * @param string $status The unix status.
3006 * @return bool success.
3008 function setUnixStatus($status) {
3011 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
3016 $this->setError(_('Error')._(': ')._('Cannot Update Group Unix Status')._(': ').db_error());
3020 if ($status == 'A') {
3021 if (!$SYS->sysCheckCreateGroup($this->getID())) {
3022 $this->setError($SYS->getErrorMessage());
3027 if ($SYS->sysCheckGroup($this->getID())) {
3028 if (!$SYS->sysRemoveGroup($this->getID())) {
3029 $this->setError($SYS->getErrorMessage());
3036 $this->data_array['unix_status'] = $status;
3043 * getUsers - Get the users of a group
3045 * @param bool $onlylocal
3046 * @param boolean $onlyactive Only users with state active, or all users of group
3047 * @return array user's objects.
3049 function getUsers($onlylocal = true, $onlyactive = true) {
3050 if (!isset($this->membersArr)) {
3051 $this->membersArr = array();
3054 foreach ($this->getRoles() as $role) {
3056 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
3059 foreach ($role->getUsers() as $user) {
3060 $ids[] = $user->getID();
3063 $ids = array_unique ($ids);
3064 foreach ($ids as $id) {
3065 $u = user_get_object ($id);
3066 if (!$onlyactive || $u->isActive()) {
3067 $this->membersArr[] = $u;
3071 return $this->membersArr;
3074 function setDocmanCreateOnlineStatus($status) {
3076 $res = db_query_params('UPDATE groups SET use_docman_create_online = $1 WHERE group_id = $2',
3077 array($status, $this->getID()));
3080 $this->setError(_('Error')._(': ')._('Cannot Update Group DocmanCreateOnline Status')._(': ').db_error());
3084 $this->data_array['use_docman_create_online'] = $status;
3090 function setDocmanWebdav($status) {
3092 $res = db_query_params('UPDATE groups SET use_webdav = $1 WHERE group_id = $2',
3097 $this->setError(_('Error')._(': ')._('Cannot Update Group UseWebdav Status')._(': ').db_error());
3101 $this->data_array['use_webdav'] = $status;
3107 function setDocmanSearchStatus($status) {
3109 /* if we activate search engine, we probably want to reindex */
3110 $res = db_query_params('UPDATE groups SET use_docman_search = $1, force_docman_reindex = $1 WHERE group_id = $2',
3111 array($status, $this->getID()));
3114 $this->setError(_('Error')._(': ')._('Cannot Update Group UseDocmanSearch Status')._(': ').db_error());
3118 $this->data_array['use_docman_search'] = $status;
3124 function setDocmanForceReindexSearch($status) {
3126 $res = db_query_params('UPDATE groups SET force_docman_reindex = $1 WHERE group_id = $2',
3127 array($status, $this->getID()));
3130 $this->setError(_('Error')._(': ')._('Cannot Update Group force_docman_reindex')._(': ').db_error());
3134 $this->data_array['force_docman_reindex'] = $status;
3142 * @param integer $unit_set_id the effort unit set id
3145 function setEffortUnitSet($unit_set_id) {
3147 $res = db_query_params ('UPDATE groups SET unit_set_id=$1 WHERE group_id=$2',
3148 array($unit_set_id, $this->getID()));
3150 $this->data_array['unit_set_id'] = $unit_set_id;
3160 * getEffortUnitSet - Get the effort unit set id.
3162 * @return integer The id of the effort unit set.
3164 function getEffortUnitSet() {
3165 return $this->data_array['unit_set_id'];
3168 function getWidgetLayoutConfig() {
3169 $lm = new WidgetLayoutManager();
3170 return $lm->getLayout($this->getID(), WidgetLayoutManager::OWNER_TYPE_GROUP);
3175 * group_getname() - get the group name
3177 * @param int $group_id The group ID
3182 function group_getname ($group_id = 0) {
3183 $grp = group_get_object($group_id);
3185 return $grp->getPublicName();
3192 * group_getunixname() - get the unixname for a group
3194 * @param int $group_id The group ID
3199 function group_getunixname ($group_id) {
3200 $grp = group_get_object($group_id);
3202 return $grp->getUnixName();
3209 * group_get_result() - Get the group object result ID.
3211 * @param int $group_id The group ID
3216 function &group_get_result($group_id=0) {
3217 $grp = group_get_object($group_id);
3219 return $grp->getData();
3225 function getAllProjectTags($onlyvisible = true) {
3226 $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',
3229 if (!$res || db_numrows($res) == 0) {
3235 while ($arr = db_fetch_array($res)) {
3237 $group_id = $arr[1];
3238 if (!isset($result[$tag])) {
3239 $result[$tag] = array();
3242 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
3243 $p = group_get_object($group_id);
3244 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
3245 'group_id' => $group_id);
3253 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
3256 class ProjectComparator {
3257 var $criterion = 'name';
3259 function Compare ($a, $b) {
3260 switch ($this->criterion) {
3263 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName());
3264 if ($namecmp != 0) {
3267 /* If several projects share a same public name */
3268 return strcoll ($a->getUnixName(), $b->getUnixName());
3270 return strcmp ($a->getUnixName(), $b->getUnixName());
3277 return ($aid < $bid) ? -1 : 1;
3282 function sortProjectList (&$list, $criterion='name') {
3283 $cmp = new ProjectComparator();
3284 $cmp->criterion = $criterion;
3286 return usort ($list, array($cmp, 'Compare'));
3291 // c-file-style: "bsd"