5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2013, Roland Mas
7 * Copyright 2010-2011,2021, Franck Villaume - Capgemini
8 * Copyright 2010-2012, Alain Peyrat - Alcatel-Lucent
9 * Copyright 2012-2017,2021, 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 (!empty($fetch)) {
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 * cached return value of getVotes
256 * @var int|bool $votes
261 * cached return value of getVoters
262 * @var int|bool $voters
267 * Group - Group object constructor - use group_get_object() to instantiate.
269 * @param int|bool $id Required - Id of the group you want to instantiate.
270 * @param int|bool $res Database result from select query OR associative array of all columns.
272 function __construct($id = false, $res = false) {
273 parent::__construct();
275 //setting up an empty object
276 //probably going to call create()
280 $this->fetchData($id);
283 // Assoc array was passed in
285 if (is_array($res)) {
286 $this->data_array =& $res;
288 if (db_numrows($res) < 1) {
289 //function in class we extended
290 $this->setError(_('Group Not Found'));
291 $this->data_array = array();
293 //set up an associative array for use by other functions
294 $this->data_array = db_fetch_array_by_row($res, 0);
302 * fetchData - May need to refresh database fields if an update occurred.
304 * @param int $group_id The group_id.
305 * @return bool success or not
307 function fetchData($group_id) {
308 $res = db_query_params ('SELECT * FROM groups WHERE group_id=$1',
310 if (!$res || db_numrows($res) < 1) {
311 $this->setError('fetchData()'._(': ').db_error());
314 $this->data_array = db_fetch_array($res);
319 * create - Create new group.
321 * This method should be called on empty Group object.
322 * It will add an entry for a pending group/project (status 'P')
324 * @param object $user The User object.
325 * @param string $group_name The full name of the user.
326 * @param string $unix_name The Unix name of the user.
327 * @param string $description The new group description.
328 * @param string $purpose The purpose of the group.
329 * @param string $unix_box
330 * @param string $scm_box
331 * @param bool $send_mail Whether to send an email or not
332 * @param int $built_from_template The id of the project this new project is based on
333 * @param int $createtimestamp The Time Stamp of creation to ease import.
334 * @return bool success or not
336 function create(&$user, $group_name, $unix_name, $description, $purpose, $unix_box = 'shell1',
337 $scm_box = 'cvs1', $send_mail = true, $built_from_template = 0, $createtimestamp = null) {
338 // $user is ignored - anyone can create pending group
341 if ($this->getID()!=0) {
342 $this->setError(_('Group object already exists.'));
344 } elseif (!$this->validateGroupName($group_name)) {
345 $this->setError(_('Invalid project name'));
347 } elseif (!account_groupnamevalid($unix_name)) {
348 $this->setError(_('Invalid Unix Name.'));
350 } elseif (!$SYS->sysUseUnixName($unix_name)) {
351 $this->setError(_('Unix name already taken.'));
353 } elseif (strlen($purpose)<10) {
354 $this->setError(_('Please describe your Registration Project Purpose and Summarization in a more comprehensive manner.'));
356 } elseif (strlen($purpose)>1500) {
357 $this->setError(_('The Registration Project Purpose and Summarization text is too long. Please make it smaller than 1500 characters.'));
359 } elseif (strlen($description)<10) {
360 $this->setError(_('Describe in a more comprehensive manner your project.'));
364 // Check if use_project_vhost for homepage
365 if (forge_get_config('use_project_vhost')) {
366 $homepage = $unix_name.'.'.forge_get_config('web_host');
368 $homepage = forge_get_config('web_host')."/www/".$unix_name."/";
372 $createtimestamp = (($createtimestamp) ? $createtimestamp : time());
373 $res = db_query_params('
388 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)',
389 array(htmlspecialchars($group_name),
391 htmlspecialchars($description),
397 htmlspecialchars($purpose),
399 md5(util_randbytes()),
400 $built_from_template));
401 if (!$res || db_affected_rows($res) < 1) {
402 $this->setError(_('Error')._(': ')._('Cannot create group')._(': ').db_error());
407 $id = db_insertid($res, 'groups', 'group_id');
409 $this->setError(_('Error')._(': ')._('Cannot get group id')._(': ').db_error());
414 if (!$this->fetchData($id)) {
419 $gjr = new GroupJoinRequest($this);
420 $gjr->create($user->getID(), 'Fake GroupJoinRequest to store the creator of a project', false);
422 $hook_params = array();
423 $hook_params['group'] = $this;
424 $hook_params['group_id'] = $this->getID();
425 $hook_params['group_name'] = $group_name;
426 $hook_params['unix_group_name'] = $unix_name;
427 $hook_params['createtimestamp'] = $createtimestamp;
428 plugin_hook("group_create", $hook_params);
432 $this->sendNewProjectNotificationEmail();
440 * updateAdmin - Update core properties of group object.
442 * This function require site admin privilege.
444 * @param string $unix_box Machine on which group's home directory located.
445 * @param string $http_domain Domain which serves group's WWW.
446 * @return bool status.
449 function updateAdmin($unix_box, $http_domain) {
450 $perm =& $this->getPermission();
452 if (!$perm || !is_object($perm)) {
453 $this->setError(_('Could not get permission.'));
457 if (!$perm->isSuperUser()) {
458 $this->setError(_('Permission denied.'));
464 $res = db_query_params('
466 SET unix_box=$1, http_domain=$2
472 if (!$res || db_affected_rows($res) < 1) {
473 $this->setError(_('Error')._(': ')._('Cannot change group properties')._(': ').db_error());
478 // Log the audit trail
479 if ($unix_box != $this->data_array['unix_box']) {
480 $this->addHistory('unix_box', $this->data_array['unix_box']);
482 if ($http_domain != $this->data_array['http_domain']) {
483 $this->addHistory('http_domain', $this->data_array['http_domain']);
486 if (!$this->fetchData($this->getID())) {
495 * update - Update number of common properties.
497 * Unlike updateAdmin(), this function accessible to project admin.
499 * @param object $user User requesting operation (for access control).
500 * @param string $group_name
501 * @param string $homepage
502 * @param string $short_description
503 * @param bool $use_mail
504 * @param bool $use_survey
505 * @param bool $use_forum
506 * @param bool $use_pm
507 * @param bool $use_pm_depend_box
508 * @param bool $use_scm
509 * @param bool $use_news
510 * @param bool $use_docman
511 * @param string $new_doc_address
512 * @param bool $send_all_docs
513 * @param int $logo_image_id XXXX UNUSED XXXX -> see getLogoImageID function
514 * @param bool $use_ftp
515 * @param bool $use_tracker
516 * @param bool $use_frs
517 * @param bool $use_stats
518 * @param string $tags
519 * @param bool $use_activity
520 * @param bool $is_public group is publicly accessible
521 * @param string $new_frs_address
522 * @param bool $send_all_frs
523 * @return int status.
526 function update(&$user, $group_name, $homepage, $short_description, $use_mail, $use_survey, $use_forum,
527 $use_pm, $use_pm_depend_box, $use_scm, $use_news, $use_docman,
528 $new_doc_address, $send_all_docs, $logo_image_id,
529 $use_ftp, $use_tracker, $use_frs, $use_stats, $tags, $use_activity, $is_public, $new_frs_address, $send_all_frs) {
531 $perm =& $this->getPermission();
533 if (!$perm || !is_object($perm)) {
534 $this->setError(_('Could not get permission.'));
538 if (!$perm->isAdmin()) {
539 $this->setError(_('Permission denied.'));
543 // Validate some values
544 if ($this->getPublicName() != htmlspecialchars($group_name) && !$this->validateGroupName($group_name)) {
548 if ($new_doc_address) {
549 $invalid_mails = validate_emails($new_doc_address);
550 if (count($invalid_mails) > 0) {
551 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
556 if ($new_frs_address) {
557 $invalid_mails = validate_emails($new_frs_address);
558 if (count($invalid_mails) > 0) {
559 $this->setError(sprintf(ngettext('New FRS Address Appeared Invalid: %s', 'New FRS Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
564 // in the database, these all default to '1',
565 // so we have to explicitly set 0
578 if (!$use_pm_depend_box) {
579 $use_pm_depend_box = 0;
602 if (!$use_activity) {
605 if (!$send_all_docs) {
609 if (!$send_all_frs) {
613 $homepage = ltrim($homepage);
615 $homepage = util_make_url('/projects/'.$this->getUnixName().'/');
620 $res = db_query_params('UPDATE groups
623 short_description=$3,
628 use_pm_depend_box=$8,
641 array(htmlspecialchars($group_name),
643 htmlspecialchars($short_description),
662 if (!$res || db_affected_rows($res) < 1) {
663 $this->setError(_('Error updating project information')._(': ').db_error());
668 if (!$this->setUseDocman($use_docman)) {
669 $this->setError(_('Error updating project information use_docman')._(': ').db_error());
674 if ($this->setTags($tags) === false) {
679 // Log the audit trail
680 $this->addHistory('Changed Public Info', '');
682 if (!$this->fetchData($this->getID())) {
687 $hook_params = array();
688 $hook_params['group'] = $this;
689 $hook_params['group_id'] = $this->getID();
690 $hook_params['group_homepage'] = $homepage;
691 $hook_params['group_name'] = htmlspecialchars($group_name);
692 $hook_params['group_description'] = htmlspecialchars($short_description);
693 $hook_params['group_ispublic'] = $is_public;
694 if (!plugin_hook("group_update", $hook_params)) {
695 if (!$this->isError()) {
696 $this->setError(_('Error updating project information in plugin_hook group_update'));
707 * getID - Simply return the group_id for this object.
709 * @return int group_id.
712 return $this->data_array['group_id'];
716 * getStatus - the status code.
718 * Statuses char include I,H,A,D,P.
725 function getStatus() {
726 return $this->data_array['status'];
730 * setStatus - set the status code.
732 * Statuses include I,H,A,D,P.
739 * @param object $user User requesting operation (for access control).
740 * @param string $status Status value.
741 * @return bool success.
744 function setStatus(&$user, $status) {
747 if (!forge_check_global_perm_for_user($user, 'approve_projects')) {
748 $this->setPermissionDeniedError();
752 // Projects in 'A' status can only go to 'H' or 'D'
753 // Projects in 'D' status can only go to 'A'
754 // Projects in 'P' status can only go to 'A' OR 'D'
755 // Projects in 'I' status can only go to 'P'
756 // Projects in 'H' status can only go to 'A' OR 'D'
757 $allowed_status_changes = array(
758 'AH'=>1,'AD'=>1,'DA'=>1,'PA'=>1,'PD'=>1,
759 'IP'=>1,'HA'=>1,'HD'=>1
762 // Check that status transition is valid
763 if ($this->getStatus() != $status
764 && !array_key_exists($this->getStatus(). $status, $allowed_status_changes)) {
765 $this->setError(_('Invalid Status Change From')._(': ').$this->getStatus()._(' To ')._(': ').$status);
771 $res = db_query_params('UPDATE groups
773 WHERE group_id=$2', array($status, $this->getID()));
775 if (!$res || db_affected_rows($res) < 1) {
776 $this->setError(_('Error')._(': ')._('Cannot change group status')._(': ').db_error());
782 // Activate system group, if not yet
783 if (!$SYS->sysCheckGroup($this->getID())) {
784 if (!$SYS->sysCreateGroup($this->getID())) {
785 $this->setError($SYS->getErrorMessage());
790 if (!$this->activateUsers()) {
795 /* Otherwise, the group is not active, and make sure that
796 System group is not active either */
797 } elseif ($SYS->sysCheckGroup($this->getID())) {
798 if (!$SYS->sysRemoveGroup($this->getID())) {
799 $this->setError($SYS->getErrorMessage());
805 $hook_params = array();
806 $hook_params['group'] = $this;
807 $hook_params['group_id'] = $this->getID();
808 $hook_params['status'] = $status;
809 plugin_hook("group_setstatus", $hook_params);
813 // Log the audit trail
814 if ($status != $this->getStatus()) {
815 $this->addHistory(_('Status'), $this->getStatus());
818 $this->data_array['status'] = $status;
823 * isPublic - Wrapper around RBAC to check if a project is anonymously readable
825 * @return boo is_public.
827 function isPublic() {
828 $ra = RoleAnonymous::getInstance();
829 return $ra->hasPermission('project_read', $this->getID());
833 * isActive - Database field status of 'A' returns true.
835 * @return bool is_active.
837 function isActive() {
838 if ($this->getStatus() == 'A') {
845 * isTemplate - Simply returns the is_template flag from the database.
847 * @return bool is_template.
849 function isTemplate() {
850 return $this->data_array['is_template'];
854 * setAsTemplate - Set the template status of a project
856 * @param bool $booleanparam is_template.
859 function setAsTemplate($booleanparam) {
861 $booleanparam = $booleanparam ? 1 : 0;
862 $res = db_query_params('UPDATE groups SET is_template=$1 WHERE group_id=$2',
863 array($booleanparam, $this->getID()));
865 if ($booleanparam != $this->data_array['is_template']) {
866 $this->addHistory('is_template', $this->data_array['is_template']);
868 $this->data_array['is_template'] = $booleanparam;
878 * getTemplateProject - Return the project template this project is built from
880 * @return object The template project
882 function getTemplateProject() {
883 return group_get_object($this->data_array['built_from_template']);
887 * getUnixName - the unix_name
889 * @return string unix_name.
891 function getUnixName() {
892 return strtolower($this->data_array['unix_group_name']);
896 * getPublicName - the full-length public name.
898 * @return string The group_name.
900 function getPublicName() {
901 return $this->data_array['group_name'];
905 * getDescription - the text description of this project.
907 * @return string The description.
909 function getDescription() {
910 return $this->data_array['short_description'];
914 * getStartDate - the unix time this project was registered.
916 * @return int (unix time) of registration.
918 function getStartDate() {
919 return $this->data_array['register_time'];
923 * getLogoImageID - the id of the logo in the database for this project.
925 * @return int The ID of logo image in db_images table (or 100 if none).
927 function getLogoImageID() {
928 if (!isset($this->data_array['logo_image_id'])) {
929 $res = db_query_params('select id from db_images where group_id = $1 and is_logo = $2',
930 array($this->getID(), 1));
931 if ($res && db_numrows($res)) {
932 $this->data_array['logo_image_id'] = db_result($res, 0, 'id');
934 $this->data_array['logo_image_id'] = null;
937 return $this->data_array['logo_image_id'];
941 * getUnixBox - the hostname of the unix box where this project is located.
943 * @return string The name of the unix machine for the group.
945 function getUnixBox() {
946 return $this->data_array['unix_box'];
950 * getSCMBox - the hostname of the scm box where this project is located.
952 * @return string The name of the unix machine for the group.
954 function getSCMBox() {
955 return $this->data_array['scm_box'];
958 * setSCMBox - the hostname of the scm box where this project is located.
960 * @param string $scm_box The name of the new SCM_BOX
963 function setSCMBox($scm_box) {
965 if ($scm_box == $this->data_array['scm_box']) {
970 $res = db_query_params('UPDATE groups SET scm_box=$1 WHERE group_id=$2', array($scm_box, $this->getID()));
972 $this->addHistory('scm_box', $this->data_array['scm_box']);
973 $this->data_array['scm_box'] = $scm_box;
978 $this->setError(_("Could not insert SCM_BOX to database"));
982 $this->setError(_("SCM Box cannot be empty"));
988 * getDomain - the hostname.domain where their web page is located.
990 * @return string The name of the group [web] domain.
992 function getDomain() {
993 return $this->data_array['http_domain'];
997 * getRegistrationPurpose - the text description of the purpose of this project.
999 * @return string The application for project hosting.
1001 function getRegistrationPurpose() {
1002 return $this->data_array['register_purpose'];
1006 * getAdmins - Get array of Admin user objects.
1008 * @return array Array of User objects.
1010 function &getAdmins() {
1011 $roles = RBACEngine::getInstance()->getRolesByAllowedAction ('project_admin', $this->getID());
1013 $user_ids = array();
1015 foreach ($roles as $role) {
1016 if (! ($role instanceof RoleExplicit)) {
1019 if ($role->getHomeProject() == NULL
1020 || $role->getHomeProject()->getID() != $this->getID()) {
1024 foreach ($role->getUsers() as $u) {
1025 $user_ids[] = $u->getID();
1028 $active_ids = array();
1029 $ids = array_unique ($user_ids);
1030 foreach ($ids as $id) {
1031 $u = user_get_object ($id);
1032 if ($u->isActive()) {
1040 Common Group preferences for tools
1044 * enableAnonSCM - whether or not this group has opted to enable Anonymous SCM.
1046 * @return bool enable_scm.
1048 function enableAnonSCM() {
1049 $r = RoleAnonymous::getInstance();
1050 return $r->hasPermission('scm', $this->getID(), 'read');
1053 function SetUsesAnonSCM($booleanparam) {
1055 $booleanparam = $booleanparam ? 1 : 0;
1056 $r = RoleAnonymous::getInstance();
1057 $r->setSetting('scm', $this->getID(), $booleanparam);
1062 * enablePserver - whether or not this group has opted to enable Pserver.
1064 * @return bool enable_pserver.
1066 function enablePserver() {
1067 if ($this->usesSCM()) {
1068 return $this->data_array['enable_pserver'];
1074 function SetUsesPserver($booleanparam) {
1076 $booleanparam = $booleanparam ? 1 : 0;
1077 $res = db_query_params('UPDATE groups SET enable_pserver=$1 WHERE group_id=$2',
1078 array($booleanparam, $this->getID()));
1080 $this->data_array['enable_pserver'] = $booleanparam;
1090 * usesSCM - whether or not this group has opted to use SCM.
1092 * @return bool uses_scm.
1094 function usesSCM() {
1095 if (forge_get_config('use_scm')) {
1096 return $this->data_array['use_scm'];
1103 * setUseSCM - Set the SCM usage
1105 * @param bool $booleanparam enabled/disabled
1108 function setUseSCM($booleanparam) {
1110 $booleanparam = $booleanparam ? 1 : 0;
1111 $res = db_query_params('UPDATE groups SET use_scm=$1 WHERE group_id=$2',
1112 array($booleanparam, $this->getID()));
1114 $this->data_array['use_scm'] = $booleanparam;
1124 * usesMail - whether or not this group has opted to use mailing lists.
1126 * @return bool uses_mail.
1128 function usesMail() {
1129 if (forge_get_config('use_mail')) {
1130 return $this->data_array['use_mail'];
1137 * setUseMail - Set the mailing-list usage
1139 * @param bool $booleanparam enabled/disabled
1142 function setUseMail($booleanparam) {
1144 $booleanparam = $booleanparam ? 1 : 0;
1145 $res = db_query_params('UPDATE groups SET use_mail=$1 WHERE group_id=$2',
1146 array($booleanparam, $this->getID()));
1148 $this->data_array['use_mail'] = $booleanparam;
1158 * usesNews - whether or not this group has opted to use news.
1160 * @return bool uses_news.
1162 function usesNews() {
1163 if (forge_get_config('use_news')) {
1164 return $this->data_array['use_news'];
1170 function setUseNews($booleanparam) {
1172 $booleanparam = $booleanparam ? 1 : 0;
1173 $res = db_query_params('UPDATE groups SET use_news=$1 WHERE group_id=$2',
1174 array($booleanparam, $this->getID()));
1176 $this->data_array['use_news'] = $booleanparam;
1186 * usesActivity - whether or not this group has opted to display Project Activities.
1188 * @return bool uses_activities.
1190 function usesActivity() {
1191 if (forge_get_config('use_activity')) {
1192 return $this->data_array['use_activity'];
1198 function setUseActivity($booleanparam) {
1200 $booleanparam = $booleanparam ? 1 : 0;
1201 $res = db_query_params('UPDATE groups SET use_activity=$1 WHERE group_id=$2',
1202 array($booleanparam, $this->getID()));
1204 $this->data_array['use_activity'] = $booleanparam;
1214 * usesForum - whether or not this group has opted to use discussion forums.
1216 * @return bool uses_forum.
1218 function usesForum() {
1219 if (forge_get_config('use_forum')) {
1220 return $this->data_array['use_forum'];
1227 * setUseForum - Set the forum usage
1229 * @param bool $booleanparam enabled/disabled
1232 function setUseForum($booleanparam) {
1234 $booleanparam = $booleanparam ? 1 : 0;
1235 $res = db_query_params('UPDATE groups SET use_forum=$1 WHERE group_id=$2',
1236 array($booleanparam, $this->getID()));
1238 $this->data_array['use_forum'] = $booleanparam;
1248 * usesStats - whether or not this group has opted to use stats.
1250 * @return bool uses_stats.
1252 function usesStats() {
1253 return $this->data_array['use_stats'];
1257 * usesFRS - whether or not this group has opted to use file release system.
1259 * @return bool uses_frs.
1261 function usesFRS() {
1262 if (forge_get_config('use_frs')) {
1263 return $this->data_array['use_frs'];
1270 * setUseFRS - Set the FRS usage
1272 * @param bool $booleanparam enabled/disabled
1275 function setUseFRS($booleanparam) {
1277 $booleanparam = $booleanparam ? 1 : 0;
1278 $res = db_query_params('UPDATE groups SET use_frs=$1 WHERE group_id=$2',
1279 array($booleanparam, $this->getID()));
1281 $this->data_array['use_frs']=$booleanparam;
1290 * usesTracker - whether or not this group has opted to use tracker.
1292 * @return bool uses_tracker.
1294 function usesTracker() {
1295 if (forge_get_config('use_tracker')) {
1296 return $this->data_array['use_tracker'];
1302 * setUseTracker - Set the tracker usage
1304 * @param bool $booleanparam enabled/disabled
1307 function setUseTracker($booleanparam) {
1309 $booleanparam = $booleanparam ? 1 : 0;
1310 $res = db_query_params ('UPDATE groups SET use_tracker=$1 WHERE group_id=$2',
1311 array($booleanparam, $this->getID()));
1313 $this->data_array['use_tracker']=$booleanparam;
1322 * useCreateOnline - whether or not this group has opted to use create online documents option.
1324 * @return bool use_docman_create_online.
1326 function useCreateOnline() {
1327 if (forge_get_config('use_docman')) {
1328 return $this->data_array['use_docman_create_online'];
1334 * usesDocman - whether or not this group has opted to use docman.
1336 * @return bool use_docman.
1338 function usesDocman() {
1339 if (forge_get_config('use_docman')) {
1340 return $this->data_array['use_docman'];
1346 * setUseDocman - Set the docman usage
1348 * @param bool $booleanparam enabled/disabled
1351 function setUseDocman($booleanparam) {
1353 $booleanparam = $booleanparam ? 1 : 0;
1354 $res = db_query_params('UPDATE groups SET use_docman = $1 WHERE group_id = $2',
1355 array($booleanparam, $this->getID()));
1357 // check if / doc_group exists, if not create it
1358 $trashdir = db_query_params('select groupname from doc_groups where groupname = $1 and group_id = $2',
1359 array('.trash', $this->getID()));
1360 if ($trashdir && db_numrows($trashdir) == 0) {
1361 $resinsert = db_query_params('insert into doc_groups (groupname, group_id, stateid) values ($1, $2, $3)',
1362 array('.trash', $this->getID(), '2'));
1368 $this->data_array['use_docman'] = $booleanparam;
1377 * useDocmanSearch - whether or not this group has opted to use docman search engine.
1379 * @return bool use_docman_search.
1381 function useDocmanSearch() {
1382 if (forge_get_config('use_docman')) {
1383 return $this->data_array['use_docman_search'];
1389 * useWebdav - whether or not this group has opted to use webdav interface.
1391 * @return bool use_docman_search.
1393 function useWebdav() {
1394 if (forge_get_config('use_webdav')) {
1395 return $this->data_array['use_webdav'];
1401 * usesFTP - whether or not this group has opted to use FTP.
1403 * @return bool uses_ftp.
1405 function usesFTP() {
1406 if (forge_get_config('use_ftp')) {
1407 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'];
1425 * usesPM - whether or not this group has opted to Project Manager.
1427 * @return bool uses_projman.
1430 if (forge_get_config('use_pm')) {
1431 return $this->data_array['use_pm'];
1437 * setUsePM - Set the PM usage
1439 * @param bool $booleanparam enabled/disabled
1442 function setUsePM($booleanparam) {
1444 $booleanparam = $booleanparam ? 1 : 0;
1445 $res = db_query_params('UPDATE groups SET use_pm=$1 WHERE group_id=$2',
1446 array($booleanparam, $this->getID()));
1448 $this->data_array['use_pm']=$booleanparam;
1457 * getPlugins - get a list of all available group plugins
1459 * @return array array containing plugin_id => plugin_name
1461 function getPlugins() {
1462 if (!isset($this->plugins_data)) {
1463 $this->plugins_data = array();
1464 $res = db_query_params('SELECT group_plugin.plugin_id, plugins.plugin_name
1465 FROM group_plugin, plugins
1466 WHERE group_plugin.group_id=$1
1467 AND group_plugin.plugin_id=plugins.plugin_id', array($this->getID()));
1468 $rows = db_numrows($res);
1470 for ($i=0; $i<$rows; $i++) {
1471 $plugin_id = db_result($res, $i, 'plugin_id');
1472 $this->plugins_data[$plugin_id] = db_result($res, $i, 'plugin_name');
1475 return $this->plugins_data;
1479 * usesPlugin - returns true if the group uses a particular plugin
1481 * @param string $pluginname name of the plugin
1482 * @return bool whether plugin is being used or not
1484 function usesPlugin($pluginname) {
1485 $plugins_data = $this->getPlugins();
1486 foreach ($plugins_data as $p_name) {
1487 if ($p_name == $pluginname) {
1495 * added for Codendi compatibility
1496 * usesServices - returns true if the group uses a particular plugin or feature
1498 * @param string $feature name of the plugin
1499 * @return bool whether plugin is being used or not
1501 function usesService($feature) {
1502 $plugins_data = $this->getPlugins();
1503 $pm = plugin_manager_get_object();
1504 foreach ($plugins_data as $p_name) {
1505 if ($p_name == $feature) {
1508 if (is_object($pm->getPluginByName($p_name)) && $pm->getPluginByName($p_name)->provide($feature)) {
1516 * setPluginUse - enables/disables plugins for the group
1518 * @param string $pluginname name of the plugin
1519 * @param bool $val the new state
1520 * @return string database result
1522 function setPluginUse($pluginname, $val=true) {
1523 if ($val == $this->usesPlugin($pluginname)) {
1524 // State is already good, returning
1527 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1528 array($pluginname));
1529 $rows = db_numrows($res);
1531 // Error: no plugin by that name
1534 $plugin_id = db_result($res,0,'plugin_id');
1536 unset($this->plugins_data);
1538 $res = db_query_params('INSERT INTO group_plugin (group_id, plugin_id) VALUES ($1, $2)',
1539 array($this->getID(),
1542 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1 AND plugin_id=$2',
1543 array($this->getID(),
1546 $this->normalizeAllRoles();
1547 $hook_params = array();
1548 $hook_params['group_id'] = $this->getID();
1549 $hook_params['val'] = $val;
1550 plugin_hook("group_plugin_use", $hook_params);
1555 * getDocEmailAddress - get email address(es) to send doc notifications to.
1557 * @return string email address.
1559 function getDocEmailAddress() {
1560 return $this->data_array['new_doc_address'];
1563 function setDocEmailAddress($email) {
1564 $invalid_mails = validate_emails($email);
1565 if (count($invalid_mails) > 0) {
1566 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
1570 $res = db_query_params('UPDATE groups SET new_doc_address = $1 WHERE group_id = $2',
1571 array($email, $this->getID()));
1574 $this->setError(_('Error')._(': ')._('Cannot Update Group new_doc_address')._(': ').db_error());
1578 $this->data_array['new_doc_address'] = $email;
1584 * docEmailAll - whether or not this group has opted to use receive notices on all doc updates.
1586 * @return bool email_on_all_doc_updates.
1588 function docEmailAll() {
1589 return $this->data_array['send_all_docs'];
1592 function setDocEmailAll($status) {
1594 $res = db_query_params('UPDATE groups SET send_all_docs = $1 WHERE group_id = $2',
1595 array($status, $this->getID()));
1598 $this->setError(_('Error')._(': ')._('Cannot Update Group send_all_docs')._(': ').db_error());
1602 $this->data_array['send_all_docs'] = $status;
1608 * getFRSEmailAddress - get email address(es) to send FRS notifications to.
1610 * @return string email address.
1612 function getFRSEmailAddress() {
1613 return $this->data_array['new_frs_address'];
1616 function setFRSEmailAddress($email) {
1617 $invalid_mails = validate_emails($email);
1618 if (count($invalid_mails) > 0) {
1619 $this->setError(sprintf(ngettext('New FRS Address Appeared Invalid: %s', 'New FRS Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
1623 $res = db_query_params('UPDATE groups SET new_frs_address = $1 WHERE group_id = $2',
1624 array($email, $this->getID()));
1627 $this->setError(_('Error')._(': ')._('Cannot Update Group new_frs_address')._(': ').db_error());
1631 $this->data_array['new_frs_address'] = $email;
1637 * frsEmailAll - whether or not this group has opted to use receive notices on all frs updates.
1639 * @return bool email_on_all_frs_updates.
1641 function frsEmailAll() {
1642 return $this->data_array['send_all_frs'];
1645 function setFRSEmailAll($status) {
1647 $res = db_query_params('UPDATE groups SET send_all_frs = $1 WHERE group_id = $2',
1648 array($status, $this->getID()));
1651 $this->setError(_('Error')._(': ')._('Cannot Update Group send_frs_docs')._(': ').db_error());
1655 $this->data_array['send_frs_docs'] = $status;
1661 * getHomePage - The URL for this project's home page.
1663 * @return string homepage URL.
1665 function getHomePage() {
1666 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9+.-]*:/", $this->data_array['homepage'])) {
1667 $this->data_array['homepage'] = 'http://'.$this->data_array['homepage'];
1669 return $this->data_array['homepage'];
1673 * setHomepage - the hostname of the website url where this project is located.
1675 * @param string $homepage The name of the new HOMEPAGE
1678 function setHomepage($homepage) {
1679 if ($homepage == $this->data_array['homepage']) {
1684 $res = db_query_params('UPDATE groups SET homepage=$1 WHERE group_id=$2', array($homepage, $this->getID()));
1686 $this->addHistory('homepage', $this->data_array['homepage']);
1687 $this->data_array['homepage'] = $homepage;
1692 $this->setError(_('Could not insert homepage to database'));
1695 $this->setError(_('Homepage cannot be empty'));
1700 * getTags - Tags of this project.
1702 * @return string List of tags. Comma separated
1704 function getTags() {
1705 $sql = 'SELECT name FROM project_tags WHERE group_id = $1';
1706 $res = db_query_params($sql, array($this->getID()));
1707 return join(', ', util_result_column_to_array($res));
1711 * setTags - Set tags of this project.
1713 * @param string $tags
1714 * @return string database result.
1716 function setTags($tags) {
1718 $sql = 'DELETE FROM project_tags WHERE group_id=$1';
1719 $res = db_query_params($sql, array($this->getID()));
1721 $this->setError(_('Deleting old tags')._(': ').db_error());
1725 $inserted = array();
1726 $tags_array = preg_split('/[;,]/', $tags);
1727 foreach ($tags_array as $tag) {
1728 $tag = preg_replace('/[\t\r\n]/', ' ', $tag);
1729 // Allowed caracteres: [A-Z][a-z][0-9] -_&'#+.
1730 if (preg_match('/[^[:alnum:]| |\-|_|\&|\'|#|\+|\.]/', $tag)) {
1731 $this->setError(_('Bad tag name, you only can use the following characters: [A-Z][a-z][0-9]-_&\'#+. and space'));
1736 if ($tag == '' || array_search($tag, $inserted) !== false) {
1739 $sql = 'INSERT INTO project_tags (group_id,name) VALUES ($1, $2)';
1740 $res = db_query_params($sql, array($this->getID(), $tag));
1742 $this->setError(_('Setting tags')._(': ').db_error());
1753 * getPermission - Return a Permission for this Group
1755 * @return object The Permission.
1757 function &getPermission() {
1758 return permission_get_object($this);
1761 function delete($sure, $really_sure, $really_really_sure) {
1762 if (!$sure || !$really_sure || !$really_really_sure) {
1763 $this->setMissingParamsError(_('Please tick all checkboxes.'));
1766 if ($this->getID() == GROUP_IS_NEWS ||
1767 $this->getID() == GROUP_IS_MASTER ||
1768 $this->getID() == GROUP_IS_STATS ||
1769 $this->getID() == GROUP_IS_PEER_RATINGS) {
1770 $this->setError(_('Cannot Delete System Group'));
1773 $perm = $this->getPermission();
1774 if (!$perm || !is_object($perm)) {
1775 $this->setPermissionDeniedError();
1777 } elseif ($perm->isError() || !$perm->isSuperUser()) {
1778 $this->setPermissionDeniedError();
1784 // Remove all the members
1786 $members = $this->getMembers(false);
1787 foreach ($members as $i) {
1788 if(!$this->removeUser($i->getID())) {
1789 $this->setError(_('Could not properly remove member')._(': ').$i->getID());
1794 // unlink roles from this project
1795 foreach ($this->getRoles() as $r) {
1796 if ($r->getHomeProject() == NULL
1797 || $r->getHomeProject()->getID() != $this->getID()) {
1798 $r->unlinkProject($this);
1805 $atf = new ArtifactTypeFactory($this, true);
1806 $at_arr = $atf->getArtifactTypes();
1807 foreach ($at_arr as $i) {
1808 if (!is_object($i)) {
1811 if (!$i->delete(1,1)) {
1812 $this->setError(_('Could not properly delete the tracker')._(': ').$i->getErrorMessage());
1819 $rmf = new RoadmapFactory($this);
1820 $rm_arr = $rmf->getRoadmaps();
1821 foreach ($rm_arr as $i) {
1822 if (!is_object($i)) {
1825 if (!$i->delete()) {
1826 $this->setError(_('Could not properly delete the roadmap')._(': ').$i->getErrorMessage());
1834 $ff = new ForumFactory($this, true);
1835 $f_arr = $ff->getForums();
1836 foreach ($f_arr as $i) {
1837 if (!is_object($i)) {
1840 if(!$i->delete(1,1)) {
1841 $this->setError(_('Could not properly delete the forum')._(': ').$i->getErrorMessage());
1847 // Delete Subprojects
1849 $pgf = new ProjectGroupFactory($this, true);
1850 $pg_arr = $pgf->getProjectGroups();
1851 foreach ($pg_arr as $i) {
1852 if (!is_object($i)) {
1855 if (!$i->delete(1,1)) {
1856 $this->setError(_('Could not properly delete the ProjectGroup')._(': ').$i->getErrorMessage());
1862 // Delete FRS Packages
1864 $res = db_query_params('SELECT * FROM frs_package WHERE group_id=$1',
1865 array($this->getID()));
1867 $this->setError(_('Error FRS Packages')._(': ').db_error());
1872 while ($arr = db_fetch_array($res)) {
1873 $frsp=new FRSPackage($this, $arr['package_id'], $arr);
1874 if (!$frsp->delete(1, 1)) {
1875 $this->setError(_('Could not properly delete the FRSPackage')._(': ').$frsp->getErrorMessage());
1882 $news_group = group_get_object(GROUP_IS_NEWS);
1883 $res = db_query_params('SELECT forum_id FROM news_bytes WHERE group_id=$1',
1884 array($this->getID()));
1886 $this->setError(_('Error Deleting News')._(': ').db_error());
1891 for ($i=0; $i<db_numrows($res); $i++) {
1892 $Forum = new Forum($news_group,db_result($res,$i,'forum_id'));
1893 if (!$Forum->delete(1,1)) {
1894 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1899 // Delete news forums in group itself
1900 for ($i = 0; $i < db_numrows($res); $i++) {
1901 $Forum = new Forum($this, db_result($res, $i, 'forum_id'));
1902 if (!$Forum->delete(1, 1)) {
1903 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1908 $res = db_query_params('DELETE FROM news_bytes WHERE group_id=$1',
1909 array($this->getID()));
1911 $this->setError(_('Error Deleting News')._(': ').db_error());
1919 $res = db_query_params('DELETE FROM doc_data WHERE group_id=$1',
1920 array($this->getID()));
1922 $this->setError(_('Error Deleting Documents')._(': ').db_error());
1927 $res = db_query_params('DELETE FROM doc_groups WHERE group_id=$1',
1928 array($this->getID()));
1930 $this->setError(_('Error Deleting Document Groups')._(': ').db_error());
1938 $res=db_query_params('DELETE FROM project_tags WHERE group_id=$1', array($this->getID()));
1940 $this->setError(_('Error Deleting Tags')._(': ').db_error());
1946 // Delete group history
1948 $res = db_query_params('DELETE FROM group_history WHERE group_id=$1',
1949 array($this->getID()));
1951 $this->setError(_('Error Deleting Project History')._(': ').db_error());
1957 // Delete group plugins
1959 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1',
1960 array($this->getID()));
1962 $this->setError(_('Error Deleting Project Plugins')._(': ').db_error());
1968 // Delete group cvs stats
1970 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE group_id=$1',
1971 array($this->getID()));
1973 $this->setError(_('Error Deleting SCM Statistics')._(': ').db_error());
1981 $sf = new SurveyFactory($this, true);
1982 $s_arr =& $sf->getSurveys();
1983 foreach ($s_arr as $i) {
1984 if (!is_object($i)) {
1987 if (!$i->delete()) {
1988 $this->setError(_('Could not properly delete the survey'));
1993 // Delete SurveyQuestions
1995 $sqf = new SurveyQuestionFactory($this);
1996 $sq_arr = $sqf->getSurveyQuestions();
1997 if (is_array($sq_arr)) {
1998 foreach ($sq_arr as $i) {
1999 if (!is_object($i)) {
2002 if (!$i->delete()) {
2003 $this->setError(_('Could not properly delete the survey questions'));
2011 // Delete Mailing List Factory
2013 $mlf = new MailingListFactory($this, true);
2014 $ml_arr = $mlf->getMailingLists();
2015 foreach ($ml_arr as $i) {
2016 if (!is_object($i)) {
2019 if (!$i->delete(1,1)) {
2020 $this->setError(_('Could not properly delete the mailing list'));
2028 $res = db_query_params('DELETE FROM trove_group_link WHERE group_id=$1',
2029 array($this->getID()));
2031 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2036 $res = db_query_params('DELETE FROM trove_agg WHERE group_id=$1',
2037 array($this->getID()));
2039 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2047 $res = db_query_params('DELETE FROM project_sums_agg WHERE group_id=$1',
2048 array($this->getID()));
2050 $this->setError(_('Error Deleting Counters')._(': ').db_error());
2055 $res = db_query_params('INSERT INTO deleted_groups (unix_group_name, delete_date, isdeleted) VALUES ($1, $2, $3)',
2056 array($this->getUnixName(),
2060 $this->setError(_('Error Deleting Project')._(': ').db_error());
2065 // Remove users & delete roles from this project
2066 $members = $this->getMembers();
2067 foreach ($members as $userObject) {
2068 $this->removeUser($userObject->getID());
2070 $localRolesId = $this->getRolesId(false);
2071 foreach ($localRolesId as $localRoleId) {
2072 $roleObject = new Role($this, $localRoleId);
2073 $roleObject->delete();
2075 // Delete entry in groups.
2076 $res = db_query_params('DELETE FROM groups WHERE group_id=$1',
2077 array($this->getID()));
2079 $this->setError(_('Error Deleting Project')._(': ').db_error());
2086 $hook_params = array();
2087 $hook_params['group'] = $this;
2088 $hook_params['group_id'] = $this->getID();
2089 plugin_hook("group_delete", $hook_params);
2091 if (forge_get_config('upload_dir') != '' && $this->getUnixName()) {
2092 exec('/bin/rm -rf '.forge_get_config('upload_dir').'/'.$this->getUnixName().'/');
2094 if (forge_get_config('ftp_upload_dir') != '' && $this->getUnixName()) {
2095 exec('/bin/rm -rf '.forge_get_config('ftp_upload_dir').'/'.$this->getUnixName().'/');
2100 db_query_params('DELETE FROM rep_group_act_monthly WHERE group_id=$1', array($this->getID()));
2101 db_query_params('DELETE FROM rep_group_act_weekly WHERE group_id=$1', array($this->getID()));
2102 db_query_params('DELETE FROM rep_group_act_daily WHERE group_id=$1', array($this->getID()));
2103 unset($this->data_array);
2108 Basic functions to add/remove users to/from a group
2109 and update their permissions
2113 * addUser - controls adding a user to a group.
2115 * @param string $user_identifier Unix name of the user to add OR integer user_id.
2116 * @param int $role_id The role_id this user should have.
2117 * @return bool success.
2120 function addUser($user_identifier, $role_id) {
2123 Admins can add users to groups
2126 if (!forge_check_perm ('project_admin', $this->getID())) {
2127 $this->setPermissionDeniedError();
2133 get user id for this user's unix_name
2135 if (is_int ($user_identifier)) { // user_id or user_name
2136 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_id=$1', array($user_identifier));
2138 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_name=$1', array($user_identifier));
2140 if (db_numrows($res_newuser) > 0) {
2142 // make sure user is active
2144 if (db_result($res_newuser,0,'status') != 'A') {
2145 $this->setError(_('User is not active. Only active users can be added.'));
2151 // user was found - set new user_id var
2153 $user_id = db_result($res_newuser,0,'user_id');
2155 $role = new Role($this, $role_id);
2156 if (!$role || !is_object($role)) {
2157 $this->setError(_('Error Getting Role Object'));
2160 } elseif ($role->isError()) {
2161 $this->setError('addUser::roleget::'.$role->getErrorMessage());
2166 $role->addUser(user_get_object($user_id));
2167 if (!$SYS->sysCheckCreateGroup($this->getID())){
2168 $this->setError($SYS->getErrorMessage());
2172 if (!$SYS->sysCheckCreateUser($user_id)) {
2173 $this->setError($SYS->getErrorMessage());
2177 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2178 $this->setError($SYS->getErrorMessage());
2184 // user doesn't exist
2186 $this->setError(_('That user does not exist.'));
2191 $hook_params['group'] = $this;
2192 $hook_params['group_id'] = $this->getID();
2193 $hook_params['user'] = user_get_object($user_id);
2194 $hook_params['user_id'] = $user_id;
2195 plugin_hook ("group_adduser", $hook_params);
2200 $this->addHistory(_('Added User'), $user_identifier);
2206 $add_u = user_get_object($user_id);
2208 if (is_array($this->membersArr)) {
2209 foreach ($this->membersArr as $u) {
2210 if ($u->getID() == $add_u->getID()) {
2216 $this->membersArr[] = $add_u;
2224 * removeUser - controls removing a user from a group.
2226 * Users can remove themselves.
2228 * @param int $user_id The ID of the user to remove.
2229 * @return bool success.
2231 function removeUser($user_id) {
2234 if ($user_id != user_getid()
2235 && !forge_check_perm('project_admin', $this->getID())) {
2236 $this->setPermissionDeniedError();
2242 $user = user_get_object($user_id);
2243 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
2244 $found_roles = array();
2245 foreach ($roles as $role) {
2246 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2247 $found_roles[] = $role;
2250 if (empty($found_roles)) {
2251 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2255 foreach ($found_roles as $found_role) {
2256 $found_role->removeUser($user);
2257 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
2258 $this->setError($SYS->getErrorMessage());
2265 // reassign open artifacts to id=100
2267 $res = db_query_params('UPDATE artifact SET assigned_to=100
2268 WHERE group_artifact_id
2269 IN (SELECT group_artifact_id
2270 FROM artifact_group_list
2271 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
2272 array($this->getID(),
2275 $this->setError(_('Error')._(': ')._('artifact')._(': ').db_error());
2281 // reassign open tasks to id=100
2282 // first have to purge any assignments that would cause
2283 // conflict with existing assignment to 100
2285 $res = db_query_params('DELETE FROM project_assigned_to
2286 WHERE project_task_id IN (SELECT pt.project_task_id
2287 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2288 WHERE pt.group_project_id = pgl.group_project_id
2289 AND pat.project_task_id=pt.project_task_id
2290 AND pt.status_id=1 AND pgl.group_id=$1
2291 AND pat.assigned_to_id=$2)
2292 AND assigned_to_id=100',
2293 array($this->getID(),
2296 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 1, db_error()));
2300 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2301 WHERE project_task_id IN (SELECT pt.project_task_id
2302 FROM project_task pt, project_group_list pgl
2303 WHERE pt.group_project_id = pgl.group_project_id
2304 AND pt.status_id=1 AND pgl.group_id=$1)
2305 AND assigned_to_id=$2',
2306 array($this->getID(),
2309 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 2, db_error()));
2315 // Remove user from system
2317 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2318 $this->setError($SYS->getErrorMessage());
2323 $hook_params['group'] = $this;
2324 $hook_params['group_id'] = $this->getID();
2325 $hook_params['user'] = user_get_object($user_id);
2326 $hook_params['user_id'] = $user_id;
2327 plugin_hook("group_removeuser", $hook_params);
2330 $this->addHistory(_('Removed User'), $user_id);
2337 $del_u = user_get_object($user_id);
2338 foreach ($this->membersArr as $k => $u) {
2339 if ($u->getID() == $del_u->getID()) {
2340 unset($this->membersArr[$k]);
2349 * updateUser - controls updating a user's role in this group.
2351 * @param int $user_id The ID of the user.
2352 * @param int $role_id The role_id to set this user to.
2353 * @return bool success.
2355 function updateUser($user_id, $role_id) {
2357 if (!forge_check_perm ('project_admin', $this->getID())) {
2358 $this->setPermissionDeniedError();
2362 $newrole = RBACEngine::getInstance()->getRoleById ($role_id);
2363 if (!$newrole || !is_object($newrole)) {
2364 $this->setError(_('Could Not Get Role'));
2366 } elseif ($newrole->isError()) {
2367 $this->setError(_('Role')._(': ').$newrole->getErrorMessage());
2369 } elseif ($newrole->getHomeProject() == NULL
2370 || $newrole->getHomeProject()->getID() != $this->getID()) {
2371 $this->setError(_('Wrong destination role'));
2374 $user = user_get_object ($user_id);
2375 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user);
2377 foreach ($roles as $role) {
2378 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2379 $found_role = $role;
2383 if ($found_role == NULL) {
2384 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2388 $found_role->removeUser ($user);
2389 $newrole->addUser ($user);
2391 $this->addHistory(_('Updated User'), $user_id);
2396 * addHistory - Makes an audit trail entry for this project.
2398 * @param string $field_name The name of the field.
2399 * @param string $old_value The Old Value for this $field_name.
2400 * @return resource database result handle.
2403 function addHistory($field_name, $old_value) {
2404 if ($old_value == NULL) {
2408 return db_query_params('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2409 VALUES ($1,$2,$3,$4,$5)',
2410 array($this->getID(),
2418 * activateUsers - Make sure that group members have unix accounts.
2420 * Setup unix accounts for group members. Can be called even
2421 * if members are already active.
2425 function activateUsers() {
2427 Activate member(s) of the project
2432 $members = $this->getUsers(true);
2434 foreach ($members as $member) {
2435 $user_id = $member->getID();
2437 if (!$SYS->sysCheckCreateGroup($this->getID())){
2438 $this->setError($SYS->getErrorMessage());
2442 if (!$SYS->sysCheckCreateUser($user_id)) {
2443 $this->setError($SYS->getErrorMessage());
2447 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2448 $this->setError($SYS->getErrorMessage());
2458 * getMembers - returns array of User objects for this project
2460 * @param bool $onlyactive Only users with state active, or all users of group
2461 * @return array of User objects for this group.
2463 function getMembers($onlyactive = true) {
2464 return $this->getUsers(true, $onlyactive);
2468 * replaceTemplateStrings - fill-in some blanks with project name
2470 * @param string $string Template string
2471 * @return string String after replacements
2473 function replaceTemplateStrings($string) {
2474 $string = str_replace('UNIXNAME', $this->getUnixName(), $string);
2475 $string = str_replace('PUBLICNAME', $this->getPublicName(), $string);
2476 $string = str_replace('DESCRIPTION', $this->getDescription(), $string);
2481 * approve - Approve pending project.
2483 * @param object $user The User object who is doing the updating.
2487 function approve(&$user) {
2488 global $gfcommon,$gfwww;
2489 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2491 if ($this->getStatus()=='A') {
2492 $this->setError(_('Group already active'));
2498 // Step 1: Activate group and create LDAP entries
2499 if (!$this->setStatus($user, 'A')) {
2506 // Switch to system language for item creation
2507 setup_gettext_from_sys_lang();
2509 // Create default roles
2510 $idadmin_group = NULL;
2511 foreach (get_group_join_requests ($this) as $gjr) {
2512 $idadmin_group = $gjr->getUserID();
2515 if ($idadmin_group == NULL) {
2516 $idadmin_group = $user->getID();
2519 $template = $this->getTemplateProject();
2520 $id_mappings = array();
2521 $seen_admin_role = false;
2523 // Copy roles from template project
2524 foreach($template->getRoles() as $oldrole) {
2525 if ($oldrole->getHomeProject() != NULL) {
2526 $role = new Role($this);
2528 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2529 $role->create('TEMPORARY ROLE NAME', $data, true);
2530 $role->setName($oldrole->getName());
2531 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2532 $seen_admin_role = true;
2536 $role->linkProject($this);
2538 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2539 // Reuse the project_admin permission
2540 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID()));
2544 if (!$seen_admin_role) {
2545 $role = new Role($this);
2546 $adminperms = array('project_admin' => array ($this->getID() => 1));
2547 $role->create ('Admin', $adminperms, true);
2550 $roles = $this->getRoles();
2551 foreach ($roles as $r) {
2552 if ($r->getHomeProject() == NULL) {
2555 if ($r->getSetting ('project_admin', $this->getID())) {
2556 $r->addUser(user_get_object ($idadmin_group));
2560 // Temporarily switch to the submitter's identity
2561 $saved_session = session_get_user();
2562 session_set_internal($idadmin_group);
2565 if (forge_get_config('use_tracker')) {
2566 $this->setUseTracker ($template->usesTracker());
2567 if ($template->usesTracker()) {
2568 $oldatf = new ArtifactTypeFactory($template);
2569 foreach ($oldatf->getArtifactTypes() as $o) {
2570 $t = new ArtifactType ($this);
2571 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions());
2572 $id_mappings['tracker'][$o->getID()] = $t->getID();
2577 if (forge_get_config('use_pm')) {
2578 $this->setUsePM ($template->usesPM());
2579 if ($template->usesPM()) {
2580 $oldpgf = new ProjectGroupFactory($template);
2581 foreach ($oldpgf->getProjectGroups() as $o) {
2582 $pg = new ProjectGroup($this);
2583 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2584 $id_mappings['pm'][$o->getID()] = $pg->getID();
2589 if (forge_get_config('use_forum')) {
2590 $this->setUseForum($template->usesForum());
2591 if ($template->usesForum()) {
2592 $oldff = new ForumFactory($template);
2593 foreach ($oldff->getForums() as $o) {
2594 $f = new Forum($this);
2595 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo(),1);
2596 $id_mappings['forum'][$o->getID()] = $f->getID();
2601 if (forge_get_config('use_docman')) {
2602 $this->setUseDocman($template->usesDocman());
2603 if ($template->usesDocman()) {
2604 $olddgf = new DocumentGroupFactory($template);
2605 // First pass: create all docgroups
2606 $id_mappings['docman_docgroup'][0] = 0;
2607 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2608 $ndg = new DocumentGroup($this);
2609 // .trash is a reserved directory
2610 if ($o->getName() != '.trash') {
2611 $ndg->create($this->replaceTemplateStrings($o->getName()), 0, 1, null, true);
2612 $id_mappings['docman_docgroup'][$o->getID()] = $ndg->getID();
2615 // Second pass: restore hierarchy links & stateid
2616 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2617 $ndgf = new DocumentGroup($this);
2618 if ($o->getName() != '.trash') {
2619 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2620 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()], 0, $o->getState());
2626 if (forge_get_config('use_frs')) {
2627 $this->setUseFRS ($template->usesFRS());
2628 if ($template->usesFRS()) {
2629 foreach (get_frs_packages($template) as $o) {
2630 $newp = new FRSPackage($this);
2631 $nname = $this->replaceTemplateStrings($o->getName());
2632 $newp->create($nname, $o->isPublic());
2633 $id_mappings['frs'][$o->getID()] = $newp->getID();
2634 foreach(get_frs_releases($o) as $or) {
2635 $newr = new FRSRelease($newp);
2636 $newr->create($this->replaceTemplateStrings($or->getName()), $this->replaceTemplateStrings($or->getNotes()), $this->replaceTemplateStrings($or->getChanges()), $or->getPreformatted());
2637 $id_mappings['frs_release'][$or->getID()] = $newr->getID();
2643 if (forge_get_config('use_mail')) {
2644 $this->setUseMail($template->usesMail());
2645 if ($template->usesMail()) {
2646 $oldmlf = new MailingListFactory($template);
2647 foreach ($oldmlf->getMailingLists() as $o) {
2648 $ml = new MailingList($this);
2649 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName());
2651 $ndescription = $this->replaceTemplateStrings($o->getDescription());
2652 $ml->create($nname, $ndescription, $o->isPublic());
2658 /* use SCM plugin from template group */
2659 $this->setUseSCM($template->usesSCM());
2661 foreach ($template->getPlugins() as $plugin_name) {
2662 $this->setPluginUse($plugin_name);
2665 /* use SCM choice from registration page */
2666 foreach ($template->getPlugins() as $plugin_name) {
2667 if (substr($plugin_name, 3) == 'scm' && $plugin_name != 'scmhook') {
2668 /* skip copying scm plugins */
2671 /* enable other plugins though */
2672 $this->setPluginUse($plugin_name);
2676 foreach ($template->getRoles() as $oldrole) {
2677 $newrole = RBACEngine::getInstance()->getRoleById($id_mappings['role'][$oldrole->getID()]);
2678 if ($oldrole->getHomeProject() != NULL
2679 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2680 $newrole->setPublic ($oldrole->isPublic());
2682 $oldsettings = $oldrole->getSettingsForProject ($template);
2684 $sections = array('project_read', 'project_admin', 'scm', 'docman', 'tracker_admin', 'new_tracker', 'forum_admin', 'new_forum', 'pm_admin', 'new_pm', 'frs_admin', 'new_frs', 'members');
2685 foreach ($sections as $section) {
2686 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]);
2689 $sections = array('tracker', 'pm', 'forum', 'frs');
2690 foreach ($sections as $section) {
2691 if (isset ($oldsettings[$section])) {
2692 foreach ($oldsettings[$section] as $k => $v) {
2693 // Only copy perms for tools that have been copied
2694 if (isset ($id_mappings[$section][$k])) {
2695 $newrole->setSetting ($section,
2696 $id_mappings[$section][$k],
2704 $lm = new WidgetLayoutManager();
2705 $lm->createDefaultLayoutForProject($this->getID(), $template->getID());
2707 // second computation to clone fields and workflow
2708 if (forge_get_config('use_tracker')) {
2709 if ($template->usesTracker()) {
2710 $oldatf = new ArtifactTypeFactory($template);
2711 foreach ($oldatf->getArtifactTypes() as $o) {
2712 $t = artifactType_get_object($id_mappings['tracker'][$o->getID()]);
2713 $id_mappings['tracker'][$o->getID()] = $t->getID();
2714 $newEFIds = $t->cloneFieldsFrom($o->getID(), $id_mappings);
2715 if (forge_get_config('use_tracker_widget_display')) {
2716 $lm->createDefaultLayoutForTracker($t->getID(), $o->getID(), $newEFIds);
2723 $params['template'] = $template;
2724 $params['project'] = $this;
2725 $params['id_mappings'] = $id_mappings;
2726 plugin_hook_by_reference ('clone_project_from_template', $params);
2728 // Disable everything - except use_scm (manually set in the registration page)
2729 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,
2730 use_docman = 0, use_ftp = 0, use_tracker = 0, use_frs = 0, use_stats = 0 WHERE group_id = $1',
2731 array($this->getID()));
2734 $this->normalizeAllRoles();
2735 // empty members cache because the group creator is not yet in cache.
2736 unset($this->membersArr);
2737 $this->activateUsers();
2739 // Delete fake join request
2740 foreach (get_group_join_requests ($this) as $gjr) {
2744 // Switch back to user preference
2745 session_set_internal($saved_session->getID());
2746 setup_gettext_from_context();
2748 $this->sendApprovalEmail();
2749 $this->addHistory(_('Approved'), 'x');
2752 // Plugin can make approve operation there
2755 $params['group'] = $this;
2756 $params['group_id'] = $this->getID();
2757 plugin_hook('group_approved', $params);
2763 * sendApprovalEmail - Send new project email.
2765 * @return bool success.
2768 function sendApprovalEmail() {
2769 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID());
2771 if (empty($admins)) {
2772 $this->setError(_('Group does not have any administrators.'));
2776 // send one email per admin
2777 foreach ($admins as $admin) {
2778 setup_gettext_for_user ($admin);
2780 $message = sprintf(_('Your project registration for %s has been approved.'), forge_get_config ('forge_name')) . "\n\n"
2782 . _('Project Full Name')._(': '). htmlspecialchars_decode($this->getPublicName()) . "\n"
2783 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2785 . _('Your DNS will take up to a day to become active on our site. '
2786 .'Your web site is accessible through your shell account. Please read '
2787 .'site documentation (see link below) about intended usage, available '
2788 .'services, and directory layout of the account.') . "\n\n"
2790 . sprintf(_('If you visit your own project page in %s while logged in, '
2791 . 'you will find additional menu functions to your left labeled “Project Admin”.'),
2792 forge_get_config ('forge_name')) . "\n\n"
2794 . sprintf(_('We highly suggest that you now visit %1$s and create a public '
2795 . 'description for your project. This can be done by visiting your project '
2796 . 'page while logged in, and selecting “Project Admin” from the menus '
2797 . 'on the left (or by visiting %2$s after login).'),
2798 forge_get_config ('forge_name'), util_make_url('/project/admin/?group_id='.$this->getID())) . "\n\n"
2800 . sprintf(_('Your project will also not appear in the Trove Software Map (primary '
2801 . 'list of projects hosted on %s which offers great flexibility in '
2802 . 'browsing and search) until you categorize it in the project administration '
2803 . 'screens. So that people can find your project, you should do this now. '
2804 . 'Visit your project while logged in, and select “Project Admin” from the '
2805 . 'menus on the left.'), forge_get_config ('forge_name')) . "\n\n"
2807 . sprintf(_('Enjoy the system, and please tell others about %s. Let us know '
2808 . 'if there is anything we can do to help you.'), forge_get_config ('forge_name')) . "\n\n"
2810 . sprintf(_('-- the %s staff'), forge_get_config ('forge_name')) . "\n";
2812 util_send_message($admin->getEmail(), sprintf(_('%s Project Approved'), forge_get_config ('forge_name')), $message);
2814 setup_gettext_from_context();
2821 * sendRejectionEmail - Send project rejection email.
2823 * This function sends out a rejection message to a user who
2824 * registered a project.
2826 * @param int $response_id The id of the response to use.
2827 * @param string $message The rejection message.
2828 * @return bool completion status.
2831 function sendRejectionEmail($response_id, $message = 'zxcv') {
2832 $submitters = array();
2833 foreach (get_group_join_requests ($this) as $gjr) {
2834 $submitters[] = user_get_object($gjr->getUserID());
2837 if (empty($submitters)) {
2838 $this->setError(_('Group does not have any administrators.'));
2842 foreach ($submitters as $admin) {
2843 setup_gettext_for_user($admin);
2845 $response = sprintf(_('Your project registration for %s has been denied.'), forge_get_config('forge_name')) . "\n\n"
2846 . _('Project Full Name')._(': '). $this->getPublicName() . "\n"
2847 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2848 . _('Reasons for negative decision')._(': ') . "\n\n";
2850 // Check to see if they want to send a custom rejection response
2851 if ($response_id == 0) {
2852 $response .= $message;
2854 $response .= db_result(
2855 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array($response_id)),
2860 util_send_message($admin->getEmail(), sprintf(_('%s Project Denied'), forge_get_config('forge_name')), $response);
2861 setup_gettext_from_context();
2868 * sendNewProjectNotificationEmail - Send new project notification email.
2870 * This function sends out a notification email to the
2871 * SourceForge admin user when a new project is
2874 * @return bool success.
2877 function sendNewProjectNotificationEmail() {
2878 // Get the user who wants to register the project
2879 $submitters = array();
2880 foreach (get_group_join_requests ($this) as $gjr) {
2881 $submitters[] = user_get_object($gjr->getUserID());
2883 if (empty($submitters)) {
2884 $this->setError(_('Could not find user who has submitted the project.'));
2888 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('approve_projects', -1);
2890 if (empty($admins)) {
2891 $this->setError(_('There is no administrator to send the mail to.'));
2895 foreach ($admins as $admin) {
2896 $admin_email = $admin->getEmail();
2897 setup_gettext_for_user ($admin);
2899 $message = sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')) . "\n\n"
2900 . _('Project Full Name')._(': ').htmlspecialchars_decode($this->getPublicName()) . "\n"
2901 . _('Submitted Description')._(': ').htmlspecialchars_decode($this->getRegistrationPurpose()) . "\n";
2903 foreach ($submitters as $submitter) {
2904 $message .= _('Submitter')._(': ').$submitter->getRealName().' ('.$submitter->getUnixName().')' . "\n\n";
2908 . _('Please visit the following URL to approve or reject this project')._(': '). "\n"
2909 . util_make_url('/admin/approve-pending.php');
2910 util_send_message($admin_email, sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')), $message);
2911 setup_gettext_from_context();
2914 $email = $submitter->getEmail();
2915 setup_gettext_for_user ($submitter);
2917 $message = sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')) . "\n\n"
2918 . _('Project Full Name')._(': ') . $this->getPublicName() . "\n"
2919 . _('Submitted Description')._(': ') . util_unconvert_htmlspecialchars($this->getRegistrationPurpose()) . "\n\n"
2920 . sprintf(_('The %s admin team will now examine your project submission. You will be notified of their decision.'),
2921 forge_get_config ('web_host'));
2923 util_send_message($email, sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')), $message);
2924 setup_gettext_from_context();
2930 * validateGroupName - Validate the group name
2932 * @param string $group_name Project name.
2934 * @return bool an error false and set an error is the group name is invalid otherwise return true
2936 function validateGroupName($group_name) {
2937 if (strlen($group_name)<3) {
2938 $this->setError(_('Project name is too short'));
2940 } elseif (strlen(htmlspecialchars($group_name))>40) {
2941 $this->setError(_('Project name is too long'));
2943 } elseif (group_get_object_by_publicname($group_name)) {
2944 $this->setError(_('Project name already taken'));
2951 * getRolesId - Get Ids of the roles of the group.
2953 * @param bool all role ids or local role ids only. Default is all role ids
2954 * @return array Role ids of this group.
2956 function getRolesId($global = true) {
2957 $role_ids = array();
2959 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2960 array($this->getID()));
2961 while ($arr = db_fetch_array($res)) {
2962 $role_ids[] = $arr['role_id'];
2965 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2966 array($this->getID()));
2967 while ($arr = db_fetch_array($res)) {
2968 $role_ids[] = $arr['role_id'];
2972 return array_unique($role_ids);
2976 * getRoles - Get the roles of the group.
2978 * @param bool all roles or local roles only. Default is all roles
2979 * @return array Roles of this group.
2981 function getRoles($global = true) {
2984 $roles = $this->getRolesId($global);
2985 $engine = RBACEngine::getInstance();
2986 foreach ($roles as $role_id) {
2987 $result[] = $engine->getRoleById($role_id);
2993 function normalizeAllRoles() {
2994 $roles = $this->getRoles();
2996 foreach ($roles as $r) {
2997 $r->normalizeData();
3002 * getUnixStatus - Status of activation of unix account.
3004 * @return string Values: (N)one, (A)ctive, (S)uspended or (D)eleted
3006 function getUnixStatus() {
3007 return $this->data_array['unix_status'];
3011 * setUnixStatus - Sets status of activation of unix account.
3013 * @param string $status The unix status.
3019 * @return bool success.
3021 function setUnixStatus($status) {
3024 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
3029 $this->setError(_('Error')._(': ')._('Cannot Update Group Unix Status')._(': ').db_error());
3033 if ($status == 'A') {
3034 if (!$SYS->sysCheckCreateGroup($this->getID())) {
3035 $this->setError($SYS->getErrorMessage());
3040 if ($SYS->sysCheckGroup($this->getID())) {
3041 if (!$SYS->sysRemoveGroup($this->getID())) {
3042 $this->setError($SYS->getErrorMessage());
3049 $this->data_array['unix_status'] = $status;
3056 * getUsers - Get the users of a group
3058 * @param bool $onlylocal
3059 * @param bool $onlyactive Only users with state active, or all users of group
3060 * @return array user's objects.
3062 function getUsers($onlylocal = true, $onlyactive = true) {
3063 if (!isset($this->membersArr)) {
3064 $this->membersArr = array();
3067 foreach ($this->getRoles() as $role) {
3069 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
3072 foreach ($role->getUsers() as $user) {
3073 $ids[] = $user->getID();
3076 $ids = array_unique ($ids);
3077 foreach ($ids as $id) {
3078 $u = user_get_object ($id);
3079 if (!$onlyactive || $u->isActive()) {
3080 $this->membersArr[] = $u;
3084 return $this->membersArr;
3087 function setDocmanCreateOnlineStatus($status) {
3089 $res = db_query_params('UPDATE groups SET use_docman_create_online = $1 WHERE group_id = $2',
3090 array($status, $this->getID()));
3093 $this->setError(_('Error')._(': ')._('Cannot Update Group DocmanCreateOnline Status')._(': ').db_error());
3097 $this->data_array['use_docman_create_online'] = $status;
3103 function setDocmanWebdav($status) {
3105 $res = db_query_params('UPDATE groups SET use_webdav = $1 WHERE group_id = $2',
3110 $this->setError(_('Error')._(': ')._('Cannot Update Group UseWebdav Status')._(': ').db_error());
3114 $this->data_array['use_webdav'] = $status;
3120 function setDocmanSearchStatus($status) {
3122 /* if we activate search engine, we probably want to reindex */
3123 $res = db_query_params('UPDATE groups SET use_docman_search = $1, force_docman_reindex = $1 WHERE group_id = $2',
3124 array($status, $this->getID()));
3127 $this->setError(_('Error')._(': ')._('Cannot Update Group UseDocmanSearch Status')._(': ').db_error());
3131 $this->data_array['use_docman_search'] = $status;
3137 function setDocmanForceReindexSearch($status) {
3139 $res = db_query_params('UPDATE groups SET force_docman_reindex = $1 WHERE group_id = $2',
3140 array($status, $this->getID()));
3143 $this->setError(_('Error')._(': ')._('Cannot Update Group force_docman_reindex')._(': ').db_error());
3147 $this->data_array['force_docman_reindex'] = $status;
3155 * @param int $unit_set_id the effort unit set id
3158 function setEffortUnitSet($unit_set_id) {
3160 $res = db_query_params ('UPDATE groups SET unit_set_id=$1 WHERE group_id=$2',
3161 array($unit_set_id, $this->getID()));
3163 $this->data_array['unit_set_id'] = $unit_set_id;
3173 * getEffortUnitSet - Get the effort unit set id.
3175 * @return int The id of the effort unit set.
3177 function getEffortUnitSet() {
3178 return $this->data_array['unit_set_id'];
3181 function getWidgetLayoutConfig() {
3182 $lm = new WidgetLayoutManager();
3183 return $lm->getLayout($this->getID(), WidgetLayoutManager::OWNER_TYPE_GROUP);
3187 * castVote - Vote on this project or retract the vote
3188 * @param bool $value true to cast, false to retract
3189 * @return bool success (false sets error message)
3191 function castVote($value = true) {
3192 if (!($uid = user_getid()) || $uid == 100) {
3193 $this->setMissingParamsError(_('User ID not passed'));
3196 if (!$this->canVote()) {
3197 $this->setPermissionDeniedError();
3200 $has_vote = $this->hasVote($uid);
3201 if ($has_vote == $value) {
3202 /* nothing changed */
3206 $res = db_query_params('INSERT INTO group_votes (group_id, user_id) VALUES ($1, $2)',
3207 array($this->getID(), $uid));
3209 $res = db_query_params('DELETE FROM group_votes WHERE group_id = $1 AND user_id = $2',
3210 array($this->getID(), $uid));
3213 $this->setError(db_error());
3220 * hasVote - Check if a user has voted on this group item
3222 * @param int|bool $uid user ID (default: current user)
3223 * @return bool true if a vote exists
3225 function hasVote($uid = false) {
3227 $uid = user_getid();
3229 if (!$uid || $uid == 100) {
3232 $res = db_query_params('SELECT * FROM group_votes WHERE group_id = $1 AND user_id = $2',
3233 array($this->getID(), $uid));
3234 return (db_numrows($res) == 1);
3238 * getVotes - get number of valid cast and potential votes
3240 * @return array|bool (votes, voters, percent)
3242 function getVotes() {
3243 if ($this->votes !== false) {
3244 return $this->votes;
3247 $lvoters = $this->getVoters();
3248 unset($lvoters[0]); /* just in case */
3249 unset($lvoters[100]); /* need users */
3250 if (($numvoters = count($lvoters)) < 1) {
3251 $this->votes = array(0, 0, 0);
3252 return $this->votes;
3255 $res = db_query_params('SELECT COUNT(*) AS count FROM group_votes WHERE group_id = $1 AND user_id = ANY($2)',
3256 array($this->getID(), db_int_array_to_any_clause($lvoters)));
3257 $db_count = db_fetch_array($res);
3258 $numvotes = $db_count['count'];
3260 /* check for invalid values */
3261 if ($numvotes < 0 || $numvoters < $numvotes) {
3262 $this->votes = array(-1, -1, 0);
3264 $this->votes = array($numvotes, $numvoters,
3265 (int)($numvotes * 100 / $numvoters + 0.5));
3267 return $this->votes;
3271 * canVote - check whether the current user can vote on
3272 * items in this project
3274 * @return bool true if they can
3276 function canVote() {
3277 if (in_array(user_getid(), $this->getVoters())) {
3284 * getVoters - get IDs of users that may vote on
3285 * items in this project
3287 * @return array list of user IDs
3289 function getVoters() {
3290 if ($this->voters !== false) {
3291 return $this->voters;
3294 $this->voters = array();
3295 if (($engine = RBACEngine::getInstance())
3296 && ($lvoters = $engine->getUsersByAllowedAction('project_read', $this->getID()))
3297 && (count($lvoters) > 0)) {
3298 foreach ($lvoters as $voter) {
3299 $voter_id = $voter->getID();
3300 $this->voters[$voter_id] = $voter_id;
3303 return $this->voters;
3308 * group_getname() - get the group name
3310 * @param int $group_id The group ID
3315 function group_getname ($group_id = 0) {
3316 $grp = group_get_object($group_id);
3318 return $grp->getPublicName();
3325 * group_getunixname() - get the unixname for a group
3327 * @param int $group_id The group ID
3332 function group_getunixname ($group_id) {
3333 $grp = group_get_object($group_id);
3335 return $grp->getUnixName();
3342 * group_get_result() - Get the group object result ID.
3344 * @param int $group_id The group ID
3349 function &group_get_result($group_id=0) {
3350 $grp = group_get_object($group_id);
3352 return $grp->getData();
3358 function getAllProjectTags($onlyvisible = true) {
3359 $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',
3362 if (!$res || db_numrows($res) == 0) {
3368 while ($arr = db_fetch_array($res)) {
3370 $group_id = $arr[1];
3371 if (!isset($result[$tag])) {
3372 $result[$tag] = array();
3375 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
3376 $p = group_get_object($group_id);
3377 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
3378 'group_id' => $group_id);
3386 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
3389 class ProjectComparator {
3390 var $criterion = 'name';
3392 function Compare ($a, $b) {
3393 switch ($this->criterion) {
3395 return strcmp ($a->getUnixName(), $b->getUnixName());
3402 return ($aid < $bid) ? -1 : 1;
3405 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName());
3406 if ($namecmp != 0) {
3409 /* If several projects share a same public name */
3410 return strcoll ($a->getUnixName(), $b->getUnixName());
3415 function sortProjectList (&$list, $criterion='name') {
3416 $cmp = new ProjectComparator();
3417 $cmp->criterion = $criterion;
3419 return usort ($list, array($cmp, 'Compare'));
3424 // c-file-style: "bsd"