3 * FusionForge user management
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2010, Roland Mas
7 * Copyright 2011, Franck Villaume - Capgemini
8 * Copyright 2012, Franck Villaume - TrivialDev
9 * Copyright (C) 2012 Alain Peyrat - Alcatel-Lucent
10 * http://fusionforge.org
12 * This file is part of FusionForge. FusionForge is free software;
13 * you can redistribute it and/or modify it under the terms of the
14 * GNU General Public License as published by the Free Software
15 * Foundation; either version 2 of the Licence, or (at your option)
18 * FusionForge is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 * user_get_object_by_name() - Get User object by username.
32 * user_get_object is useful so you can pool user objects/save database queries
33 * You should always use this instead of instantiating the object directly
35 * @param string The unix username - required
36 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
37 * @return a user object or false on failure
39 function &user_get_object_by_name($user_name, $res = false) {
40 $user_name = strtolower($user_name);
42 $res = db_query_params('SELECT * FROM users WHERE user_name=$1',
45 return user_get_object(db_result($res, 0, 'user_id'), $res);
49 * user_get_object_by_email() - Get User object by email address
50 * Only works if sys_require_unique_email is true
52 * @param string The unix username - required
53 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
54 * @return a user object or false on failure
57 function user_get_object_by_email($email ,$res = false) {
58 if (!validate_email($email)
59 || !forge_get_config('require_unique_email')) {
63 $res=db_query_params('SELECT * FROM users WHERE email=$1',
66 return user_get_object(db_result($res, 0, 'user_id'), $res);
70 * user_get_object() - Get User object by user ID.
71 * user_get_object is useful so you can pool user objects/save database queries
72 * You should always use this instead of instantiating the object directly
74 * @param int The ID of the user - required
75 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
76 * @return object a user object or false on failure
78 function &user_get_object($user_id, $res = false) {
79 //create a common set of group objects
80 //saves a little wear on the database
82 //automatically checks group_type and
83 //returns appropriate object
86 if (!isset($USER_OBJ["_".$user_id."_"])) {
88 //the db result handle was passed in
90 $res = db_query_params('SELECT * FROM users WHERE user_id=$1',
93 if (!$res || db_numrows($res) < 1) {
94 $USER_OBJ["_".$user_id."_"]=false;
96 $USER_OBJ["_".$user_id."_"]= new GFUser($user_id,$res);
99 return $USER_OBJ["_".$user_id."_"];
102 function &user_get_objects($id_arr) {
107 foreach ($id_arr as $id) {
109 // See if this ID already has been fetched in the cache
111 if (!isset($USER_OBJ["_".$id."_"])) {
115 if (count($fetch) > 0) {
116 $res = db_query_params('SELECT * FROM users WHERE user_id = ANY ($1)',
117 array(db_int_array_to_any_clause ($fetch)));
118 while ($arr = db_fetch_array($res)) {
119 $USER_OBJ["_".$arr['user_id']."_"] = new GFUser($arr['user_id'],$arr);
122 foreach ($id_arr as $id) {
123 $return[] =& $USER_OBJ["_".$id."_"];
128 function &user_get_objects_by_name($username_arr) {
129 $res = db_query_params('SELECT user_id FROM users WHERE lower(user_name) = ANY ($1)',
130 array(db_string_array_to_any_clause ($username_arr)));
131 $arr =& util_result_column_to_array($res, 0);
132 return user_get_objects($arr);
135 function &user_get_objects_by_email($email_arr) {
136 $res=db_query_params('SELECT user_id FROM users WHERE lower(email) = ANY ($1)',
137 array(db_string_array_to_any_clause ($email_arr)));
138 $arr =& util_result_column_to_array($res, 0);
139 return user_get_objects($arr);
142 function &user_get_active_users() {
143 $res=db_query_params('SELECT user_id FROM users WHERE status=$1',
145 return user_get_objects(util_result_column_to_array($res, 0));
148 class GFUser extends Error {
150 * Associative array of data from db.
152 * @var array $data_array.
157 * Is this person a site super-admin?
159 * @var bool $is_super_user
164 * Is this person the logged in user?
166 * @var bool $is_logged_in
171 * Array of preferences
173 * @var array $user_pref
181 * GFUser($id,$res) - CONSTRUCTOR - GENERALLY DON'T USE THIS
183 * instead use the user_get_object() function call
185 * @param int The user_id
186 * @param int The database result set OR array of data
188 function GFUser($id = false, $res = false) {
191 //setting up an empty object
192 //probably going to call create()
196 $this->fetchData($id);
198 if (is_array($res)) {
199 $this->data_array =& $res;
200 } elseif (db_numrows($res) < 1) {
201 //function in class we extended
202 $this->setError(_('User Not Found'));
203 $this->data_array=array();
206 //set up an associative array for use by other functions
207 $this->data_array = db_fetch_array_by_row($res, 0);
208 if (($this->getUnixStatus() == 'A') && (forge_get_config('use_shell'))) {
209 $this->data_array['authorized_keys'] = array();
210 $res = db_query_params('select * from sshkeys where userid = $1 and deleted = 0', array($this->getID()));
211 while ($arr = db_fetch_array($res)) {
212 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['upload'] = $arr['upload'];
213 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['name'] = $arr['name'];
214 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['fingerprint'] = $arr['fingerprint'];
215 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['algorithm'] = $arr['algorithm'];
216 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['deploy'] = $arr['deploy'];
217 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['key'] = $arr['sshkey'];
218 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['keyid'] = $arr['id_sshkeys'];
223 $this->is_super_user = false;
224 $this->is_logged_in = false;
229 * create() - Create a new user.
231 * @param string The unix username.
232 * @param string The real firstname.
233 * @param string The real lastname.
234 * @param string The first password.
235 * @param string The confirmation password.
236 * @param string The users email address.
237 * @param string The users preferred default language.
238 * @param string The users preferred default timezone.
239 * @param string The users preference for receiving site updates by email.
240 * @param string The users preference for receiving community updates by email.
241 * @param int The ID of the language preference.
242 * @param string The users preferred timezone.
243 * @param string The users Jabber address.
244 * @param int The users Jabber preference.
245 * @param int The users theme_id.
246 * @param string The users unix_box.
247 * @param string The users address.
248 * @param string The users address part 2.
249 * @param string The users phone.
250 * @param string The users fax.
251 * @param string The users title.
252 * @param char(2) The users ISO country_code.
253 * @param bool Whether to send an email or not
254 * @param int The users preference for tooltips
255 * @returns The newly created user ID
258 function create($unix_name, $firstname, $lastname, $password1, $password2, $email,
259 $mail_site, $mail_va, $language_id, $timezone, $jabber_address, $jabber_only, $theme_id,
260 $unix_box = 'shell', $address = '', $address2 = '', $phone = '', $fax = '', $title = '', $ccode = 'US', $send_mail = true, $tooltips = true) {
263 $this->setError(_('You must supply a theme'));
266 if (! forge_get_config('require_unique_email')) {
268 $this->setError(_('You must supply a username'));
273 $this->setError(_('You must supply a first name'));
277 $this->setError(_('You must supply a last name'));
281 $this->setError(_('You must supply a password'));
284 if ($password1 != $password2) {
285 $this->setError(_('Passwords do not match'));
288 if (!account_pwvalid($password1)) {
289 $this->setError(_('Invalid Password:'));
292 $unix_name=strtolower($unix_name);
293 if (!account_namevalid($unix_name)) {
294 $this->setError(_('Invalid Unix Name.'));
297 if (!$SYS->sysUseUnixName($unix_name)) {
298 $this->setError(_('Unix name already taken'));
301 if (!validate_email($email)) {
302 $this->setError(_('Invalid Email Address:') .' '. $email);
305 if ($jabber_address && !validate_email($jabber_address)) {
306 $this->setError(_('Invalid Jabber Address'));
314 if ($unix_name && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name LIKE $1',
315 array($unix_name))) > 0) {
316 $this->setError(_('That username already exists.'));
319 if (forge_get_config('require_unique_email')) {
320 if (user_get_object_by_email('$email')) {
321 $this->setError(_('User with this email already exists - use people search to recover your login.'));
325 if (forge_get_config('require_unique_email') && !$unix_name) {
326 // Let's generate a loginname for the user
327 // ...based on the email address:
328 $email_array = explode ('@', $email, 2) ;
329 $email_u = $email_array [0];
330 $l = preg_replace('/[^a-z0-9]/', '', $email_u);
331 $l = substr ($l, 0, 15);
332 // Is the user part of the email address okay?
333 if (account_namevalid($l)
334 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
338 // No? What if we add a number at the end?
341 $c = substr ($l, 0, 15-strlen ("$i")) . "$i" ;
342 if (account_namevalid($c)
343 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
351 // If we're really unlucky, then let's go brute-force
352 while (!$unix_name) {
353 $c = substr (md5($email . util_randbytes()), 0, 15);
354 if (account_namevalid($c)
355 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
361 $unix_name = strtolower($unix_name);
362 if (!account_namevalid($unix_name)) {
363 $this->setError(_('Invalid Unix Name.'));
366 $shell = account_get_user_default_shell();
367 // if we got this far, it must be good
368 $confirm_hash = substr(md5($password1 . util_randbytes() . microtime()),0,16);
370 $result = db_query_params('INSERT INTO users (user_name,user_pw,unix_pw,realname,firstname,lastname,email,add_date,status,confirm_hash,mail_siteupdates,mail_va,language,timezone,jabber_address,jabber_only,unix_box,address,address2,phone,fax,title,ccode,theme_id,tooltips,shell)
371 VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26)',
374 account_genunixpw($password1),
375 htmlspecialchars($firstname.' '.$lastname),
376 htmlspecialchars($firstname),
377 htmlspecialchars($lastname),
382 (($mail_site)?"1":"0"),
383 (($mail_va)?"1":"0"),
389 htmlspecialchars($address),
390 htmlspecialchars($address2),
391 htmlspecialchars($phone),
392 htmlspecialchars($fax),
393 htmlspecialchars($title),
399 $this->setError(_('Insert Failed: ') . db_error());
404 $id = db_insertid($result, 'users', 'user_id');
406 $this->setError('Could Not Get USERID: ' .db_error());
411 if (!$this->fetchData($id)) {
416 $hook_params = array();
417 $hook_params['user'] = $this;
418 $hook_params['user_id'] = $this->getID();
419 $hook_params['user_name'] = $unix_name;
420 $hook_params['user_password'] = $password1;
421 plugin_hook("user_create", $hook_params);
424 setup_gettext_from_lang_id($language_id);
425 $this->sendRegistrationEmail();
426 setup_gettext_from_context();
435 * sendRegistrationEmail() - Send email for registration verification
437 * @return bool success or not
439 function sendRegistrationEmail() {
440 $message=stripcslashes(sprintf(_('Thank you for registering on the %3$s web site. You have
441 account with username %1$s created for you. In order
442 to complete your registration, visit the following url:
446 You have 1 week to confirm your account. After this time, your account will be deleted.
448 (If you don\'t see any URL above, it is likely due to a bug in your mail client.
449 Use one below, but make sure it is entered as the single line.)
457 $this->getUnixName(),
458 util_make_url('/account/verify.php?confirm_hash=_'.$this->getConfirmHash()),
459 forge_get_config('forge_name')));
462 sprintf(_('%1$s Account Registration'), forge_get_config('forge_name')),
468 * delete() - remove the User from all his groups.
470 * Remove the User from all his groups and set his status to D.
472 * @param boolean Confirmation of deletion.
473 * @return boolean success or not
475 function delete($sure) {
479 $groups = &$this->getGroups();
480 if (is_array($groups)) {
481 foreach ($groups as $group) {
482 $group->removeUser($this->getID());
487 $res = db_query_params('DELETE FROM artifact_monitor WHERE user_id=$1',
488 array($this->getID()));
490 $this->setError('ERROR - ' . _('Could Not Delete From artifact_monitor:') . ' '.db_error());
494 $res = db_query_params('DELETE FROM artifact_type_monitor WHERE user_id=$1',
495 array($this->getID()));
497 $this->setError('ERROR - ' . _('Could Not Delete From artifact_type_monitor:') . ' ' .db_error());
501 $res = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
502 array($this->getID()));
504 $this->setError('ERROR - ' . _('Could Not Delete From forum_monitored_forums:') . ' '.db_error());
508 $res = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
509 array($this->getID()));
511 $this->setError('ERROR - ' . _('Could Not Delete From filemodule_monitor:') . ' '.db_error());
516 $hook_params = array ();
517 $hook_params['user'] = $this;
518 $hook_params['user_id'] = $this->getID();
519 plugin_hook("user_delete", $hook_params);
521 $this->setStatus('D');
528 * update() - update *common* properties of GFUser object.
530 * Use specific setter to change other properties.
532 * @param string The users first name.
533 * @param string The users last name.
534 * @param int The ID of the users language preference.
535 * @param string The useres timezone preference.
536 * @param string The users preference for receiving site updates by email.
537 * @param string The users preference for receiving community updates by email.
538 * @param string The users preference for being participating in "peer ratings".
539 * @param string The users Jabber account address.
540 * @param int The users Jabber preference.
541 * @param int The users theme_id preference.
542 * @param string The users address.
543 * @param string The users address2.
544 * @param string The users phone.
545 * @param string The users fax.
546 * @param string The users title.
547 * @param string The users ccode.
548 * @param int The users preference for tooltips.
549 * @param string The users email.
551 function update($firstname, $lastname, $language_id, $timezone, $mail_site, $mail_va, $use_ratings,
552 $jabber_address, $jabber_only, $theme_id, $address, $address2, $phone, $fax, $title, $ccode, $tooltips, $email='') {
553 $mail_site = $mail_site ? 1 : 0;
554 $mail_va = $mail_va ? 1 : 0;
555 $block_ratings = $use_ratings ? 0 : 1;
557 if ($jabber_address && !validate_email($jabber_address)) {
558 $this->setError(_('Invalid Jabber Address'));
569 $res = db_query_params('
592 htmlspecialchars($firstname . ' ' .$lastname),
593 htmlspecialchars($firstname),
594 htmlspecialchars($lastname),
602 htmlspecialchars($address),
603 htmlspecialchars($address2),
604 htmlspecialchars($phone),
605 htmlspecialchars($fax),
606 htmlspecialchars($title),
613 $this->setError(_('ERROR - Could Not Update User Object:'). ' ' .db_error());
618 if ($email && $email != $this->getEmail()
619 && !$this->setEmail($email)) {
623 // If there's a transaction from using to not
624 // using ratings, remove all rating made by the
625 // user (ratings by others should not be removed,
626 // as it opens possibility to abuse rate system)
627 if (!$use_ratings && $this->usesRatings()) {
628 db_query_params('DELETE FROM user_ratings WHERE rated_by=$1',
631 if (!$this->fetchData($this->getID())) {
636 $hook_params = array ();
637 $hook_params['user'] = $this;
638 $hook_params['user_id'] = $this->getID();
639 plugin_hook ("user_update", $hook_params);
646 * fetchData - May need to refresh database fields.
648 * If an update occurred and you need to access the updated info.
650 * @param int the User ID data to be fecthed
651 * @return boolean success;
653 function fetchData($user_id) {
654 $res = db_query_params ('SELECT * FROM users WHERE user_id=$1',
656 if (!$res || db_numrows($res) < 1) {
657 $this->setError('GFUser::fetchData():: '.db_error());
660 $this->data_array = db_fetch_array($res);
665 * getID - Simply return the user_id for this object.
667 * @return int This user's user_id number.
670 return $this->data_array['user_id'];
674 * getStatus - get the status of this user.
676 * Statuses include (A)ctive, (P)ending, (S)uspended ,(D)eleted.
678 * @return char This user's status flag.
680 function getStatus() {
681 return $this->data_array['status'];
685 * setStatus - set this user's status.
687 * @param string Status - P, A, S, or D.
688 * @return boolean success.
690 function setStatus($status) {
692 if ($status != 'P' && $status != 'A'
693 && $status != 'S' && $status != 'D') {
694 $this->setError(_('ERROR: Invalid status value'));
697 if ($this->getStatus() != 'P' && $status == 'P') {
698 $this->setError('ERROR: You can\'t set pending status if user is suspend or active');
703 $res = db_query_params ('UPDATE users SET status=$1 WHERE user_id=$2',
708 $this->setError(_('ERROR - Could Not Update User Status:') . ' ' .db_error());
712 $this->data_array['status']=$status;
713 if ($status == 'D') {
714 $projects = $this->getGroups() ;
715 foreach ($projects as $p) {
716 $p->removeUser ($this->getID()) ;
720 $hook_params = array ();
721 $hook_params['user'] = $this;
722 $hook_params['user_id'] = $this->getID();
723 $hook_params['status'] = $status;
724 plugin_hook ("user_setstatus", $hook_params);
733 * isActive - whether this user is confirmed and active.
735 * Database field status of 'A' returns true.
736 * @return boolean is_active.
738 function isActive() {
739 if ($this->getStatus()=='A') {
747 * getUnixStatus - Status of activation of unix account.
749 * @return char (N)one, (A)ctive, (S)uspended or (D)eleted
751 function getUnixStatus() {
752 return $this->data_array['unix_status'];
756 * setUnixStatus - Sets status of activation of unix account.
758 * @param string The unix status.
764 * @return boolean success.
766 function setUnixStatus($status) {
769 $res = db_query_params ('UPDATE users SET unix_status=$1 WHERE user_id=$2',
774 $this->setError('ERROR - Could Not Update User Unix Status: '.db_error());
778 if ($status == 'A') {
779 if (!$SYS->sysCheckCreateUser($this->getID())) {
780 $this->setError($SYS->getErrorMessage());
785 if ($SYS->sysCheckUser($this->getID())) {
786 if (!$SYS->sysRemoveUser($this->getID())) {
787 $this->setError($SYS->getErrorMessage());
794 $this->data_array['unix_status']=$status;
801 * getUnixName - the user's unix_name.
803 * @return string This user's unix/login name.
805 function getUnixName() {
806 return strtolower($this->data_array['user_name']);
810 * getUnixPasswd - get the user's password.
812 * @return string This user's unix crypted passwd.
814 function getUnixPasswd() {
815 return $this->data_array['unix_pw'];
819 * getUnixBox - the hostname of the unix box this user has an account on.
821 * @return string This user's shell login machine.
823 function getUnixBox() {
824 return $this->data_array['unix_box'];
828 * getMD5Passwd - the password.
830 * @return string This user's MD5-crypted passwd.
832 function getMD5Passwd() {
833 return $this->data_array['user_pw'];
836 //Added to be compatible with codendi getUserPw function
837 function getUserPw() {
838 return $this->data_array['user_pw'];
842 * getConfirmHash - the confirm hash in the db.
844 * @return string This user's confirmation hash.
846 function getConfirmHash() {
847 return $this->data_array['confirm_hash'];
851 * getEmail - the user's email address.
853 * @return string This user's email address.
855 function getEmail() {
856 return str_replace("\n", "", $this->data_array['email']);
860 * getSha1Email - a SHA1 encoded hash of the email URI (including mailto: prefix)
862 * @return string The SHA1 encoded value for the email
864 function getSha1Email() {
865 return sha1('mailto:'.$this->getEmail());
869 * getNewEmail - while changing an email address, it is stored here until confirmation.
871 * getNewEmail is a private operation for email change.
873 * @return string This user's new (not yet confirmed) email address.
876 function getNewEmail() {
877 return $this->data_array['email_new'];
881 * setEmail - set a new email address, which must be confirmed.
883 * @param string The email address.
884 * @return boolean success.
886 function setEmail($email) {
888 if (!strcasecmp($this->getEmail(), $email)) {
892 if (!$email || !validate_email($email)) {
893 $this->setError('ERROR: Invalid Email');
897 if (forge_get_config('require_unique_email')) {
898 if (db_numrows(db_query_params('SELECT user_id FROM users WHERE user_id!=$1 AND (lower(email) LIKE $2 OR lower(email_new) LIKE $2)',
899 array ($this->getID(),
900 strtolower($email)))) > 0) {
901 $this->setError(_('User with this email already exists.'));
907 $res = db_query_params ('UPDATE users SET email=$1 WHERE user_id=$2',
912 $this->setError('ERROR - Could Not Update User Email: '.db_error());
916 $hook_params = array ();
917 $hook_params['user'] = $this;
918 $hook_params['user_id'] = $this->getID();
919 $hook_params['user_email'] = $email;
920 plugin_hook("user_setemail", $hook_params);
922 if (!$this->fetchData($this->getId())) {
933 * setNewEmailAndHash - setNewEmailAndHash is a private operation for email change.
935 * @param string The email address.
936 * @param string The email hash.
937 * @return boolean success.
939 function setNewEmailAndHash($email, $hash='') {
942 $hash = substr(md5(strval(time()) . strval(util_randbytes())), 0, 16);
945 if (!$email || !validate_email($email)) {
946 $this->setError('ERROR - Invalid Email');
950 if (forge_get_config('require_unique_email')) {
951 if (db_numrows(db_query_params('SELECT user_id FROM users WHERE user_id!=$1 AND (lower(email) LIKE $2 OR lower(email_new) LIKE $2)',
952 array ($this->getID(),
953 strtolower($email)))) > 0) {
954 $this->setError(_('User with this email already exists.'));
958 $res = db_query_params ('UPDATE users SET confirm_hash=$1, email_new=$2 WHERE user_id=$3',
963 $this->setError('ERROR - Could Not Update User Email And Hash: '.db_error());
966 $this->data_array['email_new'] = $email;
967 $this->data_array['confirm_hash'] = $hash;
973 * getRealName - get the user's real name.
975 * @return string This user's real name.
977 function getRealName() {
978 return $this->data_array['realname'];
982 * setRealName - set the user's real name.
984 * @return string boolean.
986 function setRealName($realname) {
987 $res=db_query_params('UPDATE users SET realname=$1 WHERE user_id=$2',
988 array($realname, $this->getID()));
989 if (!$res || db_affected_rows($res) < 1) {
990 $this->setError('ERROR - Could Not Update real name of user : '.db_error());
993 $this->data_array['realname'] = $realname;
998 * getFirstName - get the user's first name.
1000 * @return string This user's first name.
1002 function getFirstName() {
1003 return $this->data_array['firstname'];
1007 * getLastName - get the user's last name.
1009 * @return string This user's last name.
1011 function getLastName() {
1012 return $this->data_array['lastname'];
1016 * getAddDate - this user's unix time when account was opened.
1018 * @return int This user's unix time when account was opened.
1020 function getAddDate() {
1021 return $this->data_array['add_date'];
1025 * getTimeZone - this user's timezone setting.
1027 * @return string This user's timezone setting.
1029 function getTimeZone() {
1030 return $this->data_array['timezone'];
1034 * getCountryCode - this user's ccode setting.
1036 * @return string This user's ccode setting.
1038 function getCountryCode() {
1039 return $this->data_array['ccode'];
1043 * getShell - this user's preferred shell.
1045 * @return string This user's preferred shell.
1047 function getShell() {
1048 return $this->data_array['shell'];
1052 * setShell - sets user's preferred shell.
1054 * @param string The users preferred shell.
1055 * @return boolean success.
1057 function setShell($shell) {
1060 $shells = account_getavailableshells();
1062 if (!in_array($shell, $shells)) {
1063 $this->setError( sprintf(_('ERROR: Invalid Shell %s'), $shell) );
1068 $res = db_query_params ('UPDATE users SET shell=$1 WHERE user_id=$2',
1072 $this->setError(_('ERROR - Could Not Update User Unix Shell:') . ' ' .db_error());
1076 // Now change LDAP attribute, but only if corresponding
1077 // entry exists (i.e. if user have shell access)
1078 if ($SYS->sysCheckUser($this->getID()))
1080 if (!$SYS->sysUserSetAttribute($this->getID(),"loginShell",$shell)) {
1081 $this->setError($SYS->getErrorMessage());
1086 $this->data_array['shell']=$shell;
1093 * getUnixUID() - Get the unix UID of the user
1095 * @return int This user's UID.
1097 function getUnixUID() {
1098 return $this->data_array['unix_uid'];
1102 * getUnixGID() - Get the unix GID of the user
1104 * @return int This user's GID.
1106 function getUnixGID() {
1107 return $this->data_array['unix_gid'];
1111 * getLanguage - this user's language_id from supported_languages table.
1113 * @return int This user's language_id.
1115 function getLanguage() {
1116 return $this->data_array['language'];
1120 * getJabberAddress - this user's optional jabber address.
1122 * @return string This user's jabber address.
1124 function getJabberAddress() {
1125 return $this->data_array['jabber_address'];
1129 * getJabberOnly - whether this person wants updates sent ONLY to jabber.
1131 * @return boolean This user's jabber preference.
1133 function getJabberOnly() {
1134 return $this->data_array['jabber_only'];
1138 * getAddress - get this user's address.
1140 * @return text This user's address.
1142 function getAddress() {
1143 return $this->data_array['address'];
1147 * getAddress2 - get this user's address2.
1149 * @return text This user's address2.
1151 function getAddress2() {
1152 return $this->data_array['address2'];
1156 * getPhone - get this person's phone number.
1158 * @return text This user's phone number.
1160 function getPhone() {
1161 return $this->data_array['phone'];
1165 * getFax - get this person's fax number.
1167 * @return text This user's fax.
1170 return $this->data_array['fax'];
1174 * getTitle - get this person's title.
1176 * @return text This user's title.
1178 function getTitle() {
1179 return $this->data_array['title'];
1183 * getGroups - get an array of groups this user is a member of.
1185 * @return array Array of groups.
1187 function &getGroups($onlylocal = true) {
1189 foreach ($this->getRoles() as $r) {
1191 if ($r instanceof RoleExplicit
1192 && $r->getHomeProject() != NULL) {
1193 $ids[] = $r->getHomeProject()->getID();
1196 foreach ($r->getLinkedProjects() as $p) {
1197 $ids[] = $p->getID();
1201 return group_get_objects(array_values(array_unique($ids))) ;
1205 * getAuthorizedKeys - the SSH authorized keys set by the user.
1207 * @return string This user's SSH authorized (public) keys.
1209 function getAuthorizedKeys() {
1210 return $this->data_array['authorized_keys'];
1214 * addAuthorizedKey - add the SSH authorized key for the user.
1216 * @param string The user public key.
1217 * @return boolean success.
1219 function addAuthorizedKey($key) {
1221 $key = preg_replace("/\r\n/", "\n", $key); // Convert to Unix EOL
1222 $key = preg_replace("/\n+/", "\n", $key); // Remove empty lines
1223 $tempfile = tempnam("/tmp", "authkey");
1224 $ft = fopen($tempfile, 'w');
1227 $returnExec = array();
1228 exec("/usr/bin/ssh-keygen -lf ".$tempfile, $returnExec);
1230 $returnExecExploded = explode(' ', $returnExec[0]);
1231 $fingerprint = $returnExecExploded[1];
1233 $explodedKey = explode(' ', $key);
1234 $res = db_query_params('insert into sshkeys (userid, fingerprint, upload, sshkey, name, algorithm)
1235 values ($1, $2, $3, $4, $5, $6)',
1236 array($this->getID(), $fingerprint, $now, $key, $explodedKey[2], $explodedKey[0]));
1238 $this->setError(_('ERROR - Could Not Add User SSH Key:').db_error());
1241 $keyid = db_insertid($res, 'sshkeys', 'id_sshkeys');
1242 $this->data_array['authorized_keys'][$keyid]['fingerprint'] = $fingerprint;
1243 $this->data_array['authorized_keys'][$keyid]['upload'] = $now;
1244 $this->data_array['authorized_keys'][$keyid]['sshkey'] = $key;
1245 $this->data_array['authorized_keys'][$keyid]['deploy'] = 0;
1246 $this->data_array['authorized_keys'][$keyid]['keyid'] = $keyid;
1251 function deleteAuthorizedKey($keyid) {
1252 $res = db_query_params('update sshkeys set deleted = 1 where id_sshkeys =$1 and userid = $2',
1253 array($keyid, $this->getID()));
1255 $this->setError(_('ERROR - Could Not Delete User SSH Key:').db_error());
1258 unset($this->data_array['authorized_keys'][$keyid]);
1264 * setLoggedIn($val) - Really only used by session code.
1266 * @param boolean The session value.
1268 function setLoggedIn($val=true) {
1269 $this->is_logged_in = $val;
1272 $this->is_super_user = forge_check_global_perm_for_user($this, 'forge_admin') ;
1277 * isLoggedIn - only used by session code.
1279 * @return boolean is_logged_in.
1281 function isLoggedIn() {
1282 return $this->is_logged_in;
1286 * deletePreference - delete a preference for this user.
1288 * @param string The unique field name for this preference.
1289 * @return boolean success.
1291 function deletePreference($preference_name) {
1292 $preference_name=strtolower(trim($preference_name));
1293 unset($this->user_pref["$preference_name"]);
1294 $res = db_query_params('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1295 array ($this->getID(),
1297 return ((!$res || db_affected_rows($res) < 1) ? false : true);
1301 * setPreference - set a new preference for this user.
1303 * @param string The unique field name for this preference.
1304 * @param string The value you are setting this preference to.
1305 * @return boolean success.
1307 function setPreference($preference_name,$value) {
1308 $preference_name=strtolower(trim($preference_name));
1309 //delete pref if not value passed in
1310 unset($this->user_pref);
1311 if (!isset($value)) {
1312 $result = db_query_params ('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1313 array ($this->getID(),
1314 $preference_name)) ;
1316 $result = db_query_params ('UPDATE user_preferences SET preference_value=$1,set_date=$2 WHERE user_id=$3 AND preference_name=$4',
1320 $preference_name)) ;
1321 if (db_affected_rows($result) < 1) {
1323 $result = db_query_params ('INSERT INTO user_preferences (user_id,preference_name,preference_value,set_date) VALUES ($1,$2,$3,$4)',
1324 array ($this->getID(),
1330 return ((!$result || db_affected_rows($result) < 1) ? false : true);
1334 * getPreference - get a specific preference.
1336 * @param string The unique field name for this preference.
1337 * @return string|bool the preference string or false on failure.
1339 function getPreference($preference_name) {
1340 $preference_name=strtolower(trim($preference_name));
1342 First check to see if we have already fetched the preferences
1344 if (isset($this->user_pref)) {
1345 //echo "\n\nPrefs were fetched already";
1346 if (isset($this->user_pref["$preference_name"])) {
1347 //we have fetched prefs - return part of array
1348 return $this->user_pref["$preference_name"];
1350 //we have fetched prefs, but this pref hasn't been set
1354 //we haven't returned prefs - go to the db
1355 $result = db_query_params ('SELECT preference_name,preference_value FROM user_preferences WHERE user_id=$1',
1356 array ($this->getID())) ;
1357 if (db_numrows($result) < 1) {
1358 //echo "\n\nNo Prefs Found";
1362 //iterate and put the results into an array
1363 for ($i=0; $i<db_numrows($result); $i++) {
1364 $pref["".db_result($result,$i,'preference_name').""]=db_result($result,$i,'preference_value');
1366 $this->user_pref = $pref;
1368 if (array_key_exists($preference_name,$this->user_pref)) {
1369 //we have fetched prefs - return part of array
1370 return $this->user_pref["$preference_name"];
1372 //we have fetched prefs, but this pref hasn't been set
1380 * setPasswd - Changes user's password.
1382 * @param string The plaintext password.
1383 * @return boolean success.
1385 function setPasswd($passwd) {
1387 if (!account_pwvalid($passwd)) {
1388 $this->setError('Error: '.$GLOBALS['register_error']);
1393 $md5_pw = md5 ($passwd) ;
1394 $unix_pw = account_genunixpw ($passwd) ;
1396 $res = db_query_params ('UPDATE users SET user_pw=$1, unix_pw=$2 WHERE user_id=$3',
1401 if (!$res || db_affected_rows($res) < 1) {
1402 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1406 // Now change LDAP password, but only if corresponding
1407 // entry exists (i.e. if user have shell access)
1408 if ($SYS->sysCheckUser($this->getID())) {
1409 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix_pw)) {
1410 $this->setError($SYS->getErrorMessage());
1416 $hook_params = array ();
1417 $hook_params['user'] = $this;
1418 $hook_params['user_id'] = $this->getID();
1419 $hook_params['user_password'] = $passwd;
1420 plugin_hook ("user_setpasswd", $hook_params);
1426 * setMD5Passwd - Changes user's MD5 password.
1428 * @param string The MD5-hashed password.
1429 * @return boolean success.
1431 function setMD5Passwd($md5) {
1437 $res = db_query_params('UPDATE users SET user_pw=$1 WHERE user_id=$2',
1441 if (!$res || db_affected_rows($res) < 1) {
1442 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1452 * setUnixPasswd - Changes user's Unix-hashed password.
1454 * @param string The Unix-hashed password.
1455 * @return boolean success.
1457 function setUnixPasswd($unix) {
1463 $res = db_query_params('UPDATE users SET unix_pw=$1 WHERE user_id=$1',
1467 if (!$res || db_affected_rows($res) < 1) {
1468 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1473 // Now change system password, but only if corresponding
1474 // entry exists (i.e. if user have shell access)
1475 if ($SYS->sysCheckUser($this->getID())) {
1476 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix)) {
1477 $this->setError($SYS->getErrorMessage());
1488 * usesRatings - whether user participates in rating system.
1490 * @return boolean success.
1492 function usesRatings() {
1493 return !$this->data_array['block_ratings'];
1497 * usesTooltips - whether user enables or not tooltips.
1499 * @return boolean success.
1501 function usesTooltips() {
1502 return $this->data_array['tooltips'];
1506 * getPlugins - get a list of all available user plugins
1508 * @return array array containing plugin_id => plugin_name
1510 function getPlugins() {
1511 if (!isset($this->plugins_data)) {
1512 $this->plugins_data = array () ;
1513 $res = db_query_params ('SELECT user_plugin.plugin_id, plugins.plugin_name
1514 FROM user_plugin, plugins
1515 WHERE user_plugin.user_id=$1
1516 AND user_plugin.plugin_id=plugins.plugin_id',
1517 array ($this->getID())) ;
1518 $rows = db_numrows($res);
1520 for ($i=0; $i<$rows; $i++) {
1521 $plugin_id = db_result($res,$i,'plugin_id');
1522 $this->plugins_data[$plugin_id] = db_result($res,$i,'plugin_name');
1525 return $this->plugins_data ;
1529 * usesPlugin - returns true if the user uses a particular plugin
1531 * @param string name of the plugin
1532 * @return boolean whether plugin is being used or not
1534 function usesPlugin($pluginname) {
1535 $plugins_data = $this->getPlugins() ;
1536 foreach ($plugins_data as $p_name) {
1537 if ($p_name == $pluginname) {
1545 * setPluginUse - enables/disables plugins for the user
1547 * @param string name of the plugin
1548 * @param boolean the new state
1549 * @return string database result
1551 function setPluginUse($pluginname, $val=true) {
1552 if ($val == $this->usesPlugin($pluginname)) {
1553 // State is already good, returning
1556 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1557 array($pluginname));
1558 $rows = db_numrows($res);
1560 // Error: no plugin by that name
1563 $plugin_id = db_result($res,0,'plugin_id');
1565 unset ($this->plugins_data);
1567 return db_query_params('INSERT INTO user_plugin (user_id,plugin_id) VALUES ($1,$2)',
1568 array($this->getID(),
1571 return db_query_params('DELETE FROM user_plugin WHERE user_id=$1 AND plugin_id=$2',
1572 array($this->getID(),
1578 * getMailingsPrefs - Get activity status for one of the site mailings.
1580 * @param string The id of mailing ('mail_va' for community mailings, 'mail_siteupdates' for site mailings)
1581 * @return boolean success.
1583 function getMailingsPrefs($mailing_id) {
1584 if ($mailing_id == 'va') {
1585 return $this->data_array['mail_va'];
1586 } else if ($mailing_id == 'site') {
1587 return $this->data_array['mail_siteupdates'];
1594 * unsubscribeFromMailings - Disable email notifications for user.
1596 * @param boolean If false, disable general site mailings, else - all.
1597 * @return boolean success.
1599 function unsubscribeFromMailings($all = false) {
1600 $res1 = $res2 = $res3 = true;
1601 $res1 = db_query_params ('UPDATE users SET mail_siteupdates=0, mail_va=0 WHERE user_id=$1',
1602 array ($this->getID())) ;
1604 $res2 = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
1605 array ($this->getID())) ;
1606 $res3 = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
1607 array ($this->getID())) ;
1610 return $res1 && $res2 && $res3;
1614 * getThemeID - get the theme_id for this user.
1616 * @return int The theme_id.
1618 function getThemeID() {
1619 return $this->data_array['theme_id'];
1623 * setUpTheme - get the theme path
1625 * @return string The theme path.
1627 function setUpTheme() {
1629 // An optimization in session_getdata lets us pre-fetch this in most cases.....
1631 if (!isset($this->data_array['dirname']) || !$this->data_array['dirname']) {
1632 $res = db_query_params ('SELECT dirname FROM themes WHERE theme_id=$1',
1633 array ($this->getThemeID())) ;
1634 $this->theme=db_result($res,0,'dirname');
1636 $this->theme=$this->data_array['dirname'];
1638 if (is_file(forge_get_config('themes_root').'/'.$this->theme.'/Theme.class.php')) {
1639 $GLOBALS['sys_theme']=$this->theme;
1641 $this->theme=forge_get_config('default_theme');
1643 return $this->theme;
1647 * getRole() - Get user Role object.
1649 * @param object group object
1650 * @return object Role object
1652 function getRole(&$g) {
1653 if (is_int ($g) || is_string($g)) {
1656 $group_id = $g->getID();
1658 foreach ($this->getRoles () as $r) {
1659 if ($r instanceof RoleExplicit ) {
1660 $homeproj = $r->getHomeProject();
1662 if ($homeproj->getID() == $group_id) {
1671 function getRoles() {
1672 return RBACEngine::getInstance()->getAvailableRolesForUser($this);
1676 function isMember($g, $type = 0){
1677 if (is_int ($g) || is_string($g)) {
1678 $group = group_get_object ($g) ;
1682 $group_id = $group->getID() ;
1688 foreach ($this->getGroups() as $p) {
1689 if ($p->getID() == $group_id) {
1697 return forge_check_perm_for_user($this, 'pm_admin', $group_id);
1701 return forge_check_perm_for_user($this, 'forum_admin', $group_id);
1704 //admin for this group
1705 return forge_check_perm_for_user($this, 'project_admin', $group_id);
1709 return forge_check_perm_for_user($this, 'docman', $group_id, 'admin');
1715 * setAdminNotification - send an email to all admins (used in verify.php)
1717 * @return boolean True
1719 function setAdminNotification() {
1720 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('forge_admin', -1);
1721 foreach ($admins as $admin) {
1722 $admin_email = $admin->getEmail();
1723 setup_gettext_for_user($admin);
1724 $message = sprintf(_('New User %1$s registered and validated
1728 $this->getUnixName() , $this->getRealName(), $this->getEmail());
1729 util_send_message($admin_email, sprintf(_('New %1$s User'), forge_get_config ('forge_name')), $message);
1730 setup_gettext_from_context();
1741 EVERYTHING BELOW HERE IS DEPRECATED
1744 DO NOT USE FOR ANY NEW CODE
1753 * user_ismember() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1754 * Replace user_ismember(1[, 'A']) with forge_check_global_perm('forge_admin')
1755 * Replace user_ismember($group_id, 'A') with forge_check_perm('project_admin', $group_id)
1756 * For now, keep user_ismember($group_id) alone
1757 * @param int The Group ID
1758 * @param int The Type
1762 function user_ismember($group_id,$type=0) {
1763 if (!session_loggedin()) {
1767 return session_get_user()->isMember($group_id, $type) ;
1771 * user_getname() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1773 * @param int The User ID
1777 function user_getname($user_id = false) {
1778 // use current user if one is not passed in
1780 if (session_loggedin()) {
1781 $user=&user_get_object(user_getid());
1783 return $user->getUnixName();
1785 return 'Error getting user';
1788 return 'No User Id';
1791 $user=&user_get_object($user_id);
1793 return $user->getUnixName();
1795 return 'Invalid User';
1800 class UserComparator {
1801 var $criterion = 'name' ;
1803 function Compare ($a, $b) {
1804 switch ($this->criterion) {
1807 $namecmp = strcoll ($a->getRealName(), $b->getRealName()) ;
1808 if ($namecmp != 0) {
1811 /* If several projects share a same real name */
1812 return strcoll ($a->getUnixName(), $b->getUnixName()) ;
1815 return strcmp ($a->getUnixName(), $b->getUnixName()) ;
1818 $aid = $a->getID() ;
1819 $bid = $b->getID() ;
1823 return ($a < $b) ? -1 : 1;
1829 function sortUserList (&$list, $criterion='name') {
1830 $cmp = new UserComparator () ;
1831 $cmp->criterion = $criterion ;
1833 return usort ($list, array ($cmp, 'Compare')) ;
1838 // c-file-style: "bsd"