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 * http://fusionforge.org
10 * This file is part of FusionForge. FusionForge is free software;
11 * you can redistribute it and/or modify it under the terms of the
12 * GNU General Public License as published by the Free Software
13 * Foundation; either version 2 of the Licence, or (at your option)
16 * FusionForge is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 * user_get_object_by_name() - Get User object by username.
30 * user_get_object is useful so you can pool user objects/save database queries
31 * You should always use this instead of instantiating the object directly
33 * @param string The unix username - required
34 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
35 * @return a user object or false on failure
37 function &user_get_object_by_name($user_name, $res = false) {
38 $user_name = strtolower($user_name);
40 $res = db_query_params('SELECT * FROM users WHERE user_name=$1',
43 return user_get_object(db_result($res, 0, 'user_id'), $res);
47 * user_get_object_by_email() - Get User object by email address
48 * Only works if sys_require_unique_email is true
50 * @param string The unix username - required
51 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
52 * @return a user object or false on failure
55 function user_get_object_by_email($email ,$res = false) {
56 if (!validate_email($email)
57 || !forge_get_config('require_unique_email')) {
61 $res=db_query_params('SELECT * FROM users WHERE email=$1',
64 return user_get_object(db_result($res, 0, 'user_id'), $res);
68 * user_get_object() - Get User object by user ID.
69 * user_get_object is useful so you can pool user objects/save database queries
70 * You should always use this instead of instantiating the object directly
72 * @param int The ID of the user - required
73 * @param int The result set handle ("SELECT * FROM USERS WHERE user_id=xx")
74 * @return object a user object or false on failure
76 function &user_get_object($user_id, $res = false) {
77 //create a common set of group objects
78 //saves a little wear on the database
80 //automatically checks group_type and
81 //returns appropriate object
84 if (!isset($USER_OBJ["_".$user_id."_"])) {
86 //the db result handle was passed in
88 $res = db_query_params('SELECT * FROM users WHERE user_id=$1',
91 if (!$res || db_numrows($res) < 1) {
92 $USER_OBJ["_".$user_id."_"]=false;
94 $USER_OBJ["_".$user_id."_"]= new GFUser($user_id,$res);
97 return $USER_OBJ["_".$user_id."_"];
100 function &user_get_objects($id_arr) {
105 foreach ($id_arr as $id) {
107 // See if this ID already has been fetched in the cache
109 if (!isset($USER_OBJ["_".$id."_"])) {
113 if (count($fetch) > 0) {
114 $res = db_query_params('SELECT * FROM users WHERE user_id = ANY ($1)',
115 array(db_int_array_to_any_clause ($fetch)));
116 while ($arr = db_fetch_array($res)) {
117 $USER_OBJ["_".$arr['user_id']."_"] = new GFUser($arr['user_id'],$arr);
120 foreach ($id_arr as $id) {
121 $return[] =& $USER_OBJ["_".$id."_"];
126 function &user_get_objects_by_name($username_arr) {
127 $res = db_query_params('SELECT user_id FROM users WHERE lower(user_name) = ANY ($1)',
128 array(db_string_array_to_any_clause ($username_arr)));
129 $arr =& util_result_column_to_array($res, 0);
130 return user_get_objects($arr);
133 function &user_get_objects_by_email($email_arr) {
134 $res=db_query_params('SELECT user_id FROM users WHERE lower(email) = ANY ($1)',
135 array(db_string_array_to_any_clause ($email_arr)));
136 $arr =& util_result_column_to_array($res, 0);
137 return user_get_objects($arr);
140 function &user_get_active_users() {
141 $res=db_query_params('SELECT user_id FROM users WHERE status=$1',
143 return user_get_objects(util_result_column_to_array($res, 0));
146 class GFUser extends Error {
148 * Associative array of data from db.
150 * @var array $data_array.
155 * Is this person a site super-admin?
157 * @var bool $is_super_user
162 * Is this person the logged in user?
164 * @var bool $is_logged_in
169 * Array of preferences
171 * @var array $user_pref
179 * GFUser($id,$res) - CONSTRUCTOR - GENERALLY DON'T USE THIS
181 * instead use the user_get_object() function call
183 * @param int The user_id
184 * @param int The database result set OR array of data
186 function GFUser($id = false, $res = false) {
189 //setting up an empty object
190 //probably going to call create()
194 $this->fetchData($id);
196 if (is_array($res)) {
197 $this->data_array =& $res;
198 } elseif (db_numrows($res) < 1) {
199 //function in class we extended
200 $this->setError(_('User Not Found'));
201 $this->data_array=array();
204 //set up an associative array for use by other functions
205 $this->data_array = db_fetch_array_by_row($res, 0);
208 $this->is_super_user=false;
209 $this->is_logged_in=false;
214 * create() - Create a new user.
216 * @param string The unix username.
217 * @param string The real firstname.
218 * @param string The real lastname.
219 * @param string The first password.
220 * @param string The confirmation password.
221 * @param string The users email address.
222 * @param string The users preferred default language.
223 * @param string The users preferred default timezone.
224 * @param string The users preference for receiving site updates by email.
225 * @param string The users preference for receiving community updates by email.
226 * @param int The ID of the language preference.
227 * @param string The users preferred timezone.
228 * @param string The users Jabber address.
229 * @param int The users Jabber preference.
230 * @param int The users theme_id.
231 * @param string The users unix_box.
232 * @param string The users address.
233 * @param string The users address part 2.
234 * @param string The users phone.
235 * @param string The users fax.
236 * @param string The users title.
237 * @param char(2) The users ISO country_code.
238 * @param bool Whether to send an email or not
239 * @param int The users preference for tooltips
240 * @returns The newly created user ID
243 function create($unix_name, $firstname, $lastname, $password1, $password2, $email,
244 $mail_site, $mail_va, $language_id, $timezone, $jabber_address, $jabber_only, $theme_id,
245 $unix_box = 'shell', $address = '', $address2 = '', $phone = '', $fax = '', $title = '', $ccode = 'US', $send_mail = true, $tooltips = true) {
248 $this->setError(_('You must supply a theme'));
251 if (! forge_get_config('require_unique_email')) {
253 $this->setError(_('You must supply a username'));
258 $this->setError(_('You must supply a first name'));
262 $this->setError(_('You must supply a last name'));
266 $this->setError(_('You must supply a password'));
269 if ($password1 != $password2) {
270 $this->setError(_('Passwords do not match'));
273 if (!account_pwvalid($password1)) {
274 $this->setError(_('Invalid Password:'));
277 $unix_name=strtolower($unix_name);
278 if (!account_namevalid($unix_name)) {
279 $this->setError(_('Invalid Unix Name.'));
282 if (!$SYS->sysUseUnixName($unix_name)) {
283 $this->setError(_('Unix name already taken'));
286 if (!validate_email($email)) {
287 $this->setError(_('Invalid Email Address:') .' '. $email);
290 if ($jabber_address && !validate_email($jabber_address)) {
291 $this->setError(_('Invalid Jabber Address'));
299 if ($unix_name && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name LIKE $1',
300 array($unix_name))) > 0) {
301 $this->setError(_('That username already exists.'));
304 if (forge_get_config('require_unique_email')) {
305 if (user_get_object_by_email('$email')) {
306 $this->setError(_('User with this email already exists - use people search to recover your login.'));
310 if (forge_get_config('require_unique_email') && !$unix_name) {
311 // Let's generate a loginname for the user
312 // ...based on the email address:
313 $email_array = explode ('@', $email, 2) ;
314 $email_u = $email_array [0];
315 $l = preg_replace('/[^a-z0-9]/', '', $email_u);
316 $l = substr ($l, 0, 15);
317 // Is the user part of the email address okay?
318 if (account_namevalid($l)
319 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
323 // No? What if we add a number at the end?
326 $c = substr ($l, 0, 15-strlen ("$i")) . "$i" ;
327 if (account_namevalid($c)
328 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
336 // If we're really unlucky, then let's go brute-force
337 while (!$unix_name) {
338 $c = substr (md5($email . util_randbytes()), 0, 15);
339 if (account_namevalid($c)
340 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
346 $unix_name = strtolower($unix_name);
347 if (!account_namevalid($unix_name)) {
348 $this->setError(_('Invalid Unix Name.'));
351 // if we got this far, it must be good
352 $confirm_hash = substr(md5($password1 . util_randbytes() . microtime()),0,16);
354 $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)
355 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)',
358 account_genunixpw($password1),
359 htmlspecialchars($firstname.' '.$lastname),
360 htmlspecialchars($firstname),
361 htmlspecialchars($lastname),
366 (($mail_site)?"1":"0"),
367 (($mail_va)?"1":"0"),
373 htmlspecialchars($address),
374 htmlspecialchars($address2),
375 htmlspecialchars($phone),
376 htmlspecialchars($fax),
377 htmlspecialchars($title),
382 $this->setError(_('Insert Failed: ') . db_error());
387 $id = db_insertid($result, 'users', 'user_id');
389 $this->setError('Could Not Get USERID: ' .db_error());
394 if (!$this->fetchData($id)) {
399 $hook_params = array();
400 $hook_params['user'] = $this;
401 $hook_params['user_id'] = $this->getID();
402 $hook_params['user_name'] = $unix_name;
403 $hook_params['user_password'] = $password1;
404 plugin_hook("user_create", $hook_params);
407 setup_gettext_from_lang_id($language_id);
408 $this->sendRegistrationEmail();
409 setup_gettext_from_context();
418 * sendRegistrationEmail() - Send email for registration verification
420 * @return bool success or not
422 function sendRegistrationEmail() {
423 $message=stripcslashes(sprintf(_('Thank you for registering on the %3$s web site. You have
424 account with username %1$s created for you. In order
425 to complete your registration, visit the following url:
429 You have 1 week to confirm your account. After this time, your account will be deleted.
431 (If you don\'t see any URL above, it is likely due to a bug in your mail client.
432 Use one below, but make sure it is entered as the single line.)
440 $this->getUnixName(),
441 util_make_url('/account/verify.php?confirm_hash=_'.$this->getConfirmHash()),
442 forge_get_config('forge_name')));
445 sprintf(_('%1$s Account Registration'), forge_get_config('forge_name')),
451 * delete() - remove the User from all his groups.
453 * Remove the User from all his groups and set his status to D.
455 * @param boolean Confirmation of deletion.
456 * @return boolean success or not
458 function delete($sure) {
462 $groups = &$this->getGroups();
463 if (is_array($groups)) {
464 foreach ($groups as $group) {
465 $group->removeUser($this->getID());
470 $res = db_query_params('DELETE FROM artifact_monitor WHERE user_id=$1',
471 array($this->getID()));
473 $this->setError('ERROR - ' . _('Could Not Delete From artifact_monitor:') . ' '.db_error());
477 $res = db_query_params('DELETE FROM artifact_type_monitor WHERE user_id=$1',
478 array($this->getID()));
480 $this->setError('ERROR - ' . _('Could Not Delete From artifact_type_monitor:') . ' ' .db_error());
484 $res = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
485 array($this->getID()));
487 $this->setError('ERROR - ' . _('Could Not Delete From forum_monitored_forums:') . ' '.db_error());
491 $res = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
492 array($this->getID()));
494 $this->setError('ERROR - ' . _('Could Not Delete From filemodule_monitor:') . ' '.db_error());
499 $hook_params = array ();
500 $hook_params['user'] = $this;
501 $hook_params['user_id'] = $this->getID();
502 plugin_hook("user_delete", $hook_params);
504 $this->setStatus('D');
511 * update() - update *common* properties of GFUser object.
513 * Use specific setter to change other properties.
515 * @param string The users first name.
516 * @param string The users last name.
517 * @param int The ID of the users language preference.
518 * @param string The useres timezone preference.
519 * @param string The users preference for receiving site updates by email.
520 * @param string The users preference for receiving community updates by email.
521 * @param string The users preference for being participating in "peer ratings".
522 * @param string The users Jabber account address.
523 * @param int The users Jabber preference.
524 * @param int The users theme_id preference.
525 * @param string The users address.
526 * @param string The users address2.
527 * @param string The users phone.
528 * @param string The users fax.
529 * @param string The users title.
530 * @param string The users ccode.
531 * @param int The users preference for tooltips.
532 * @param string The users email.
534 function update($firstname, $lastname, $language_id, $timezone, $mail_site, $mail_va, $use_ratings,
535 $jabber_address, $jabber_only, $theme_id, $address, $address2, $phone, $fax, $title, $ccode, $tooltips, $email='') {
536 $mail_site = $mail_site ? 1 : 0;
537 $mail_va = $mail_va ? 1 : 0;
538 $block_ratings = $use_ratings ? 0 : 1;
540 if ($jabber_address && !validate_email($jabber_address)) {
541 $this->setError(_('Invalid Jabber Address'));
552 $res = db_query_params('
575 htmlspecialchars($firstname . ' ' .$lastname),
576 htmlspecialchars($firstname),
577 htmlspecialchars($lastname),
585 htmlspecialchars($address),
586 htmlspecialchars($address2),
587 htmlspecialchars($phone),
588 htmlspecialchars($fax),
589 htmlspecialchars($title),
596 $this->setError(_('ERROR - Could Not Update User Object:'). ' ' .db_error());
601 if ($email && $email != $this->getEmail()
602 && !$this->setEmail($email)) {
606 // If there's a transaction from using to not
607 // using ratings, remove all rating made by the
608 // user (ratings by others should not be removed,
609 // as it opens possibility to abuse rate system)
610 if (!$use_ratings && $this->usesRatings()) {
611 db_query_params('DELETE FROM user_ratings WHERE rated_by=$1',
614 if (!$this->fetchData($this->getID())) {
619 $hook_params = array ();
620 $hook_params['user'] = $this;
621 $hook_params['user_id'] = $this->getID();
622 plugin_hook ("user_update", $hook_params);
629 * fetchData - May need to refresh database fields.
631 * If an update occurred and you need to access the updated info.
633 * @param int the User ID data to be fecthed
634 * @return boolean success;
636 function fetchData($user_id) {
637 $res = db_query_params ('SELECT * FROM users WHERE user_id=$1',
639 if (!$res || db_numrows($res) < 1) {
640 $this->setError('GFUser::fetchData():: '.db_error());
643 $this->data_array = db_fetch_array($res);
648 * getID - Simply return the user_id for this object.
650 * @return int This user's user_id number.
653 return $this->data_array['user_id'];
657 * getStatus - get the status of this user.
659 * Statuses include (A)ctive, (P)ending, (S)uspended ,(D)eleted.
661 * @return char This user's status flag.
663 function getStatus() {
664 return $this->data_array['status'];
668 * setStatus - set this user's status.
670 * @param string Status - P, A, S, or D.
671 * @return boolean success.
673 function setStatus($status) {
675 if ($status != 'P' && $status != 'A'
676 && $status != 'S' && $status != 'D') {
677 $this->setError(_('ERROR: Invalid status value'));
680 if ($this->getStatus() != 'P' && $status == 'P') {
681 $this->setError('ERROR: You can\'t set pending status if user is suspend or active');
686 $res = db_query_params ('UPDATE users SET status=$1 WHERE user_id=$2',
691 $this->setError(_('ERROR - Could Not Update User Status:') . ' ' .db_error());
695 $this->data_array['status']=$status;
696 if ($status == 'D') {
697 $projects = $this->getGroups() ;
698 foreach ($projects as $p) {
699 $p->removeUser ($this->getID()) ;
703 $hook_params = array ();
704 $hook_params['user'] = $this;
705 $hook_params['user_id'] = $this->getID();
706 $hook_params['status'] = $status;
707 plugin_hook ("user_setstatus", $hook_params);
716 * isActive - whether this user is confirmed and active.
718 * Database field status of 'A' returns true.
719 * @return boolean is_active.
721 function isActive() {
722 if ($this->getStatus()=='A') {
730 * getUnixStatus - Status of activation of unix account.
732 * @return char (N)one, (A)ctive, (S)uspended or (D)eleted
734 function getUnixStatus() {
735 return $this->data_array['unix_status'];
739 * setUnixStatus - Sets status of activation of unix account.
741 * @param string The unix status.
747 * @return boolean success.
749 function setUnixStatus($status) {
752 $res = db_query_params ('UPDATE users SET unix_status=$1 WHERE user_id=$2',
757 $this->setError('ERROR - Could Not Update User Unix Status: '.db_error());
761 if ($status == 'A') {
762 if (!$SYS->sysCheckCreateUser($this->getID())) {
763 $this->setError($SYS->getErrorMessage());
768 if ($SYS->sysCheckUser($this->getID())) {
769 if (!$SYS->sysRemoveUser($this->getID())) {
770 $this->setError($SYS->getErrorMessage());
777 $this->data_array['unix_status']=$status;
784 * getUnixName - the user's unix_name.
786 * @return string This user's unix/login name.
788 function getUnixName() {
789 return strtolower($this->data_array['user_name']);
793 * getUnixPasswd - get the user's password.
795 * @return string This user's unix crypted passwd.
797 function getUnixPasswd() {
798 return $this->data_array['unix_pw'];
802 * getUnixBox - the hostname of the unix box this user has an account on.
804 * @return string This user's shell login machine.
806 function getUnixBox() {
807 return $this->data_array['unix_box'];
811 * getMD5Passwd - the password.
813 * @return string This user's MD5-crypted passwd.
815 function getMD5Passwd() {
816 return $this->data_array['user_pw'];
819 //Added to be compatible with codendi getUserPw function
820 function getUserPw() {
821 return $this->data_array['user_pw'];
825 * getConfirmHash - the confirm hash in the db.
827 * @return string This user's confirmation hash.
829 function getConfirmHash() {
830 return $this->data_array['confirm_hash'];
834 * getEmail - the user's email address.
836 * @return string This user's email address.
838 function getEmail() {
839 return str_replace("\n", "", $this->data_array['email']);
843 * getSha1Email - a SHA1 encoded hash of the email URI (including mailto: prefix)
845 * @return string The SHA1 encoded value for the email
847 function getSha1Email() {
848 return sha1('mailto:'.$this->getEmail());
852 * getNewEmail - while changing an email address, it is stored here until confirmation.
854 * getNewEmail is a private operation for email change.
856 * @return string This user's new (not yet confirmed) email address.
859 function getNewEmail() {
860 return $this->data_array['email_new'];
864 * setEmail - set a new email address, which must be confirmed.
866 * @param string The email address.
867 * @return boolean success.
869 function setEmail($email) {
871 if (!strcasecmp($this->getEmail(), $email)) {
875 if (!$email || !validate_email($email)) {
876 $this->setError('ERROR: Invalid Email');
880 if (forge_get_config('require_unique_email')) {
881 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)',
882 array ($this->getID(),
883 strtolower($email)))) > 0) {
884 $this->setError(_('User with this email already exists.'));
890 $res = db_query_params ('UPDATE users SET email=$1 WHERE user_id=$2',
895 $this->setError('ERROR - Could Not Update User Email: '.db_error());
899 $hook_params = array ();
900 $hook_params['user'] = $this;
901 $hook_params['user_id'] = $this->getID();
902 $hook_params['user_email'] = $email;
903 plugin_hook("user_setemail", $hook_params);
905 if (!$this->fetchData($this->getId())) {
916 * setNewEmailAndHash - setNewEmailAndHash is a private operation for email change.
918 * @param string The email address.
919 * @param string The email hash.
920 * @return boolean success.
922 function setNewEmailAndHash($email, $hash='') {
925 $hash = substr(md5(strval(time()) . strval(util_randbytes())), 0, 16);
928 if (!$email || !validate_email($email)) {
929 $this->setError('ERROR - Invalid Email');
933 if (forge_get_config('require_unique_email')) {
934 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)',
935 array ($this->getID(),
936 strtolower($email)))) > 0) {
937 $this->setError(_('User with this email already exists.'));
941 $res = db_query_params ('UPDATE users SET confirm_hash=$1, email_new=$2 WHERE user_id=$3',
946 $this->setError('ERROR - Could Not Update User Email And Hash: '.db_error());
949 $this->data_array['email_new'] = $email;
950 $this->data_array['confirm_hash'] = $hash;
956 * getRealName - get the user's real name.
958 * @return string This user's real name.
960 function getRealName() {
961 $last_name = $this->getLastName();
962 return $this->getFirstName(). ($last_name ? ' ' .$last_name:'');
966 * getFirstName - get the user's first name.
968 * @return string This user's first name.
970 function getFirstName() {
971 return $this->data_array['firstname'];
975 * getLastName - get the user's last name.
977 * @return string This user's last name.
979 function getLastName() {
980 return $this->data_array['lastname'];
984 * getAddDate - this user's unix time when account was opened.
986 * @return int This user's unix time when account was opened.
988 function getAddDate() {
989 return $this->data_array['add_date'];
993 * getTimeZone - this user's timezone setting.
995 * @return string This user's timezone setting.
997 function getTimeZone() {
998 return $this->data_array['timezone'];
1002 * getCountryCode - this user's ccode setting.
1004 * @return string This user's ccode setting.
1006 function getCountryCode() {
1007 return $this->data_array['ccode'];
1011 * getShell - this user's preferred shell.
1013 * @return string This user's preferred shell.
1015 function getShell() {
1016 return $this->data_array['shell'];
1020 * setShell - sets user's preferred shell.
1022 * @param string The users preferred shell.
1023 * @return boolean success.
1025 function setShell($shell) {
1027 $shells = file('/etc/shells');
1028 $shells[count($shells)] = "/bin/cvssh";
1029 $out_shells = array();
1030 foreach ($shells as $s) {
1031 if (substr($s, 0, 1) == '#') {
1034 $out_shells[] = chop($s);
1036 if (!in_array($shell, $out_shells)) {
1037 $this->setError(_('ERROR: Invalid Shell'));
1042 $res = db_query_params ('UPDATE users SET shell=$1 WHERE user_id=$2',
1046 $this->setError(_('ERROR - Could Not Update User Unix Shell:') . ' ' .db_error());
1050 // Now change LDAP attribute, but only if corresponding
1051 // entry exists (i.e. if user have shell access)
1052 if ($SYS->sysCheckUser($this->getID()))
1054 if (!$SYS->sysUserSetAttribute($this->getID(),"loginShell",$shell)) {
1055 $this->setError($SYS->getErrorMessage());
1060 $this->data_array['shell']=$shell;
1067 * getUnixUID() - Get the unix UID of the user
1069 * @return int This user's UID.
1071 function getUnixUID() {
1072 return $this->data_array['unix_uid'];
1076 * getUnixGID() - Get the unix GID of the user
1078 * @return int This user's GID.
1080 function getUnixGID() {
1081 return $this->data_array['unix_gid'];
1085 * getLanguage - this user's language_id from supported_languages table.
1087 * @return int This user's language_id.
1089 function getLanguage() {
1090 return $this->data_array['language'];
1094 * getJabberAddress - this user's optional jabber address.
1096 * @return string This user's jabber address.
1098 function getJabberAddress() {
1099 return $this->data_array['jabber_address'];
1103 * getJabberOnly - whether this person wants updates sent ONLY to jabber.
1105 * @return boolean This user's jabber preference.
1107 function getJabberOnly() {
1108 return $this->data_array['jabber_only'];
1112 * getAddress - get this user's address.
1114 * @return text This user's address.
1116 function getAddress() {
1117 return $this->data_array['address'];
1121 * getAddress2 - get this user's address2.
1123 * @return text This user's address2.
1125 function getAddress2() {
1126 return $this->data_array['address2'];
1130 * getPhone - get this person's phone number.
1132 * @return text This user's phone number.
1134 function getPhone() {
1135 return $this->data_array['phone'];
1139 * getFax - get this person's fax number.
1141 * @return text This user's fax.
1144 return $this->data_array['fax'];
1148 * getTitle - get this person's title.
1150 * @return text This user's title.
1152 function getTitle() {
1153 return $this->data_array['title'];
1157 * getGroups - get an array of groups this user is a member of.
1159 * @return array Array of groups.
1161 function &getGroups($onlylocal = true) {
1163 foreach ($this->getRoles() as $r) {
1165 if ($r instanceof RoleExplicit
1166 && $r->getHomeProject() != NULL) {
1167 $ids[] = $r->getHomeProject()->getID();
1170 foreach ($r->getLinkedProjects() as $p) {
1171 $ids[] = $p->getID();
1175 return group_get_objects(array_values(array_unique($ids))) ;
1179 * getAuthorizedKeys - the SSH authorized keys set by the user.
1181 * @return string This user's SSH authorized (public) keys.
1183 function getAuthorizedKeys() {
1184 return preg_replace("/###/", "\n", $this->data_array['authorized_keys']);
1188 * setAuthorizedKeys - set the SSH authorized keys for the user.
1190 * @param string The users public keys.
1191 * @return boolean success.
1193 function setAuthorizedKeys($keys) {
1194 $keys = trim($keys);
1195 $keys = preg_replace("/\r\n/", "\n", $keys); // Convert to Unix EOL
1196 $keys = preg_replace("/\n+/", "\n", $keys); // Remove empty lines
1197 $keys = preg_replace("/\n/", "###", $keys); // Convert EOL to marker
1199 $res = db_query_params('UPDATE users SET authorized_keys=$1 WHERE user_id=$2',
1203 $this->setError(_('ERROR - Could Not Update User SSH Keys'));
1206 $this->data_array['authorized_keys'] = $keys;
1212 * setLoggedIn($val) - Really only used by session code.
1214 * @param boolean The session value.
1216 function setLoggedIn($val=true) {
1217 $this->is_logged_in = $val;
1220 $this->is_super_user = forge_check_global_perm_for_user($this, 'forge_admin') ;
1225 * isLoggedIn - only used by session code.
1227 * @return boolean is_logged_in.
1229 function isLoggedIn() {
1230 return $this->is_logged_in;
1234 * deletePreference - delete a preference for this user.
1236 * @param string The unique field name for this preference.
1237 * @return boolean success.
1239 function deletePreference($preference_name) {
1240 $preference_name=strtolower(trim($preference_name));
1241 unset($this->user_pref["$preference_name"]);
1242 $res = db_query_params('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1243 array ($this->getID(),
1249 * setPreference - set a new preference for this user.
1251 * @param string The unique field name for this preference.
1252 * @param string The value you are setting this preference to.
1253 * @return boolean success.
1255 function setPreference($preference_name,$value) {
1256 $preference_name=strtolower(trim($preference_name));
1257 //delete pref if not value passed in
1258 unset($this->user_pref);
1259 if (!isset($value)) {
1260 $result = db_query_params ('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1261 array ($this->getID(),
1262 $preference_name)) ;
1264 $result = db_query_params ('UPDATE user_preferences SET preference_value=$1,set_date=$2 WHERE user_id=$3 AND preference_name=$4',
1268 $preference_name)) ;
1269 if (db_affected_rows($result) < 1) {
1271 $result = db_query_params ('INSERT INTO user_preferences (user_id,preference_name,preference_value,set_date) VALUES ($1,$2,$3,$4)',
1272 array ($this->getID(),
1282 * getPreference - get a specific preference.
1284 * @param string The unique field name for this preference.
1285 * @return string|bool the preference string or false on failure.
1287 function getPreference($preference_name) {
1288 $preference_name=strtolower(trim($preference_name));
1290 First check to see if we have already fetched the preferences
1292 if (isset($this->user_pref)) {
1293 //echo "\n\nPrefs were fetched already";
1294 if (isset($this->user_pref["$preference_name"])) {
1295 //we have fetched prefs - return part of array
1296 return $this->user_pref["$preference_name"];
1298 //we have fetched prefs, but this pref hasn't been set
1302 //we haven't returned prefs - go to the db
1303 $result = db_query_params ('SELECT preference_name,preference_value FROM user_preferences WHERE user_id=$1',
1304 array ($this->getID())) ;
1305 if (db_numrows($result) < 1) {
1306 //echo "\n\nNo Prefs Found";
1310 //iterate and put the results into an array
1311 for ($i=0; $i<db_numrows($result); $i++) {
1312 $pref["".db_result($result,$i,'preference_name').""]=db_result($result,$i,'preference_value');
1314 $this->user_pref = $pref;
1316 if (array_key_exists($preference_name,$this->user_pref)) {
1317 //we have fetched prefs - return part of array
1318 return $this->user_pref["$preference_name"];
1320 //we have fetched prefs, but this pref hasn't been set
1328 * setPasswd - Changes user's password.
1330 * @param string The plaintext password.
1331 * @return boolean success.
1333 function setPasswd($passwd) {
1335 if (!account_pwvalid($passwd)) {
1336 $this->setError('Error: '.$GLOBALS['register_error']);
1341 $md5_pw = md5 ($passwd) ;
1342 $unix_pw = account_genunixpw ($passwd) ;
1344 $res = db_query_params ('UPDATE users SET user_pw=$1, unix_pw=$2 WHERE user_id=$3',
1349 if (!$res || db_affected_rows($res) < 1) {
1350 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1354 // Now change LDAP password, but only if corresponding
1355 // entry exists (i.e. if user have shell access)
1356 if ($SYS->sysCheckUser($this->getID())) {
1357 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix_pw)) {
1358 $this->setError($SYS->getErrorMessage());
1364 $hook_params = array ();
1365 $hook_params['user'] = $this;
1366 $hook_params['user_id'] = $this->getID();
1367 $hook_params['user_password'] = $passwd;
1368 plugin_hook ("user_setpasswd", $hook_params);
1374 * setMD5Passwd - Changes user's MD5 password.
1376 * @param string The MD5-hashed password.
1377 * @return boolean success.
1379 function setMD5Passwd($md5) {
1385 $res = db_query_params('UPDATE users SET user_pw=$1 WHERE user_id=$2',
1389 if (!$res || db_affected_rows($res) < 1) {
1390 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1400 * setUnixPasswd - Changes user's Unix-hashed password.
1402 * @param string The Unix-hashed password.
1403 * @return boolean success.
1405 function setUnixPasswd($unix) {
1411 $res = db_query_params('UPDATE users SET unix_pw=$1 WHERE user_id=$1',
1415 if (!$res || db_affected_rows($res) < 1) {
1416 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1421 // Now change system password, but only if corresponding
1422 // entry exists (i.e. if user have shell access)
1423 if ($SYS->sysCheckUser($this->getID())) {
1424 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix)) {
1425 $this->setError($SYS->getErrorMessage());
1436 * usesRatings - whether user participates in rating system.
1438 * @return boolean success.
1440 function usesRatings() {
1441 return !$this->data_array['block_ratings'];
1445 * usesTooltips - whether user enables or not tooltips.
1447 * @return boolean success.
1449 function usesTooltips() {
1450 return $this->data_array['tooltips'];
1454 * getPlugins - get a list of all available user plugins
1456 * @return array array containing plugin_id => plugin_name
1458 function getPlugins() {
1459 if (!isset($this->plugins_data)) {
1460 $this->plugins_data = array () ;
1461 $res = db_query_params ('SELECT user_plugin.plugin_id, plugins.plugin_name
1462 FROM user_plugin, plugins
1463 WHERE user_plugin.user_id=$1
1464 AND user_plugin.plugin_id=plugins.plugin_id',
1465 array ($this->getID())) ;
1466 $rows = db_numrows($res);
1468 for ($i=0; $i<$rows; $i++) {
1469 $plugin_id = db_result($res,$i,'plugin_id');
1470 $this->plugins_data[$plugin_id] = db_result($res,$i,'plugin_name');
1473 return $this->plugins_data ;
1477 * usesPlugin - returns true if the user uses a particular plugin
1479 * @param string name of the plugin
1480 * @return boolean whether plugin is being used or not
1482 function usesPlugin($pluginname) {
1483 $plugins_data = $this->getPlugins() ;
1484 foreach ($plugins_data as $p_name) {
1485 if ($p_name == $pluginname) {
1493 * setPluginUse - enables/disables plugins for the user
1495 * @param string name of the plugin
1496 * @param boolean the new state
1497 * @return string database result
1499 function setPluginUse($pluginname, $val=true) {
1500 if ($val == $this->usesPlugin($pluginname)) {
1501 // State is already good, returning
1504 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1505 array($pluginname));
1506 $rows = db_numrows($res);
1508 // Error: no plugin by that name
1511 $plugin_id = db_result($res,0,'plugin_id');
1513 unset ($this->plugins_data);
1515 return db_query_params('INSERT INTO user_plugin (user_id,plugin_id) VALUES ($1,$2)',
1516 array($this->getID(),
1519 return db_query_params('DELETE FROM user_plugin WHERE user_id=$1 AND plugin_id=$2',
1520 array($this->getID(),
1526 * getMailingsPrefs - Get activity status for one of the site mailings.
1528 * @param string The id of mailing ('mail_va' for community mailings, 'mail_siteupdates' for site mailings)
1529 * @return boolean success.
1531 function getMailingsPrefs($mailing_id) {
1532 if ($mailing_id == 'va') {
1533 return $this->data_array['mail_va'];
1534 } else if ($mailing_id == 'site') {
1535 return $this->data_array['mail_siteupdates'];
1542 * unsubscribeFromMailings - Disable email notifications for user.
1544 * @param boolean If false, disable general site mailings, else - all.
1545 * @return boolean success.
1547 function unsubscribeFromMailings($all = false) {
1548 $res1 = $res2 = $res3 = true;
1549 $res1 = db_query_params ('UPDATE users SET mail_siteupdates=0, mail_va=0 WHERE user_id=$1',
1550 array ($this->getID())) ;
1552 $res2 = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
1553 array ($this->getID())) ;
1554 $res3 = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
1555 array ($this->getID())) ;
1558 return $res1 && $res2 && $res3;
1562 * getThemeID - get the theme_id for this user.
1564 * @return int The theme_id.
1566 function getThemeID() {
1567 return $this->data_array['theme_id'];
1571 * setUpTheme - get the theme path
1573 * @return string The theme path.
1575 function setUpTheme() {
1577 // An optimization in session_getdata lets us pre-fetch this in most cases.....
1579 if (!isset($this->data_array['dirname']) || !$this->data_array['dirname']) {
1580 $res = db_query_params ('SELECT dirname FROM themes WHERE theme_id=$1',
1581 array ($this->getThemeID())) ;
1582 $this->theme=db_result($res,0,'dirname');
1584 $this->theme=$this->data_array['dirname'];
1586 if (is_file(forge_get_config('themes_root').'/'.$this->theme.'/Theme.class.php')) {
1587 $GLOBALS['sys_theme']=$this->theme;
1589 $this->theme=forge_get_config('default_theme');
1591 return $this->theme;
1595 * getRole() - Get user Role object.
1597 * @param object group object
1598 * @return object Role object
1600 function getRole(&$g) {
1601 if (is_int ($g) || is_string($g)) {
1604 $group_id = $g->getID();
1606 foreach ($this->getRoles () as $r) {
1607 if ($r instanceof RoleExplicit ) {
1608 $homeproj = $r->getHomeProject();
1610 if ($homeproj->getID() == $group_id) {
1619 function getRoles() {
1620 return RBACEngine::getInstance()->getAvailableRolesForUser($this);
1624 function isMember($g, $type = 0){
1625 if (is_int ($g) || is_string($g)) {
1626 $group = group_get_object ($g) ;
1630 $group_id = $group->getID() ;
1636 foreach ($this->getGroups() as $p) {
1637 if ($p->getID() == $group_id) {
1645 return forge_check_perm_for_user($this, 'pm_admin', $group_id);
1649 return forge_check_perm_for_user($this, 'forum_admin', $group_id);
1652 //admin for this group
1653 return forge_check_perm_for_user($this, 'project_admin', $group_id);
1657 return forge_check_perm_for_user($this, 'docman', $group_id, 'admin');
1668 EVERYTHING BELOW HERE IS DEPRECATED
1671 DO NOT USE FOR ANY NEW CODE
1680 * user_ismember() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1681 * Replace user_ismember(1[, 'A']) with forge_check_global_perm('forge_admin')
1682 * Replace user_ismember($group_id, 'A') with forge_check_perm('project_admin', $group_id)
1683 * For now, keep user_ismember($group_id) alone
1684 * @param int The Group ID
1685 * @param int The Type
1689 function user_ismember($group_id,$type=0) {
1690 if (!session_loggedin()) {
1694 return session_get_user()->isMember($group_id, $type) ;
1698 * user_getname() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1700 * @param int The User ID
1704 function user_getname($user_id = false) {
1705 // use current user if one is not passed in
1707 if (session_loggedin()) {
1708 $user=&user_get_object(user_getid());
1710 return $user->getUnixName();
1712 return 'Error getting user';
1715 return 'No User Id';
1718 $user=&user_get_object($user_id);
1720 return $user->getUnixName();
1722 return 'Invalid User';
1727 class UserComparator {
1728 var $criterion = 'name' ;
1730 function Compare ($a, $b) {
1731 switch ($this->criterion) {
1734 $namecmp = strcoll ($a->getRealName(), $b->getRealName()) ;
1735 if ($namecmp != 0) {
1738 /* If several projects share a same real name */
1739 return strcoll ($a->getUnixName(), $b->getUnixName()) ;
1742 return strcmp ($a->getUnixName(), $b->getUnixName()) ;
1745 $aid = $a->getID() ;
1746 $bid = $b->getID() ;
1750 return ($a < $b) ? -1 : 1;
1756 function sortUserList (&$list, $criterion='name') {
1757 $cmp = new UserComparator () ;
1758 $cmp->criterion = $criterion ;
1760 return usort ($list, array ($cmp, 'Compare')) ;
1765 // c-file-style: "bsd"