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-2022, 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
269 * Group - Group object constructor - use group_get_object() to instantiate.
271 * @param int|bool $id Required - Id of the group you want to instantiate.
272 * @param int|bool $res Database result from select query OR associative array of all columns.
274 function __construct($id = false, $res = false) {
275 parent::__construct();
277 //setting up an empty object
278 //probably going to call create()
282 $this->fetchData($id);
285 // Assoc array was passed in
287 if (is_array($res)) {
288 $this->data_array =& $res;
290 if (db_numrows($res) < 1) {
291 //function in class we extended
292 $this->setError(_('Group Not Found'));
293 $this->data_array = array();
295 //set up an associative array for use by other functions
296 $this->data_array = db_fetch_array_by_row($res, 0);
304 * fetchData - May need to refresh database fields if an update occurred.
306 * @param int $group_id The group_id.
307 * @return bool success or not
309 function fetchData($group_id) {
310 $res = db_query_params ('SELECT * FROM groups WHERE group_id=$1',
312 if (!$res || db_numrows($res) < 1) {
313 $this->setError('fetchData()'._(': ').db_error());
316 $this->data_array = db_fetch_array($res);
321 * create - Create new group.
323 * This method should be called on empty Group object.
324 * It will add an entry for a pending group/project (status 'P')
326 * @param object $user The User object.
327 * @param string $group_name The full name of the user.
328 * @param string $unix_name The Unix name of the user.
329 * @param string $description The new group description.
330 * @param string $purpose The purpose of the group.
331 * @param string $unix_box
332 * @param string $scm_box
333 * @param bool $send_mail Whether to send an email or not
334 * @param int $built_from_template The id of the project this new project is based on
335 * @param int $createtimestamp The Time Stamp of creation to ease import.
336 * @return bool success or not
338 function create(&$user, $group_name, $unix_name, $description, $purpose, $unix_box = 'shell1',
339 $scm_box = 'cvs1', $send_mail = true, $built_from_template = 0, $createtimestamp = null) {
340 // $user is ignored - anyone can create pending group
343 if ($this->getID()!=0) {
344 $this->setError(_('Group object already exists.'));
346 } elseif (!$this->validateGroupName($group_name)) {
347 $this->setError(_('Invalid project name'));
349 } elseif (!account_groupnamevalid($unix_name)) {
350 $this->setError(_('Invalid Unix Name.'));
352 } elseif (!$SYS->sysUseUnixName($unix_name)) {
353 $this->setError(_('Unix name already taken.'));
355 } elseif (strlen($purpose)<10) {
356 $this->setError(_('Please describe your Registration Project Purpose and Summarization in a more comprehensive manner.'));
358 } elseif (strlen($purpose)>1500) {
359 $this->setError(_('The Registration Project Purpose and Summarization text is too long. Please make it smaller than 1500 characters.'));
361 } elseif (strlen($description)<10) {
362 $this->setError(_('Describe in a more comprehensive manner your project.'));
366 // Check if use_project_vhost for homepage
367 if (forge_get_config('use_project_vhost')) {
368 $homepage = $unix_name.'.'.forge_get_config('web_host');
370 $homepage = forge_get_config('web_host')."/www/".$unix_name."/";
374 $createtimestamp = (($createtimestamp) ? $createtimestamp : time());
375 $res = db_query_params('
390 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)',
391 array(htmlspecialchars($group_name),
393 htmlspecialchars($description),
399 htmlspecialchars($purpose),
401 md5(util_randbytes()),
402 $built_from_template));
403 if (!$res || db_affected_rows($res) < 1) {
404 $this->setError(_('Error')._(': ')._('Cannot create group')._(': ').db_error());
409 $id = db_insertid($res, 'groups', 'group_id');
411 $this->setError(_('Error')._(': ')._('Cannot get group id')._(': ').db_error());
416 if (!$this->fetchData($id)) {
421 $gjr = new GroupJoinRequest($this);
422 $gjr->create($user->getID(), 'Fake GroupJoinRequest to store the creator of a project', false);
424 $hook_params = array();
425 $hook_params['group'] = $this;
426 $hook_params['group_id'] = $this->getID();
427 $hook_params['group_name'] = $group_name;
428 $hook_params['unix_group_name'] = $unix_name;
429 $hook_params['createtimestamp'] = $createtimestamp;
430 plugin_hook("group_create", $hook_params);
434 $this->sendNewProjectNotificationEmail();
442 * updateAdmin - Update core properties of group object.
444 * This function require site admin privilege.
446 * @param string $unix_box Machine on which group's home directory located.
447 * @param string $http_domain Domain which serves group's WWW.
448 * @return bool status.
451 function updateAdmin($unix_box, $http_domain) {
452 $perm =& $this->getPermission();
454 if (!$perm || !is_object($perm)) {
455 $this->setError(_('Could not get permission.'));
459 if (!$perm->isSuperUser()) {
460 $this->setError(_('Permission denied.'));
466 $res = db_query_params('
468 SET unix_box=$1, http_domain=$2
474 if (!$res || db_affected_rows($res) < 1) {
475 $this->setError(_('Error')._(': ')._('Cannot change group properties')._(': ').db_error());
480 // Log the audit trail
481 if ($unix_box != $this->data_array['unix_box']) {
482 $this->addHistory('unix_box', $this->data_array['unix_box']);
484 if ($http_domain != $this->data_array['http_domain']) {
485 $this->addHistory('http_domain', $this->data_array['http_domain']);
488 if (!$this->fetchData($this->getID())) {
497 * update - Update number of common properties.
499 * Unlike updateAdmin(), this function accessible to project admin.
501 * @param string $group_name
502 * @param string $homepage
503 * @param string $short_description
504 * @param bool $use_mail
505 * @param bool $use_survey
506 * @param bool $use_forum
507 * @param bool $use_pm
508 * @param bool $use_pm_depend_box
509 * @param bool $use_scm
510 * @param bool $use_news
511 * @param bool $use_docman
512 * @param string $new_doc_address
513 * @param bool $send_all_docs
514 * @param int $logo_image_id XXXX UNUSED XXXX -> see getLogoImageID function
515 * @param bool $use_ftp
516 * @param bool $use_tracker
517 * @param bool $use_frs
518 * @param bool $use_stats
519 * @param string $tags
520 * @param bool $use_activity
521 * @param bool $is_public group is publicly accessible
522 * @param string $new_frs_address
523 * @param bool $send_all_frs
524 * @return int status.
527 function update($group_name, $homepage, $short_description, $use_mail, $use_survey, $use_forum,
528 $use_pm, $use_pm_depend_box, $use_scm, $use_news, $use_docman,
529 $new_doc_address, $send_all_docs, $logo_image_id,
530 $use_ftp, $use_tracker, $use_frs, $use_stats, $tags, $use_activity, $is_public, $new_frs_address, $send_all_frs) {
532 $perm =& $this->getPermission();
534 if (!$perm || !is_object($perm)) {
535 $this->setError(_('Could not get permission.'));
539 if (!$perm->isAdmin()) {
540 $this->setError(_('Permission denied.'));
544 // Validate some values
545 if ($this->getPublicName() != htmlspecialchars($group_name) && !$this->validateGroupName($group_name)) {
549 if ($new_doc_address) {
550 $invalid_mails = validate_emails($new_doc_address);
551 if (count($invalid_mails) > 0) {
552 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
557 if ($new_frs_address) {
558 $invalid_mails = validate_emails($new_frs_address);
559 if (count($invalid_mails) > 0) {
560 $this->setError(sprintf(ngettext('New FRS Address Appeared Invalid: %s', 'New FRS Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
565 // in the database, these all default to '1',
566 // so we have to explicitly set 0
579 if (!$use_pm_depend_box) {
580 $use_pm_depend_box = 0;
603 if (!$use_activity) {
606 if (!$send_all_docs) {
610 if (!$send_all_frs) {
614 $homepage = ltrim($homepage);
616 $homepage = util_make_url('/projects/'.$this->getUnixName().'/');
621 $res = db_query_params('UPDATE groups
624 short_description=$3,
629 use_pm_depend_box=$8,
642 array(htmlspecialchars($group_name),
644 htmlspecialchars($short_description),
663 if (!$res || db_affected_rows($res) < 1) {
664 $this->setError(_('Error updating project information')._(': ').db_error());
669 if (!$this->setUseDocman($use_docman)) {
670 $this->setError(_('Error updating project information use_docman')._(': ').db_error());
675 if ($this->setTags($tags) === false) {
680 // Log the audit trail
681 $this->addHistory('Changed Public Info', '');
683 if (!$this->fetchData($this->getID())) {
688 $hook_params = array();
689 $hook_params['group'] = $this;
690 $hook_params['group_id'] = $this->getID();
691 $hook_params['group_homepage'] = $homepage;
692 $hook_params['group_name'] = htmlspecialchars($group_name);
693 $hook_params['group_description'] = htmlspecialchars($short_description);
694 $hook_params['group_ispublic'] = $is_public;
695 if (!plugin_hook("group_update", $hook_params)) {
696 if (!$this->isError()) {
697 $this->setError(_('Error updating project information in plugin_hook group_update'));
708 * getID - Simply return the group_id for this object.
710 * @return int group_id.
713 return $this->data_array['group_id'];
717 * getStatus - the status code.
719 * Statuses char include I,H,A,D,P.
726 function getStatus() {
727 return $this->data_array['status'];
731 * setStatus - set the status code.
733 * Statuses include I,H,A,D,P.
740 * @param object $user User requesting operation (for access control).
741 * @param string $status Status value.
742 * @return bool success.
745 function setStatus(&$user, $status) {
748 if (!forge_check_global_perm_for_user($user, 'approve_projects')) {
749 $this->setPermissionDeniedError();
753 // Projects in 'A' status can only go to 'H' or 'D'
754 // Projects in 'D' status can only go to 'A'
755 // Projects in 'P' status can only go to 'A' OR 'D'
756 // Projects in 'I' status can only go to 'P'
757 // Projects in 'H' status can only go to 'A' OR 'D'
758 $allowed_status_changes = array(
759 'AH'=>1,'AD'=>1,'DA'=>1,'PA'=>1,'PD'=>1,
760 'IP'=>1,'HA'=>1,'HD'=>1
763 // Check that status transition is valid
764 if ($this->getStatus() != $status
765 && !array_key_exists($this->getStatus(). $status, $allowed_status_changes)) {
766 $this->setError(_('Invalid Status Change From')._(': ').$this->getStatus()._(' To ')._(': ').$status);
772 $res = db_query_params('UPDATE groups
774 WHERE group_id=$2', array($status, $this->getID()));
776 if (!$res || db_affected_rows($res) < 1) {
777 $this->setError(_('Error')._(': ')._('Cannot change group status')._(': ').db_error());
783 // Activate system group, if not yet
784 if (!$SYS->sysCheckGroup($this->getID())) {
785 if (!$SYS->sysCreateGroup($this->getID())) {
786 $this->setError($SYS->getErrorMessage());
791 if (!$this->activateUsers()) {
796 /* Otherwise, the group is not active, and make sure that
797 System group is not active either */
798 } elseif ($SYS->sysCheckGroup($this->getID())) {
799 if (!$SYS->sysRemoveGroup($this->getID())) {
800 $this->setError($SYS->getErrorMessage());
806 $hook_params = array();
807 $hook_params['group'] = $this;
808 $hook_params['group_id'] = $this->getID();
809 $hook_params['status'] = $status;
810 plugin_hook("group_setstatus", $hook_params);
814 // Log the audit trail
815 if ($status != $this->getStatus()) {
816 $this->addHistory(_('Status'), $this->getStatus());
819 $this->data_array['status'] = $status;
824 * isPublic - Wrapper around RBAC to check if a project is anonymously readable
826 * @return boo is_public.
828 function isPublic() {
829 $ra = RoleAnonymous::getInstance();
830 return $ra->hasPermission('project_read', $this->getID());
834 * isActive - Database field status of 'A' returns true.
836 * @return bool is_active.
838 function isActive() {
839 if ($this->getStatus() == 'A') {
846 * isTemplate - Simply returns the is_template flag from the database.
848 * @return bool is_template.
850 function isTemplate() {
851 return $this->data_array['is_template'];
855 * setAsTemplate - Set the template status of a project
857 * @param bool $booleanparam is_template.
860 function setAsTemplate($booleanparam) {
862 $booleanparam = $booleanparam ? 1 : 0;
863 $res = db_query_params('UPDATE groups SET is_template=$1 WHERE group_id=$2',
864 array($booleanparam, $this->getID()));
866 if ($booleanparam != $this->data_array['is_template']) {
867 $this->addHistory('is_template', $this->data_array['is_template']);
869 $this->data_array['is_template'] = $booleanparam;
879 * getTemplateProject - Return the project template this project is built from
881 * @return object The template project
883 function getTemplateProject() {
884 return group_get_object($this->data_array['built_from_template']);
888 * getUnixName - the unix_name
890 * @return string unix_name.
892 function getUnixName() {
893 return strtolower($this->data_array['unix_group_name']);
897 * getPublicName - the full-length public name.
899 * @return string The group_name.
901 function getPublicName() {
902 return $this->data_array['group_name'];
906 * getDescription - the text description of this project.
908 * @return string The description.
910 function getDescription() {
911 return $this->data_array['short_description'];
915 * getStartDate - the unix time this project was registered.
917 * @return int (unix time) of registration.
919 function getStartDate() {
920 return $this->data_array['register_time'];
924 * getLogoImageID - the id of the logo in the database for this project.
926 * @return int The ID of logo image in db_images table (or 100 if none).
928 function getLogoImageID() {
929 if (!isset($this->data_array['logo_image_id'])) {
930 $res = db_query_params('select id from db_images where group_id = $1 and is_logo = $2',
931 array($this->getID(), 1));
932 if ($res && db_numrows($res)) {
933 $this->data_array['logo_image_id'] = db_result($res, 0, 'id');
935 $this->data_array['logo_image_id'] = null;
938 return $this->data_array['logo_image_id'];
942 * getUnixBox - the hostname of the unix box where this project is located.
944 * @return string The name of the unix machine for the group.
946 function getUnixBox() {
947 return $this->data_array['unix_box'];
951 * getSCMBox - the hostname of the scm box where this project is located.
953 * @return string The name of the unix machine for the group.
955 function getSCMBox() {
956 return $this->data_array['scm_box'];
959 * setSCMBox - the hostname of the scm box where this project is located.
961 * @param string $scm_box The name of the new SCM_BOX
964 function setSCMBox($scm_box) {
966 if ($scm_box == $this->data_array['scm_box']) {
971 $res = db_query_params('UPDATE groups SET scm_box=$1 WHERE group_id=$2', array($scm_box, $this->getID()));
973 $this->addHistory('scm_box', $this->data_array['scm_box']);
974 $this->data_array['scm_box'] = $scm_box;
979 $this->setError(_("Could not insert SCM_BOX to database"));
983 $this->setError(_("SCM Box cannot be empty"));
989 * getDomain - the hostname.domain where their web page is located.
991 * @return string The name of the group [web] domain.
993 function getDomain() {
994 return $this->data_array['http_domain'];
998 * getRegistrationPurpose - the text description of the purpose of this project.
1000 * @return string The application for project hosting.
1002 function getRegistrationPurpose() {
1003 return $this->data_array['register_purpose'];
1007 * getAdmins - Get array of Admin user objects.
1009 * @return array Array of User objects.
1011 function &getAdmins() {
1012 $roles = RBACEngine::getInstance()->getRolesByAllowedAction ('project_admin', $this->getID());
1014 $user_ids = array();
1016 foreach ($roles as $role) {
1017 if (! ($role instanceof RoleExplicit)) {
1020 if ($role->getHomeProject() == NULL
1021 || $role->getHomeProject()->getID() != $this->getID()) {
1025 foreach ($role->getUsers() as $u) {
1026 $user_ids[] = $u->getID();
1029 $active_ids = array();
1030 $ids = array_unique ($user_ids);
1031 foreach ($ids as $id) {
1032 $u = user_get_object ($id);
1033 if ($u->isActive()) {
1041 Common Group preferences for tools
1045 * enableAnonSCM - whether or not this group has opted to enable Anonymous SCM.
1047 * @return bool enable_scm.
1049 function enableAnonSCM() {
1050 $r = RoleAnonymous::getInstance();
1051 return $r->hasPermission('scm', $this->getID(), 'read');
1054 function SetUsesAnonSCM($booleanparam) {
1056 $booleanparam = $booleanparam ? 1 : 0;
1057 $r = RoleAnonymous::getInstance();
1058 $r->setSetting('scm', $this->getID(), $booleanparam);
1063 * enablePserver - whether or not this group has opted to enable Pserver.
1065 * @return bool enable_pserver.
1067 function enablePserver() {
1068 if ($this->usesSCM()) {
1069 return $this->data_array['enable_pserver'];
1075 function SetUsesPserver($booleanparam) {
1077 $booleanparam = $booleanparam ? 1 : 0;
1078 $res = db_query_params('UPDATE groups SET enable_pserver=$1 WHERE group_id=$2',
1079 array($booleanparam, $this->getID()));
1081 $this->data_array['enable_pserver'] = $booleanparam;
1091 * usesSCM - whether or not this group has opted to use SCM.
1093 * @return bool uses_scm.
1095 function usesSCM() {
1096 if (forge_get_config('use_scm')) {
1097 return $this->data_array['use_scm'];
1104 * setUseSCM - Set the SCM usage
1106 * @param bool $booleanparam enabled/disabled
1109 function setUseSCM($booleanparam) {
1111 $booleanparam = $booleanparam ? 1 : 0;
1112 $res = db_query_params('UPDATE groups SET use_scm=$1 WHERE group_id=$2',
1113 array($booleanparam, $this->getID()));
1115 $this->data_array['use_scm'] = $booleanparam;
1125 * usesMail - whether or not this group has opted to use mailing lists.
1127 * @return bool uses_mail.
1129 function usesMail() {
1130 if (forge_get_config('use_mail')) {
1131 return $this->data_array['use_mail'];
1138 * setUseMail - Set the mailing-list usage
1140 * @param bool $booleanparam enabled/disabled
1143 function setUseMail($booleanparam) {
1145 $booleanparam = $booleanparam ? 1 : 0;
1146 $res = db_query_params('UPDATE groups SET use_mail=$1 WHERE group_id=$2',
1147 array($booleanparam, $this->getID()));
1149 $this->data_array['use_mail'] = $booleanparam;
1159 * usesNews - whether or not this group has opted to use news.
1161 * @return bool uses_news.
1163 function usesNews() {
1164 if (forge_get_config('use_news')) {
1165 return $this->data_array['use_news'];
1171 function setUseNews($booleanparam) {
1173 $booleanparam = $booleanparam ? 1 : 0;
1174 $res = db_query_params('UPDATE groups SET use_news=$1 WHERE group_id=$2',
1175 array($booleanparam, $this->getID()));
1177 $this->data_array['use_news'] = $booleanparam;
1187 * usesActivity - whether or not this group has opted to display Project Activities.
1189 * @return bool uses_activities.
1191 function usesActivity() {
1192 if (forge_get_config('use_activity')) {
1193 return $this->data_array['use_activity'];
1199 function setUseActivity($booleanparam) {
1201 $booleanparam = $booleanparam ? 1 : 0;
1202 $res = db_query_params('UPDATE groups SET use_activity=$1 WHERE group_id=$2',
1203 array($booleanparam, $this->getID()));
1205 $this->data_array['use_activity'] = $booleanparam;
1215 * usesForum - whether or not this group has opted to use discussion forums.
1217 * @return bool uses_forum.
1219 function usesForum() {
1220 if (forge_get_config('use_forum')) {
1221 return $this->data_array['use_forum'];
1228 * setUseForum - Set the forum usage
1230 * @param bool $booleanparam enabled/disabled
1233 function setUseForum($booleanparam) {
1235 $booleanparam = $booleanparam ? 1 : 0;
1236 $res = db_query_params('UPDATE groups SET use_forum=$1 WHERE group_id=$2',
1237 array($booleanparam, $this->getID()));
1239 $this->data_array['use_forum'] = $booleanparam;
1249 * usesStats - whether or not this group has opted to use stats.
1251 * @return bool uses_stats.
1253 function usesStats() {
1254 return $this->data_array['use_stats'];
1258 * usesFRS - whether or not this group has opted to use file release system.
1260 * @return bool uses_frs.
1262 function usesFRS() {
1263 if (forge_get_config('use_frs')) {
1264 return $this->data_array['use_frs'];
1271 * setUseFRS - Set the FRS usage
1273 * @param bool $booleanparam enabled/disabled
1276 function setUseFRS($booleanparam) {
1278 $booleanparam = $booleanparam ? 1 : 0;
1279 $res = db_query_params('UPDATE groups SET use_frs=$1 WHERE group_id=$2',
1280 array($booleanparam, $this->getID()));
1282 $this->data_array['use_frs']=$booleanparam;
1291 * usesTracker - whether or not this group has opted to use tracker.
1293 * @return bool uses_tracker.
1295 function usesTracker() {
1296 if (forge_get_config('use_tracker')) {
1297 return $this->data_array['use_tracker'];
1303 * setUseTracker - Set the tracker usage
1305 * @param bool $booleanparam enabled/disabled
1308 function setUseTracker($booleanparam) {
1310 $booleanparam = $booleanparam ? 1 : 0;
1311 $res = db_query_params ('UPDATE groups SET use_tracker=$1 WHERE group_id=$2',
1312 array($booleanparam, $this->getID()));
1314 $this->data_array['use_tracker']=$booleanparam;
1323 * useCreateOnline - whether or not this group has opted to use create online documents option.
1325 * @return bool use_docman_create_online.
1327 function useCreateOnline() {
1328 if (forge_get_config('use_docman')) {
1329 return $this->data_array['use_docman_create_online'];
1335 * usesDocman - whether or not this group has opted to use docman.
1337 * @return bool use_docman.
1339 function usesDocman() {
1340 if (forge_get_config('use_docman')) {
1341 return $this->data_array['use_docman'];
1347 * setUseDocman - Set the docman usage
1349 * @param bool $booleanparam enabled/disabled
1352 function setUseDocman($booleanparam) {
1354 $booleanparam = $booleanparam ? 1 : 0;
1355 $res = db_query_params('UPDATE groups SET use_docman = $1 WHERE group_id = $2',
1356 array($booleanparam, $this->getID()));
1358 // check if / doc_group exists, if not create it
1359 $trashdir = db_query_params('select groupname from doc_groups where groupname = $1 and group_id = $2',
1360 array('.trash', $this->getID()));
1361 if ($trashdir && db_numrows($trashdir) == 0) {
1362 $resinsert = db_query_params('insert into doc_groups (groupname, group_id, stateid) values ($1, $2, $3)',
1363 array('.trash', $this->getID(), '2'));
1369 $this->data_array['use_docman'] = $booleanparam;
1378 * useDocmanSearch - whether or not this group has opted to use docman search engine.
1380 * @return bool use_docman_search.
1382 function useDocmanSearch() {
1383 if (forge_get_config('use_docman')) {
1384 return $this->data_array['use_docman_search'];
1390 * useWebdav - whether or not this group has opted to use webdav interface.
1392 * @return bool use_docman_search.
1394 function useWebdav() {
1395 if (forge_get_config('use_webdav')) {
1396 return $this->data_array['use_webdav'];
1402 * usesFTP - whether or not this group has opted to use FTP.
1404 * @return bool uses_ftp.
1406 function usesFTP() {
1407 if (forge_get_config('use_ftp')) {
1408 return $this->data_array['use_ftp'];
1414 * usesSurvey - whether or not this group has opted to use surveys.
1416 * @return bool uses_survey.
1418 function usesSurvey() {
1419 if (forge_get_config('use_survey')) {
1420 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'];
1438 * setUsePM - Set the PM usage
1440 * @param bool $booleanparam enabled/disabled
1443 function setUsePM($booleanparam) {
1445 $booleanparam = $booleanparam ? 1 : 0;
1446 $res = db_query_params('UPDATE groups SET use_pm=$1 WHERE group_id=$2',
1447 array($booleanparam, $this->getID()));
1449 $this->data_array['use_pm']=$booleanparam;
1458 * getPlugins - get a list of all available group plugins
1460 * @return array array containing plugin_id => plugin_name
1462 function getPlugins() {
1463 if (!isset($this->plugins_data)) {
1464 $this->plugins_data = array();
1465 $res = db_query_params('SELECT group_plugin.plugin_id, plugins.plugin_name
1466 FROM group_plugin, plugins
1467 WHERE group_plugin.group_id=$1
1468 AND group_plugin.plugin_id=plugins.plugin_id', array($this->getID()));
1469 $rows = db_numrows($res);
1471 for ($i=0; $i<$rows; $i++) {
1472 $plugin_id = db_result($res, $i, 'plugin_id');
1473 $this->plugins_data[$plugin_id] = db_result($res, $i, 'plugin_name');
1476 return $this->plugins_data;
1480 * usesPlugin - returns true if the group uses a particular plugin
1482 * @param string $pluginname name of the plugin
1483 * @return bool whether plugin is being used or not
1485 function usesPlugin($pluginname) {
1486 foreach ($this->getPlugins() 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 $pm = plugin_manager_get_object();
1503 foreach ($this->getPlugins() as $p_name) {
1504 if ($p_name == $feature) {
1507 if (is_object($pm->getPluginByName($p_name)) && $pm->getPluginByName($p_name)->provide($feature)) {
1515 * setPluginUse - enables/disables plugins for the group
1517 * @param string $pluginname name of the plugin
1518 * @param bool $val the new state
1519 * @return string database result
1521 function setPluginUse($pluginname, $val=true) {
1522 if ($val == $this->usesPlugin($pluginname)) {
1523 // State is already good, returning
1526 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1527 array($pluginname));
1528 $rows = db_numrows($res);
1530 // Error: no plugin by that name
1533 $plugin_id = db_result($res,0,'plugin_id');
1535 unset($this->plugins_data);
1537 $res = db_query_params('INSERT INTO group_plugin (group_id, plugin_id) VALUES ($1, $2)',
1538 array($this->getID(),
1541 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1 AND plugin_id=$2',
1542 array($this->getID(),
1545 $this->normalizeAllRoles();
1546 $hook_params = array();
1547 $hook_params['group_id'] = $this->getID();
1548 $hook_params['val'] = $val;
1549 plugin_hook("group_plugin_use", $hook_params);
1554 * getDocEmailAddress - get email address(es) to send doc notifications to.
1556 * @return string email address.
1558 function getDocEmailAddress() {
1559 return $this->data_array['new_doc_address'];
1562 function setDocEmailAddress($email) {
1563 $invalid_mails = validate_emails($email);
1564 if (count($invalid_mails) > 0) {
1565 $this->setError(sprintf(ngettext('New Doc Address Appeared Invalid: %s', 'New Doc Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
1569 $res = db_query_params('UPDATE groups SET new_doc_address = $1 WHERE group_id = $2',
1570 array($email, $this->getID()));
1573 $this->setError(_('Error')._(': ')._('Cannot Update Group new_doc_address')._(': ').db_error());
1577 $this->data_array['new_doc_address'] = $email;
1583 * docEmailAll - whether or not this group has opted to use receive notices on all doc updates.
1585 * @return bool email_on_all_doc_updates.
1587 function docEmailAll() {
1588 return $this->data_array['send_all_docs'];
1591 function setDocEmailAll($status) {
1593 $res = db_query_params('UPDATE groups SET send_all_docs = $1 WHERE group_id = $2',
1594 array($status, $this->getID()));
1597 $this->setError(_('Error')._(': ')._('Cannot Update Group send_all_docs')._(': ').db_error());
1601 $this->data_array['send_all_docs'] = $status;
1607 * getFRSEmailAddress - get email address(es) to send FRS notifications to.
1609 * @return string email address.
1611 function getFRSEmailAddress() {
1612 return $this->data_array['new_frs_address'];
1615 function setFRSEmailAddress($email) {
1616 $invalid_mails = validate_emails($email);
1617 if (count($invalid_mails) > 0) {
1618 $this->setError(sprintf(ngettext('New FRS Address Appeared Invalid: %s', 'New FRS Addresses Appeared Invalid: %s', count($invalid_mails)),implode(',',$invalid_mails)));
1622 $res = db_query_params('UPDATE groups SET new_frs_address = $1 WHERE group_id = $2',
1623 array($email, $this->getID()));
1626 $this->setError(_('Error')._(': ')._('Cannot Update Group new_frs_address')._(': ').db_error());
1630 $this->data_array['new_frs_address'] = $email;
1636 * frsEmailAll - whether or not this group has opted to use receive notices on all frs updates.
1638 * @return bool email_on_all_frs_updates.
1640 function frsEmailAll() {
1641 return $this->data_array['send_all_frs'];
1644 function setFRSEmailAll($status) {
1646 $res = db_query_params('UPDATE groups SET send_all_frs = $1 WHERE group_id = $2',
1647 array($status, $this->getID()));
1650 $this->setError(_('Error')._(': ')._('Cannot Update Group send_frs_docs')._(': ').db_error());
1654 $this->data_array['send_frs_docs'] = $status;
1660 * getHomePage - The URL for this project's home page.
1662 * @return string homepage URL.
1664 function getHomePage() {
1665 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9+.-]*:/", $this->data_array['homepage'])) {
1666 $this->data_array['homepage'] = 'http://'.$this->data_array['homepage'];
1668 return $this->data_array['homepage'];
1672 * setHomepage - the hostname of the website url where this project is located.
1674 * @param string $homepage The name of the new HOMEPAGE
1677 function setHomepage($homepage) {
1678 if ($homepage == $this->data_array['homepage']) {
1683 $res = db_query_params('UPDATE groups SET homepage=$1 WHERE group_id=$2', array($homepage, $this->getID()));
1685 $this->addHistory('homepage', $this->data_array['homepage']);
1686 $this->data_array['homepage'] = $homepage;
1691 $this->setError(_('Could not insert homepage to database'));
1694 $this->setError(_('Homepage cannot be empty'));
1699 * getTags - Tags of this project.
1701 * @return string List of tags. Comma separated
1703 function getTags() {
1704 $sql = 'SELECT name FROM project_tags WHERE group_id = $1';
1705 $res = db_query_params($sql, array($this->getID()));
1706 return join(', ', util_result_column_to_array($res));
1710 * setTags - Set tags of this project.
1712 * @param string $tags
1713 * @return string database result.
1715 function setTags($tags) {
1717 $sql = 'DELETE FROM project_tags WHERE group_id=$1';
1718 $res = db_query_params($sql, array($this->getID()));
1720 $this->setError(_('Deleting old tags')._(': ').db_error());
1724 $inserted = array();
1725 $tags_array = preg_split('/[;,]/', $tags);
1726 foreach ($tags_array as $tag) {
1727 $tag = preg_replace('/[\t\r\n]/', ' ', $tag);
1728 // Allowed caracteres: [A-Z][a-z][0-9] -_&'#+.
1729 if (preg_match('/[^[:alnum:]| |\-|_|\&|\'|#|\+|\.]/', $tag)) {
1730 $this->setError(_('Bad tag name, you only can use the following characters: [A-Z][a-z][0-9]-_&\'#+. and space'));
1735 if ($tag == '' || array_search($tag, $inserted) !== false) {
1738 $sql = 'INSERT INTO project_tags (group_id,name) VALUES ($1, $2)';
1739 $res = db_query_params($sql, array($this->getID(), $tag));
1741 $this->setError(_('Setting tags')._(': ').db_error());
1752 * getPermission - Return a Permission for this Group
1754 * @return object The Permission.
1756 function &getPermission() {
1757 return permission_get_object($this);
1760 function delete($sure, $really_sure, $really_really_sure) {
1761 if (!$sure || !$really_sure || !$really_really_sure) {
1762 $this->setMissingParamsError(_('Please tick all checkboxes.'));
1765 if ($this->getID() == GROUP_IS_NEWS ||
1766 $this->getID() == GROUP_IS_MASTER ||
1767 $this->getID() == GROUP_IS_STATS ||
1768 $this->getID() == GROUP_IS_PEER_RATINGS) {
1769 $this->setError(_('Cannot Delete System Group'));
1772 $perm = $this->getPermission();
1773 if (!$perm || !is_object($perm)) {
1774 $this->setPermissionDeniedError();
1776 } elseif ($perm->isError() || !$perm->isSuperUser()) {
1777 $this->setPermissionDeniedError();
1783 // Remove all the members
1785 $members = $this->getMembers(false);
1786 foreach ($members as $i) {
1787 if(!$this->removeUser($i->getID())) {
1788 $this->setError(_('Could not properly remove member')._(': ').$i->getID());
1793 // unlink roles from this project
1794 foreach ($this->getRoles() as $r) {
1795 if ($r->getHomeProject() == NULL
1796 || $r->getHomeProject()->getID() != $this->getID()) {
1797 $r->unlinkProject($this);
1804 $atf = new ArtifactTypeFactory($this, true);
1805 $at_arr = $atf->getArtifactTypes();
1806 foreach ($at_arr as $i) {
1807 if (!is_object($i)) {
1810 if (!$i->delete(1,1)) {
1811 $this->setError(_('Could not properly delete the tracker')._(': ').$i->getErrorMessage());
1818 $rmf = new RoadmapFactory($this);
1819 $rm_arr = $rmf->getRoadmaps();
1820 foreach ($rm_arr as $i) {
1821 if (!is_object($i)) {
1824 if (!$i->delete()) {
1825 $this->setError(_('Could not properly delete the roadmap')._(': ').$i->getErrorMessage());
1833 $ff = new ForumFactory($this, true);
1834 $f_arr = $ff->getForums();
1835 foreach ($f_arr as $i) {
1836 if (!is_object($i)) {
1839 if(!$i->delete(1,1)) {
1840 $this->setError(_('Could not properly delete the forum')._(': ').$i->getErrorMessage());
1846 // Delete Subprojects
1848 $pgf = new ProjectGroupFactory($this, true);
1849 $pg_arr = $pgf->getProjectGroups();
1850 foreach ($pg_arr as $i) {
1851 if (!is_object($i)) {
1854 if (!$i->delete(1,1)) {
1855 $this->setError(_('Could not properly delete the ProjectGroup')._(': ').$i->getErrorMessage());
1861 // Delete FRS Packages
1863 $res = db_query_params('SELECT * FROM frs_package WHERE group_id=$1',
1864 array($this->getID()));
1866 $this->setError(_('Error FRS Packages')._(': ').db_error());
1871 while ($arr = db_fetch_array($res)) {
1872 $frsp=new FRSPackage($this, $arr['package_id'], $arr);
1873 if (!$frsp->delete(1, 1)) {
1874 $this->setError(_('Could not properly delete the FRSPackage')._(': ').$frsp->getErrorMessage());
1881 $news_group = group_get_object(GROUP_IS_NEWS);
1882 $res = db_query_params('SELECT forum_id FROM news_bytes WHERE group_id=$1',
1883 array($this->getID()));
1885 $this->setError(_('Error Deleting News')._(': ').db_error());
1890 for ($i=0; $i<db_numrows($res); $i++) {
1891 $Forum = new Forum($news_group,db_result($res,$i,'forum_id'));
1892 if (!$Forum->delete(1,1)) {
1893 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1898 // Delete news forums in group itself
1899 for ($i = 0; $i < db_numrows($res); $i++) {
1900 $Forum = new Forum($this, db_result($res, $i, 'forum_id'));
1901 if (!$Forum->delete(1, 1)) {
1902 $this->setError(_('Could not delete News Forum')._(': ').$Forum->getID());
1907 $res = db_query_params('DELETE FROM news_bytes WHERE group_id=$1',
1908 array($this->getID()));
1910 $this->setError(_('Error Deleting News')._(': ').db_error());
1918 $res = db_query_params('DELETE FROM doc_data WHERE group_id=$1',
1919 array($this->getID()));
1921 $this->setError(_('Error Deleting Documents')._(': ').db_error());
1926 $res = db_query_params('DELETE FROM doc_groups WHERE group_id=$1',
1927 array($this->getID()));
1929 $this->setError(_('Error Deleting Document Groups')._(': ').db_error());
1937 $res=db_query_params('DELETE FROM project_tags WHERE group_id=$1', array($this->getID()));
1939 $this->setError(_('Error Deleting Tags')._(': ').db_error());
1945 // Delete group history
1947 $res = db_query_params('DELETE FROM group_history WHERE group_id=$1',
1948 array($this->getID()));
1950 $this->setError(_('Error Deleting Project History')._(': ').db_error());
1956 // Delete group plugins
1958 $res = db_query_params('DELETE FROM group_plugin WHERE group_id=$1',
1959 array($this->getID()));
1961 $this->setError(_('Error Deleting Project Plugins')._(': ').db_error());
1967 // Delete group cvs stats
1969 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE group_id=$1',
1970 array($this->getID()));
1972 $this->setError(_('Error Deleting SCM Statistics')._(': ').db_error());
1980 $sf = new SurveyFactory($this, true);
1981 $s_arr =& $sf->getSurveys();
1982 foreach ($s_arr as $i) {
1983 if (!is_object($i)) {
1986 if (!$i->delete()) {
1987 $this->setError(_('Could not properly delete the survey'));
1992 // Delete SurveyQuestions
1994 $sqf = new SurveyQuestionFactory($this);
1995 $sq_arr = $sqf->getSurveyQuestions();
1996 if (is_array($sq_arr)) {
1997 foreach ($sq_arr as $i) {
1998 if (!is_object($i)) {
2001 if (!$i->delete()) {
2002 $this->setError(_('Could not properly delete the survey questions'));
2010 // Delete Mailing List Factory
2012 $mlf = new MailingListFactory($this, true);
2013 $ml_arr = $mlf->getMailingLists();
2014 foreach ($ml_arr as $i) {
2015 if (!is_object($i)) {
2018 if (!$i->delete(1,1)) {
2019 $this->setError(_('Could not properly delete the mailing list'));
2027 $res = db_query_params('DELETE FROM trove_group_link WHERE group_id=$1',
2028 array($this->getID()));
2030 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2035 $res = db_query_params('DELETE FROM trove_agg WHERE group_id=$1',
2036 array($this->getID()));
2038 $this->setError(_('Error Deleting Trove')._(': ').db_error());
2046 $res = db_query_params('DELETE FROM project_sums_agg WHERE group_id=$1',
2047 array($this->getID()));
2049 $this->setError(_('Error Deleting Counters')._(': ').db_error());
2054 $res = db_query_params('INSERT INTO deleted_groups (unix_group_name, delete_date, isdeleted) VALUES ($1, $2, $3)',
2055 array($this->getUnixName(),
2059 $this->setError(_('Error Deleting Project')._(': ').db_error());
2064 // Remove users & delete roles from this project
2065 $members = $this->getMembers();
2066 foreach ($members as $userObject) {
2067 $this->removeUser($userObject->getID());
2069 $localRolesId = $this->getRolesId(false);
2070 foreach ($localRolesId as $localRoleId) {
2071 $roleObject = new Role($this, $localRoleId);
2072 $roleObject->delete();
2074 // Delete entry in groups.
2075 $res = db_query_params('DELETE FROM groups WHERE group_id=$1',
2076 array($this->getID()));
2078 $this->setError(_('Error Deleting Project')._(': ').db_error());
2085 $hook_params = array();
2086 $hook_params['group'] = $this;
2087 $hook_params['group_id'] = $this->getID();
2088 plugin_hook("group_delete", $hook_params);
2090 if (forge_get_config('upload_dir') != '' && $this->getUnixName()) {
2091 exec('/bin/rm -rf '.forge_get_config('upload_dir').'/'.$this->getUnixName().'/');
2093 if (forge_get_config('ftp_upload_dir') != '' && $this->getUnixName()) {
2094 exec('/bin/rm -rf '.forge_get_config('ftp_upload_dir').'/'.$this->getUnixName().'/');
2099 db_query_params('DELETE FROM rep_group_act_monthly WHERE group_id=$1', array($this->getID()));
2100 db_query_params('DELETE FROM rep_group_act_weekly WHERE group_id=$1', array($this->getID()));
2101 db_query_params('DELETE FROM rep_group_act_daily WHERE group_id=$1', array($this->getID()));
2102 unset($this->data_array);
2107 Basic functions to add/remove users to/from a group
2108 and update their permissions
2112 * addUser - controls adding a user to a group.
2114 * @param string $user_identifier Unix name of the user to add OR integer user_id.
2115 * @param int $role_id The role_id this user should have.
2116 * @return bool success.
2119 function addUser($user_identifier, $role_id) {
2122 Admins can add users to groups
2125 if (!forge_check_perm ('project_admin', $this->getID())) {
2126 $this->setPermissionDeniedError();
2132 get user id for this user's unix_name
2134 if (is_int ($user_identifier)) { // user_id or user_name
2135 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_id=$1', array($user_identifier));
2137 $res_newuser = db_query_params ('SELECT * FROM users WHERE user_name=$1', array($user_identifier));
2139 if (db_numrows($res_newuser) > 0) {
2141 // make sure user is active
2143 if (db_result($res_newuser,0,'status') != 'A') {
2144 $this->setError(_('User is not active. Only active users can be added.'));
2150 // user was found - set new user_id var
2152 $user_id = db_result($res_newuser,0,'user_id');
2154 $role = new Role($this, $role_id);
2155 if (!$role || !is_object($role)) {
2156 $this->setError(_('Error Getting Role Object'));
2159 } elseif ($role->isError()) {
2160 $this->setError('addUser::roleget::'.$role->getErrorMessage());
2165 $role->addUser(user_get_object($user_id));
2166 if (!$SYS->sysCheckCreateGroup($this->getID())){
2167 $this->setError($SYS->getErrorMessage());
2171 if (!$SYS->sysCheckCreateUser($user_id)) {
2172 $this->setError($SYS->getErrorMessage());
2176 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2177 $this->setError($SYS->getErrorMessage());
2183 // user doesn't exist
2185 $this->setError(_('That user does not exist.'));
2190 $hook_params['group'] = $this;
2191 $hook_params['group_id'] = $this->getID();
2192 $hook_params['user'] = user_get_object($user_id);
2193 $hook_params['user_id'] = $user_id;
2194 plugin_hook ("group_adduser", $hook_params);
2199 $this->addHistory(_('Added User'), $user_identifier);
2205 $add_u = user_get_object($user_id);
2207 if (is_array($this->membersArr)) {
2208 foreach ($this->membersArr as $u) {
2209 if ($u->getID() == $add_u->getID()) {
2215 $this->membersArr[] = $add_u;
2223 * removeUser - controls removing a user from a group.
2225 * Users can remove themselves.
2227 * @param int $user_id The ID of the user to remove.
2228 * @return bool success.
2230 function removeUser($user_id) {
2233 if ($user_id != user_getid()
2234 && !forge_check_perm('project_admin', $this->getID())) {
2235 $this->setPermissionDeniedError();
2241 $user = user_get_object($user_id);
2242 $roles = RBACEngine::getInstance()->getAvailableRolesForUser($user);
2243 $found_roles = array();
2244 foreach ($roles as $role) {
2245 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2246 $found_roles[] = $role;
2249 if (empty($found_roles)) {
2250 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2254 foreach ($found_roles as $found_role) {
2255 $found_role->removeUser($user);
2256 if (!$SYS->sysGroupCheckUser($this->getID(), $user_id)) {
2257 $this->setError($SYS->getErrorMessage());
2264 // reassign open artifacts to id=100
2266 $res = db_query_params('UPDATE artifact SET assigned_to=100
2267 WHERE group_artifact_id
2268 IN (SELECT group_artifact_id
2269 FROM artifact_group_list
2270 WHERE group_id=$1 AND status_id=1 AND assigned_to=$2)',
2271 array($this->getID(),
2274 $this->setError(_('Error')._(': ')._('artifact')._(': ').db_error());
2280 // reassign open tasks to id=100
2281 // first have to purge any assignments that would cause
2282 // conflict with existing assignment to 100
2284 $res = db_query_params('DELETE FROM project_assigned_to
2285 WHERE project_task_id IN (SELECT pt.project_task_id
2286 FROM project_task pt, project_group_list pgl, project_assigned_to pat
2287 WHERE pt.group_project_id = pgl.group_project_id
2288 AND pat.project_task_id=pt.project_task_id
2289 AND pt.status_id=1 AND pgl.group_id=$1
2290 AND pat.assigned_to_id=$2)
2291 AND assigned_to_id=100',
2292 array($this->getID(),
2295 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 1, db_error()));
2299 $res = db_query_params('UPDATE project_assigned_to SET assigned_to_id=100
2300 WHERE project_task_id IN (SELECT pt.project_task_id
2301 FROM project_task pt, project_group_list pgl
2302 WHERE pt.group_project_id = pgl.group_project_id
2303 AND pt.status_id=1 AND pgl.group_id=$1)
2304 AND assigned_to_id=$2',
2305 array($this->getID(),
2308 $this->setError(_('Error')._(': ').sprintf(_('project_assigned_to %d: %s'), 2, db_error()));
2314 // Remove user from system
2316 if (!$SYS->sysGroupRemoveUser($this->getID(), $user_id)) {
2317 $this->setError($SYS->getErrorMessage());
2322 $hook_params['group'] = $this;
2323 $hook_params['group_id'] = $this->getID();
2324 $hook_params['user'] = user_get_object($user_id);
2325 $hook_params['user_id'] = $user_id;
2326 plugin_hook("group_removeuser", $hook_params);
2329 $this->addHistory(_('Removed User'), $user_id);
2336 $del_u = user_get_object($user_id);
2337 foreach ($this->membersArr as $k => $u) {
2338 if ($u->getID() == $del_u->getID()) {
2339 unset($this->membersArr[$k]);
2348 * updateUser - controls updating a user's role in this group.
2350 * @param int $user_id The ID of the user.
2351 * @param int $role_id The role_id to set this user to.
2352 * @return bool success.
2354 function updateUser($user_id, $role_id) {
2356 if (!forge_check_perm ('project_admin', $this->getID())) {
2357 $this->setPermissionDeniedError();
2361 $newrole = RBACEngine::getInstance()->getRoleById ($role_id);
2362 if (!$newrole || !is_object($newrole)) {
2363 $this->setError(_('Could Not Get Role'));
2365 } elseif ($newrole->isError()) {
2366 $this->setError(_('Role')._(': ').$newrole->getErrorMessage());
2368 } elseif ($newrole->getHomeProject() == NULL
2369 || $newrole->getHomeProject()->getID() != $this->getID()) {
2370 $this->setError(_('Wrong destination role'));
2373 $user = user_get_object ($user_id);
2374 $roles = RBACEngine::getInstance()->getAvailableRolesForUser ($user);
2376 foreach ($roles as $role) {
2377 if ($role->getHomeProject() && $role->getHomeProject()->getID() == $this->getID()) {
2378 $found_role = $role;
2382 if ($found_role == NULL) {
2383 $this->setError(_('Error')._(': ')._('User not removed')._(': ').$user_id);
2387 $found_role->removeUser ($user);
2388 $newrole->addUser ($user);
2390 $this->addHistory(_('Updated User'), $user_id);
2395 * addHistory - Makes an audit trail entry for this project.
2397 * @param string $field_name The name of the field.
2398 * @param string $old_value The Old Value for this $field_name.
2399 * @return resource database result handle.
2402 function addHistory($field_name, $old_value) {
2403 if ($old_value == NULL) {
2407 return db_query_params('INSERT INTO group_history(group_id,field_name,old_value,mod_by,adddate)
2408 VALUES ($1,$2,$3,$4,$5)',
2409 array($this->getID(),
2417 * activateUsers - Make sure that group members have unix accounts.
2419 * Setup unix accounts for group members. Can be called even
2420 * if members are already active.
2424 function activateUsers() {
2426 Activate member(s) of the project
2431 $members = $this->getUsers(true);
2433 foreach ($members as $member) {
2434 $user_id = $member->getID();
2436 if (!$SYS->sysCheckCreateGroup($this->getID())){
2437 $this->setError($SYS->getErrorMessage());
2441 if (!$SYS->sysCheckCreateUser($user_id)) {
2442 $this->setError($SYS->getErrorMessage());
2446 if (!$SYS->sysGroupCheckUser($this->getID(),$user_id)) {
2447 $this->setError($SYS->getErrorMessage());
2457 * getMembers - returns array of User objects for this project
2459 * @param bool $onlyactive Only users with state active, or all users of group
2460 * @return array of User objects for this group.
2462 function getMembers($onlyactive = true) {
2463 return $this->getUsers(true, $onlyactive);
2467 * replaceTemplateStrings - fill-in some blanks with project name
2469 * @param string $string Template string
2470 * @return string String after replacements
2472 function replaceTemplateStrings($string) {
2473 $string = str_replace('UNIXNAME', $this->getUnixName(), $string);
2474 $string = str_replace('PUBLICNAME', $this->getPublicName(), $string);
2475 $string = str_replace('DESCRIPTION', $this->getDescription(), $string);
2480 * approve - Approve pending project.
2482 * @param object $user The User object who is doing the updating.
2486 function approve(&$user) {
2487 global $gfcommon,$gfwww;
2488 require_once $gfcommon.'widget/WidgetLayoutManager.class.php';
2490 if ($this->getStatus()=='A') {
2491 $this->setError(_('Group already active'));
2497 // Step 1: Activate group and create LDAP entries
2498 if (!$this->setStatus($user, 'A')) {
2505 // Switch to system language for item creation
2506 setup_gettext_from_sys_lang();
2508 // Create default roles
2509 $idadmin_group = NULL;
2510 foreach (get_group_join_requests ($this) as $gjr) {
2511 $idadmin_group = $gjr->getUserID();
2514 if ($idadmin_group == NULL) {
2515 $idadmin_group = $user->getID();
2518 $template = $this->getTemplateProject();
2519 $id_mappings = array();
2520 $seen_admin_role = false;
2522 // Copy roles from template project
2523 foreach($template->getRoles() as $oldrole) {
2524 if ($oldrole->getHomeProject() != NULL) {
2525 $role = new Role($this);
2527 // Need to use a different role name so that the permissions aren't set from the hardcoded defaults
2528 $role->create('TEMPORARY ROLE NAME', $data, true);
2529 $role->setName($oldrole->getName());
2530 if ($oldrole->getSetting ('project_admin', $template->getID())) {
2531 $seen_admin_role = true;
2535 $role->linkProject($this);
2537 $id_mappings['role'][$oldrole->getID()] = $role->getID();
2538 // Reuse the project_admin permission
2539 $role->setSetting ('project_admin', $this->getID(), $oldrole->getSetting ('project_admin', $template->getID()));
2543 if (!$seen_admin_role) {
2544 $role = new Role($this);
2545 $adminperms = array('project_admin' => array ($this->getID() => 1));
2546 $role->create ('Admin', $adminperms, true);
2549 $roles = $this->getRoles();
2550 foreach ($roles as $r) {
2551 if ($r->getHomeProject() == NULL) {
2554 if ($r->getSetting ('project_admin', $this->getID())) {
2555 $r->addUser(user_get_object ($idadmin_group));
2559 // Temporarily switch to the submitter's identity
2560 $saved_session = session_get_user();
2561 session_set_internal($idadmin_group);
2564 if (forge_get_config('use_tracker')) {
2565 $this->setUseTracker ($template->usesTracker());
2566 if ($template->usesTracker()) {
2567 $oldatf = new ArtifactTypeFactory($template);
2568 foreach ($oldatf->getArtifactTypes() as $o) {
2569 $t = new ArtifactType ($this);
2570 $t->create ($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->emailAll(),$o->getEmailAddress(),$o->getDuePeriod()/86400,0,$o->getSubmitInstructions(),$o->getBrowseInstructions());
2571 $id_mappings['tracker'][$o->getID()] = $t->getID();
2576 if (forge_get_config('use_pm')) {
2577 $this->setUsePM ($template->usesPM());
2578 if ($template->usesPM()) {
2579 $oldpgf = new ProjectGroupFactory($template);
2580 foreach ($oldpgf->getProjectGroups() as $o) {
2581 $pg = new ProjectGroup($this);
2582 $pg->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo());
2583 $id_mappings['pm'][$o->getID()] = $pg->getID();
2588 if (forge_get_config('use_forum')) {
2589 $this->setUseForum($template->usesForum());
2590 if ($template->usesForum()) {
2591 $oldff = new ForumFactory($template);
2592 foreach ($oldff->getForums() as $o) {
2593 $f = new Forum($this);
2594 $f->create($this->replaceTemplateStrings($o->getName()),$this->replaceTemplateStrings($o->getDescription()),$o->getSendAllPostsTo(),1);
2595 $id_mappings['forum'][$o->getID()] = $f->getID();
2600 if (forge_get_config('use_docman')) {
2601 $this->setUseDocman($template->usesDocman());
2602 if ($template->usesDocman()) {
2603 $olddgf = new DocumentGroupFactory($template);
2604 // First pass: create all docgroups
2605 $id_mappings['docman_docgroup'][0] = 0;
2606 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2607 $ndg = new DocumentGroup($this);
2608 // .trash is a reserved directory
2609 if ($o->getName() != '.trash') {
2610 $ndg->create($this->replaceTemplateStrings($o->getName()), 0, 1, null, true);
2611 $id_mappings['docman_docgroup'][$o->getID()] = $ndg->getID();
2614 // Second pass: restore hierarchy links & stateid
2615 foreach ($olddgf->getDocumentGroups(array(1, 5)) as $o) {
2616 $ndgf = new DocumentGroup($this);
2617 if ($o->getName() != '.trash') {
2618 $ndgf->fetchData($id_mappings['docman_docgroup'][$o->getID()]);
2619 $ndgf->update($ndgf->getName(), $id_mappings['docman_docgroup'][$o->getParentID()], 0, $o->getState());
2625 if (forge_get_config('use_frs')) {
2626 $this->setUseFRS ($template->usesFRS());
2627 if ($template->usesFRS()) {
2628 foreach (get_frs_packages($template) as $o) {
2629 $newp = new FRSPackage($this);
2630 $nname = $this->replaceTemplateStrings($o->getName());
2631 $newp->create($nname, $o->isPublic());
2632 $id_mappings['frs'][$o->getID()] = $newp->getID();
2633 foreach(get_frs_releases($o) as $or) {
2634 $newr = new FRSRelease($newp);
2635 $newr->create($this->replaceTemplateStrings($or->getName()), $this->replaceTemplateStrings($or->getNotes()), $this->replaceTemplateStrings($or->getChanges()), $or->getPreformatted());
2636 $id_mappings['frs_release'][$or->getID()] = $newr->getID();
2642 if (forge_get_config('use_mail')) {
2643 $this->setUseMail($template->usesMail());
2644 if ($template->usesMail()) {
2645 $oldmlf = new MailingListFactory($template);
2646 foreach ($oldmlf->getMailingLists() as $o) {
2647 $ml = new MailingList($this);
2648 $nname = preg_replace ('/^'.$template->getUnixName().'-/','',$o->getName());
2650 $ndescription = $this->replaceTemplateStrings($o->getDescription());
2651 $ml->create($nname, $ndescription, $o->isPublic());
2657 /* use SCM plugin from template group */
2658 $this->setUseSCM($template->usesSCM());
2660 foreach ($template->getPlugins() as $plugin_name) {
2661 $this->setPluginUse($plugin_name);
2664 /* use SCM choice from registration page */
2665 foreach ($template->getPlugins() as $plugin_name) {
2666 if (substr($plugin_name, 3) == 'scm' && $plugin_name != 'scmhook') {
2667 /* skip copying scm plugins */
2670 /* enable other plugins though */
2671 $this->setPluginUse($plugin_name);
2675 foreach ($template->getRoles() as $oldrole) {
2676 $newrole = RBACEngine::getInstance()->getRoleById($id_mappings['role'][$oldrole->getID()]);
2677 if ($oldrole->getHomeProject() != NULL
2678 && $oldrole->getHomeProject()->getID() == $template->getID()) {
2679 $newrole->setPublic ($oldrole->isPublic());
2681 $oldsettings = $oldrole->getSettingsForProject ($template);
2683 $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');
2684 foreach ($sections as $section) {
2685 $newrole->setSetting ($section, $this->getID(), $oldsettings[$section][$template->getID()]);
2688 $sections = array('tracker', 'pm', 'forum', 'frs');
2689 foreach ($sections as $section) {
2690 if (isset ($oldsettings[$section])) {
2691 foreach ($oldsettings[$section] as $k => $v) {
2692 // Only copy perms for tools that have been copied
2693 if (isset ($id_mappings[$section][$k])) {
2694 $newrole->setSetting ($section,
2695 $id_mappings[$section][$k],
2703 $lm = new WidgetLayoutManager();
2704 $lm->createDefaultLayoutForProject($this->getID(), $template->getID());
2706 // second computation to clone fields and workflow
2707 if (forge_get_config('use_tracker')) {
2708 if ($template->usesTracker()) {
2709 $oldatf = new ArtifactTypeFactory($template);
2710 foreach ($oldatf->getArtifactTypes() as $o) {
2711 $t = artifactType_get_object($id_mappings['tracker'][$o->getID()]);
2712 $id_mappings['tracker'][$o->getID()] = $t->getID();
2713 $newEFIds = $t->cloneFieldsFrom($o->getID(), $id_mappings);
2714 if (forge_get_config('use_tracker_widget_display')) {
2715 $lm->createDefaultLayoutForTracker($t->getID(), $o->getID(), $newEFIds);
2722 $params['template'] = $template;
2723 $params['project'] = $this;
2724 $params['id_mappings'] = $id_mappings;
2725 plugin_hook_by_reference ('clone_project_from_template', $params);
2727 // Disable everything - except use_scm (manually set in the registration page)
2728 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,
2729 use_docman = 0, use_ftp = 0, use_tracker = 0, use_frs = 0, use_stats = 0 WHERE group_id = $1',
2730 array($this->getID()));
2733 $this->normalizeAllRoles();
2734 // empty members cache because the group creator is not yet in cache.
2735 unset($this->membersArr);
2736 $this->activateUsers();
2738 // Delete fake join request
2739 foreach (get_group_join_requests ($this) as $gjr) {
2743 // Switch back to user preference
2744 session_set_internal($saved_session->getID());
2745 setup_gettext_from_context();
2747 $this->sendApprovalEmail();
2748 $this->addHistory(_('Approved'), 'x');
2751 // Plugin can make approve operation there
2754 $params['group'] = $this;
2755 $params['group_id'] = $this->getID();
2756 plugin_hook('group_approved', $params);
2762 * sendApprovalEmail - Send new project email.
2764 * @return bool success.
2767 function sendApprovalEmail() {
2768 $admins = RBACEngine::getInstance()->getUsersByAllowedAction ('project_admin', $this->getID());
2770 if (empty($admins)) {
2771 $this->setError(_('Group does not have any administrators.'));
2775 // send one email per admin
2776 foreach ($admins as $admin) {
2777 setup_gettext_for_user ($admin);
2779 $message = sprintf(_('Your project registration for %s has been approved.'), forge_get_config ('forge_name')) . "\n\n"
2781 . _('Project Full Name')._(': '). htmlspecialchars_decode($this->getPublicName()) . "\n"
2782 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2784 . _('Your DNS will take up to a day to become active on our site. '
2785 .'Your web site is accessible through your shell account. Please read '
2786 .'site documentation (see link below) about intended usage, available '
2787 .'services, and directory layout of the account.') . "\n\n"
2789 . sprintf(_('If you visit your own project page in %s while logged in, '
2790 . 'you will find additional menu functions to your left labeled “Project Admin”.'),
2791 forge_get_config ('forge_name')) . "\n\n"
2793 . sprintf(_('We highly suggest that you now visit %1$s and create a public '
2794 . 'description for your project. This can be done by visiting your project '
2795 . 'page while logged in, and selecting “Project Admin” from the menus '
2796 . 'on the left (or by visiting %2$s after login).'),
2797 forge_get_config ('forge_name'), util_make_url('/project/admin/?group_id='.$this->getID())) . "\n\n"
2799 . sprintf(_('Your project will also not appear in the Trove Software Map (primary '
2800 . 'list of projects hosted on %s which offers great flexibility in '
2801 . 'browsing and search) until you categorize it in the project administration '
2802 . 'screens. So that people can find your project, you should do this now. '
2803 . 'Visit your project while logged in, and select “Project Admin” from the '
2804 . 'menus on the left.'), forge_get_config ('forge_name')) . "\n\n"
2806 . sprintf(_('Enjoy the system, and please tell others about %s. Let us know '
2807 . 'if there is anything we can do to help you.'), forge_get_config ('forge_name')) . "\n\n"
2809 . sprintf(_('-- the %s staff'), forge_get_config ('forge_name')) . "\n";
2811 util_send_message($admin->getEmail(), sprintf(_('%s Project Approved'), forge_get_config ('forge_name')), $message);
2813 setup_gettext_from_context();
2820 * sendRejectionEmail - Send project rejection email.
2822 * This function sends out a rejection message to a user who
2823 * registered a project.
2825 * @param int $response_id The id of the response to use.
2826 * @param string $message The rejection message.
2827 * @return bool completion status.
2830 function sendRejectionEmail($response_id, $message = 'zxcv') {
2831 $submitters = array();
2832 foreach (get_group_join_requests ($this) as $gjr) {
2833 $submitters[] = user_get_object($gjr->getUserID());
2836 if (empty($submitters)) {
2837 $this->setError(_('Group does not have any administrators.'));
2841 foreach ($submitters as $admin) {
2842 setup_gettext_for_user($admin);
2844 $response = sprintf(_('Your project registration for %s has been denied.'), forge_get_config('forge_name')) . "\n\n"
2845 . _('Project Full Name')._(': '). $this->getPublicName() . "\n"
2846 . _('Project Unix Name')._(': '). $this->getUnixName() . "\n\n"
2847 . _('Reasons for negative decision')._(': ') . "\n\n";
2849 // Check to see if they want to send a custom rejection response
2850 if ($response_id == 0) {
2851 $response .= $message;
2853 $response .= db_result(
2854 db_query_params('SELECT response_text FROM canned_responses WHERE response_id=$1', array($response_id)),
2859 util_send_message($admin->getEmail(), sprintf(_('%s Project Denied'), forge_get_config('forge_name')), $response);
2860 setup_gettext_from_context();
2867 * sendNewProjectNotificationEmail - Send new project notification email.
2869 * This function sends out a notification email to the
2870 * SourceForge admin user when a new project is
2873 * @return bool success.
2876 function sendNewProjectNotificationEmail() {
2877 // Get the user who wants to register the project
2878 $submitters = array();
2879 foreach (get_group_join_requests ($this) as $gjr) {
2880 $submitters[] = user_get_object($gjr->getUserID());
2882 if (empty($submitters)) {
2883 $this->setError(_('Could not find user who has submitted the project.'));
2887 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('approve_projects', -1);
2889 if (empty($admins)) {
2890 $this->setError(_('There is no administrator to send the mail to.'));
2894 foreach ($admins as $admin) {
2895 $admin_email = $admin->getEmail();
2896 setup_gettext_for_user ($admin);
2898 $message = sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')) . "\n\n"
2899 . _('Project Full Name')._(': ').htmlspecialchars_decode($this->getPublicName()) . "\n"
2900 . _('Submitted Description')._(': ').htmlspecialchars_decode($this->getRegistrationPurpose()) . "\n";
2902 foreach ($submitters as $submitter) {
2903 $message .= _('Submitter')._(': ').$submitter->getRealName().' ('.$submitter->getUnixName().')' . "\n\n";
2907 . _('Please visit the following URL to approve or reject this project')._(': '). "\n"
2908 . util_make_url('/admin/approve-pending.php');
2909 util_send_message($admin_email, sprintf(_('New %s Project Submitted'), forge_get_config('forge_name')), $message);
2910 setup_gettext_from_context();
2913 $email = $submitter->getEmail();
2914 setup_gettext_for_user ($submitter);
2916 $message = sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')) . "\n\n"
2917 . _('Project Full Name')._(': ') . $this->getPublicName() . "\n"
2918 . _('Submitted Description')._(': ') . util_unconvert_htmlspecialchars($this->getRegistrationPurpose()) . "\n\n"
2919 . sprintf(_('The %s admin team will now examine your project submission. You will be notified of their decision.'),
2920 forge_get_config ('web_host'));
2922 util_send_message($email, sprintf(_('New %s Project Submitted'), forge_get_config ('forge_name')), $message);
2923 setup_gettext_from_context();
2929 * validateGroupName - Validate the group name
2931 * @param string $group_name Project name.
2933 * @return bool an error false and set an error is the group name is invalid otherwise return true
2935 function validateGroupName($group_name) {
2936 if (strlen($group_name)<3) {
2937 $this->setError(_('Project name is too short'));
2939 } elseif (strlen(htmlspecialchars($group_name))>40) {
2940 $this->setError(_('Project name is too long'));
2942 } elseif (group_get_object_by_publicname($group_name)) {
2943 $this->setError(_('Project name already taken'));
2950 * getRolesId - Get Ids of the roles of the group.
2952 * @param bool all role ids or local role ids only. Default is all role ids
2953 * @return array Role ids of this group.
2955 function getRolesId($global = true) {
2956 $role_ids = array();
2958 $res = db_query_params('SELECT role_id FROM pfo_role WHERE home_group_id=$1',
2959 array($this->getID()));
2960 while ($arr = db_fetch_array($res)) {
2961 $role_ids[] = $arr['role_id'];
2964 $res = db_query_params('SELECT role_id FROM role_project_refs WHERE group_id=$1',
2965 array($this->getID()));
2966 while ($arr = db_fetch_array($res)) {
2967 $role_ids[] = $arr['role_id'];
2971 return array_unique($role_ids);
2975 * getRoles - Get the roles of the group.
2977 * @param bool all roles or local roles only. Default is all roles
2978 * @return array Roles of this group.
2980 function getRoles($global = true) {
2983 $roles = $this->getRolesId($global);
2984 $engine = RBACEngine::getInstance();
2985 foreach ($roles as $role_id) {
2986 $result[] = $engine->getRoleById($role_id);
2992 function normalizeAllRoles() {
2993 $roles = $this->getRoles();
2995 foreach ($roles as $r) {
2996 $r->normalizeData();
3001 * getUnixStatus - Status of activation of unix account.
3003 * @return string Values: (N)one, (A)ctive, (S)uspended or (D)eleted
3005 function getUnixStatus() {
3006 return $this->data_array['unix_status'];
3010 * setUnixStatus - Sets status of activation of unix account.
3012 * @param string $status The unix status.
3018 * @return bool success.
3020 function setUnixStatus($status) {
3023 $res = db_query_params ('UPDATE groups SET unix_status=$1 WHERE group_id=$2',
3028 $this->setError(_('Error')._(': ')._('Cannot Update Group Unix Status')._(': ').db_error());
3032 if ($status == 'A') {
3033 if (!$SYS->sysCheckCreateGroup($this->getID())) {
3034 $this->setError($SYS->getErrorMessage());
3039 if ($SYS->sysCheckGroup($this->getID())) {
3040 if (!$SYS->sysRemoveGroup($this->getID())) {
3041 $this->setError($SYS->getErrorMessage());
3048 $this->data_array['unix_status'] = $status;
3055 * getUsers - Get the users of a group
3057 * @param bool $onlylocal
3058 * @param bool $onlyactive Only users with state active, or all users of group
3059 * @return array user's objects.
3061 function getUsers($onlylocal = true, $onlyactive = true) {
3062 if (!isset($this->membersArr)) {
3063 $this->membersArr = array();
3066 foreach ($this->getRoles() as $role) {
3068 && ($role->getHomeProject() == NULL || $role->getHomeProject()->getID() != $this->getID())) {
3071 foreach ($role->getUsers() as $user) {
3072 $ids[] = $user->getID();
3075 $ids = array_unique ($ids);
3076 foreach ($ids as $id) {
3077 $u = user_get_object ($id);
3078 if (!$onlyactive || $u->isActive()) {
3079 $this->membersArr[] = $u;
3083 return $this->membersArr;
3086 function setDocmanCreateOnlineStatus($status) {
3088 $res = db_query_params('UPDATE groups SET use_docman_create_online = $1 WHERE group_id = $2',
3089 array($status, $this->getID()));
3092 $this->setError(_('Error')._(': ')._('Cannot Update Group DocmanCreateOnline Status')._(': ').db_error());
3096 $this->data_array['use_docman_create_online'] = $status;
3102 function setDocmanWebdav($status) {
3104 $res = db_query_params('UPDATE groups SET use_webdav = $1 WHERE group_id = $2',
3109 $this->setError(_('Error')._(': ')._('Cannot Update Group UseWebdav Status')._(': ').db_error());
3113 $this->data_array['use_webdav'] = $status;
3119 function setDocmanSearchStatus($status) {
3121 /* if we activate search engine, we probably want to reindex */
3122 $res = db_query_params('UPDATE groups SET use_docman_search = $1, force_docman_reindex = $1 WHERE group_id = $2',
3123 array($status, $this->getID()));
3126 $this->setError(_('Error')._(': ')._('Cannot Update Group UseDocmanSearch Status')._(': ').db_error());
3130 $this->data_array['use_docman_search'] = $status;
3136 function setDocmanForceReindexSearch($status) {
3138 $res = db_query_params('UPDATE groups SET force_docman_reindex = $1 WHERE group_id = $2',
3139 array($status, $this->getID()));
3142 $this->setError(_('Error')._(': ')._('Cannot Update Group force_docman_reindex')._(': ').db_error());
3146 $this->data_array['force_docman_reindex'] = $status;
3154 * @param int $unit_set_id the effort unit set id
3157 function setEffortUnitSet($unit_set_id) {
3159 $res = db_query_params ('UPDATE groups SET unit_set_id=$1 WHERE group_id=$2',
3160 array($unit_set_id, $this->getID()));
3162 $this->data_array['unit_set_id'] = $unit_set_id;
3172 * getEffortUnitSet - Get the effort unit set id.
3174 * @return int The id of the effort unit set.
3176 function getEffortUnitSet() {
3177 return $this->data_array['unit_set_id'];
3180 function getWidgetLayoutConfig() {
3181 $lm = new WidgetLayoutManager();
3182 return $lm->getLayout($this->getID(), WidgetLayoutManager::OWNER_TYPE_GROUP);
3186 * castVote - Vote on this project or retract the vote
3187 * @param bool $value true to cast, false to retract
3188 * @return bool success (false sets error message)
3190 function castVote($value = true) {
3191 if (!($uid = user_getid()) || $uid == 100) {
3192 $this->setMissingParamsError(_('User ID not passed'));
3195 if (!$this->canVote()) {
3196 $this->setPermissionDeniedError();
3199 $has_vote = $this->hasVote($uid);
3200 if ($has_vote == $value) {
3201 /* nothing changed */
3205 $res = db_query_params('INSERT INTO group_votes (group_id, user_id) VALUES ($1, $2)',
3206 array($this->getID(), $uid));
3208 $res = db_query_params('DELETE FROM group_votes WHERE group_id = $1 AND user_id = $2',
3209 array($this->getID(), $uid));
3212 $this->setError(db_error());
3219 * hasVote - Check if a user has voted on this group item
3221 * @param int|bool $uid user ID (default: current user)
3222 * @return bool true if a vote exists
3224 function hasVote($uid = false) {
3226 $uid = user_getid();
3228 if (!$uid || $uid == 100) {
3231 $res = db_query_params('SELECT * FROM group_votes WHERE group_id = $1 AND user_id = $2',
3232 array($this->getID(), $uid));
3233 return (db_numrows($res) == 1);
3237 * getVotes - get number of valid cast and potential votes
3239 * @return array|bool (votes, voters, percent)
3241 function getVotes() {
3242 if ($this->votes !== false) {
3243 return $this->votes;
3246 $lvoters = $this->getVoters();
3247 unset($lvoters[0]); /* just in case */
3248 unset($lvoters[100]); /* need users */
3249 if (($numvoters = count($lvoters)) < 1) {
3250 $this->votes = array(0, 0, 0);
3251 return $this->votes;
3254 $res = db_query_params('SELECT COUNT(*) AS count FROM group_votes WHERE group_id = $1 AND user_id = ANY($2)',
3255 array($this->getID(), db_int_array_to_any_clause($lvoters)));
3256 $db_count = db_fetch_array($res);
3257 $numvotes = $db_count['count'];
3259 /* check for invalid values */
3260 if ($numvotes < 0 || $numvoters < $numvotes) {
3261 $this->votes = array(-1, -1, 0);
3263 $this->votes = array($numvotes, $numvoters,
3264 (int)($numvotes * 100 / $numvoters + 0.5));
3266 return $this->votes;
3270 * canVote - check whether the current user can vote on
3271 * items in this project
3273 * @return bool true if they can
3275 function canVote() {
3276 if (in_array(user_getid(), $this->getVoters())) {
3283 * getVoters - get IDs of users that may vote on
3284 * items in this project
3286 * @return array list of user IDs
3288 function getVoters() {
3289 if ($this->voters !== false) {
3290 return $this->voters;
3293 $this->voters = array();
3294 if (($engine = RBACEngine::getInstance())
3295 && ($lvoters = $engine->getUsersByAllowedAction('project_read', $this->getID()))
3296 && (count($lvoters) > 0)) {
3297 foreach ($lvoters as $voter) {
3298 $voter_id = $voter->getID();
3299 $this->voters[$voter_id] = $voter_id;
3302 return $this->voters;
3307 * group_getname() - get the group name
3309 * @param int $group_id The group ID
3314 function group_getname ($group_id = 0) {
3315 $grp = group_get_object($group_id);
3317 return $grp->getPublicName();
3324 * group_getunixname() - get the unixname for a group
3326 * @param int $group_id The group ID
3331 function group_getunixname ($group_id) {
3332 $grp = group_get_object($group_id);
3334 return $grp->getUnixName();
3341 * group_get_result() - Get the group object result ID.
3343 * @param int $group_id The group ID
3348 function &group_get_result($group_id=0) {
3349 $grp = group_get_object($group_id);
3351 return $grp->getData();
3357 function getAllProjectTags($onlyvisible = true) {
3358 $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',
3361 if (!$res || db_numrows($res) == 0) {
3367 while ($arr = db_fetch_array($res)) {
3369 $group_id = $arr[1];
3370 if (!isset($result[$tag])) {
3371 $result[$tag] = array();
3374 if (!$onlyvisible || forge_check_perm('project_read', $group_id)) {
3375 $p = group_get_object($group_id);
3376 $result[$tag][] = array('unix_group_name' => $p->getUnixName(),
3377 'group_id' => $group_id);
3385 * Utility class to compare project based in various criteria (names, unixnames, id, ...)
3388 class ProjectComparator {
3389 var $criterion = 'name';
3391 function Compare ($a, $b) {
3392 switch ($this->criterion) {
3394 return strcmp ($a->getUnixName(), $b->getUnixName());
3401 return ($aid < $bid) ? -1 : 1;
3404 $namecmp = strcoll ($a->getPublicName(), $b->getPublicName());
3405 if ($namecmp != 0) {
3408 /* If several projects share a same public name */
3409 return strcoll ($a->getUnixName(), $b->getUnixName());
3414 function sortProjectList (&$list, $criterion='name') {
3415 $cmp = new ProjectComparator();
3416 $cmp->criterion = $criterion;
3418 return usort ($list, array($cmp, 'Compare'));
3423 // c-file-style: "bsd"