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 __construct($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 //testing if there is at least one capital letter in the unix name
293 if (preg_match('/[A-Z]/', $unix_name)) {
294 $this->setError(_('Invalid Unix Name (must not contain uppercase characters)'));
297 $unix_name=strtolower($unix_name);
298 if (!account_namevalid($unix_name)) {
299 $this->setError(_('Invalid Unix Name.'));
302 if (!$SYS->sysUseUnixName($unix_name)) {
303 $this->setError(_('Unix name already taken'));
306 if (!validate_email($email)) {
307 $this->setError(_('Invalid Email Address:') .' '. $email);
310 if ($jabber_address && !validate_email($jabber_address)) {
311 $this->setError(_('Invalid Jabber Address'));
319 if ($unix_name && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name LIKE $1',
320 array($unix_name))) > 0) {
321 $this->setError(_('That username already exists.'));
324 if (forge_get_config('require_unique_email')) {
325 if (user_get_object_by_email('$email')) {
326 $this->setError(_('User with this email already exists - use people search to recover your login.'));
330 if (forge_get_config('require_unique_email') && !$unix_name) {
331 // Let's generate a loginname for the user
332 // ...based on the email address:
333 $email_array = explode ('@', $email, 2) ;
334 $email_u = $email_array [0];
335 $l = preg_replace('/[^a-z0-9]/', '', $email_u);
336 $l = substr ($l, 0, 15);
337 // Is the user part of the email address okay?
338 if (account_namevalid($l)
339 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
343 // No? What if we add a number at the end?
346 $c = substr ($l, 0, 15-strlen ("$i")) . "$i" ;
347 if (account_namevalid($c)
348 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
356 // If we're really unlucky, then let's go brute-force
357 while (!$unix_name) {
358 $c = substr (md5($email . util_randbytes()), 0, 15);
359 if (account_namevalid($c)
360 && db_numrows(db_query_params('SELECT user_id FROM users WHERE user_name = $1',
366 $unix_name = strtolower($unix_name);
367 if (!account_namevalid($unix_name)) {
368 $this->setError(_('Invalid Unix Name.'));
371 $shell = account_get_user_default_shell();
372 // if we got this far, it must be good
373 $confirm_hash = substr(md5($password1 . util_randbytes() . microtime()),0,16);
375 $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)
376 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)',
379 account_genunixpw($password1),
380 htmlspecialchars($firstname.' '.$lastname),
381 htmlspecialchars($firstname),
382 htmlspecialchars($lastname),
387 (($mail_site)?"1":"0"),
388 (($mail_va)?"1":"0"),
394 htmlspecialchars($address),
395 htmlspecialchars($address2),
396 htmlspecialchars($phone),
397 htmlspecialchars($fax),
398 htmlspecialchars($title),
404 $this->setError(_('Insert Failed: ') . db_error());
409 $id = db_insertid($result, 'users', 'user_id');
411 $this->setError('Could Not Get USERID: ' .db_error());
416 if (!$this->fetchData($id)) {
421 $hook_params = array();
422 $hook_params['user'] = $this;
423 $hook_params['user_id'] = $this->getID();
424 $hook_params['user_name'] = $unix_name;
425 $hook_params['user_password'] = $password1;
426 plugin_hook("user_create", $hook_params);
429 setup_gettext_from_lang_id($language_id);
430 $this->sendRegistrationEmail();
431 setup_gettext_from_context();
440 * sendRegistrationEmail() - Send email for registration verification
442 * @return bool success or not
444 function sendRegistrationEmail() {
445 $message=stripcslashes(sprintf(_('Thank you for registering on the %3$s web site. You have
446 account with username %1$s created for you. In order
447 to complete your registration, visit the following url:
451 You have 1 week to confirm your account. After this time, your account will be deleted.
453 (If you don\'t see any URL above, it is likely due to a bug in your mail client.
454 Use one below, but make sure it is entered as the single line.)
462 $this->getUnixName(),
463 util_make_url('/account/verify.php?confirm_hash=_'.$this->getConfirmHash()),
464 forge_get_config('forge_name')));
467 sprintf(_('%1$s Account Registration'), forge_get_config('forge_name')),
473 * delete() - remove the User from all his groups.
475 * Remove the User from all his groups and set his status to D.
477 * @param boolean Confirmation of deletion.
478 * @return boolean success or not
480 function delete($sure) {
484 $groups = &$this->getGroups();
485 if (is_array($groups)) {
486 foreach ($groups as $group) {
487 $group->removeUser($this->getID());
492 $res = db_query_params('DELETE FROM artifact_monitor WHERE user_id=$1',
493 array($this->getID()));
495 $this->setError('ERROR - ' . _('Could Not Delete From artifact_monitor:') . ' '.db_error());
499 $res = db_query_params('DELETE FROM artifact_type_monitor WHERE user_id=$1',
500 array($this->getID()));
502 $this->setError('ERROR - ' . _('Could Not Delete From artifact_type_monitor:') . ' ' .db_error());
506 $res = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
507 array($this->getID()));
509 $this->setError('ERROR - ' . _('Could Not Delete From forum_monitored_forums:') . ' '.db_error());
513 $res = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
514 array($this->getID()));
516 $this->setError('ERROR - ' . _('Could Not Delete From filemodule_monitor:') . ' '.db_error());
521 $hook_params = array ();
522 $hook_params['user'] = $this;
523 $hook_params['user_id'] = $this->getID();
524 plugin_hook("user_delete", $hook_params);
526 $this->setStatus('D');
527 $this->setUnixStatus('D');
534 * update() - update *common* properties of GFUser object.
536 * Use specific setter to change other properties.
538 * @param string The users first name.
539 * @param string The users last name.
540 * @param int The ID of the users language preference.
541 * @param string The useres timezone preference.
542 * @param string The users preference for receiving site updates by email.
543 * @param string The users preference for receiving community updates by email.
544 * @param string The users preference for being participating in "peer ratings".
545 * @param string The users Jabber account address.
546 * @param int The users Jabber preference.
547 * @param int The users theme_id preference.
548 * @param string The users address.
549 * @param string The users address2.
550 * @param string The users phone.
551 * @param string The users fax.
552 * @param string The users title.
553 * @param string The users ccode.
554 * @param int The users preference for tooltips.
555 * @param string The users email.
557 function update($firstname, $lastname, $language_id, $timezone, $mail_site, $mail_va, $use_ratings,
558 $jabber_address, $jabber_only, $theme_id, $address, $address2, $phone, $fax, $title, $ccode, $tooltips, $email='') {
559 $mail_site = $mail_site ? 1 : 0;
560 $mail_va = $mail_va ? 1 : 0;
561 $block_ratings = $use_ratings ? 0 : 1;
563 if ($jabber_address && !validate_email($jabber_address)) {
564 $this->setError(_('Invalid Jabber Address'));
575 $res = db_query_params('
598 htmlspecialchars($firstname . ' ' .$lastname),
599 htmlspecialchars($firstname),
600 htmlspecialchars($lastname),
608 htmlspecialchars($address),
609 htmlspecialchars($address2),
610 htmlspecialchars($phone),
611 htmlspecialchars($fax),
612 htmlspecialchars($title),
619 $this->setError(_('ERROR - Could Not Update User Object:'). ' ' .db_error());
624 if ($email && $email != $this->getEmail()
625 && !$this->setEmail($email)) {
629 // If there's a transaction from using to not
630 // using ratings, remove all rating made by the
631 // user (ratings by others should not be removed,
632 // as it opens possibility to abuse rate system)
633 if (!$use_ratings && $this->usesRatings()) {
634 db_query_params('DELETE FROM user_ratings WHERE rated_by=$1',
635 array($this->getID()));
637 if (!$this->fetchData($this->getID())) {
642 $hook_params = array ();
643 $hook_params['user'] = $this;
644 $hook_params['user_id'] = $this->getID();
645 plugin_hook ("user_update", $hook_params);
652 * fetchData - May need to refresh database fields.
654 * If an update occurred and you need to access the updated info.
656 * @param int $user_id the User ID data to be fetched
657 * @return boolean success;
659 function fetchData($user_id) {
660 $res = db_query_params ('SELECT * FROM users WHERE user_id=$1',
662 if (!$res || db_numrows($res) < 1) {
663 $this->setError('GFUser::fetchData():: '.db_error());
666 $this->data_array = db_fetch_array($res);
667 if (($this->getUnixStatus() == 'A') && (forge_get_config('use_shell'))) {
668 $this->data_array['authorized_keys'] = array();
669 $res = db_query_params('select * from sshkeys where userid = $1 and deleted = 0', array($this->getID()));
670 while ($arr = db_fetch_array($res)) {
671 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['upload'] = $arr['upload'];
672 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['name'] = $arr['name'];
673 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['fingerprint'] = $arr['fingerprint'];
674 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['algorithm'] = $arr['algorithm'];
675 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['deploy'] = $arr['deploy'];
676 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['key'] = $arr['sshkey'];
677 $this->data_array['authorized_keys'][$arr['id_sshkeys']]['keyid'] = $arr['id_sshkeys'];
684 * getID - Simply return the user_id for this object.
686 * @return int This user's user_id number.
689 return $this->data_array['user_id'];
693 * getStatus - get the status of this user.
695 * Statuses include (A)ctive, (P)ending, (S)uspended ,(D)eleted.
697 * @return char This user's status flag.
699 function getStatus() {
700 return $this->data_array['status'];
704 * setStatus - set this user's status.
706 * @param string $status Status - P, A, S, or D.
707 * @return boolean success.
709 function setStatus($status) {
711 if ($status != 'P' && $status != 'A'
712 && $status != 'S' && $status != 'D') {
713 $this->setError(_('ERROR: Invalid status value'));
716 if ($this->getStatus() != 'P' && $status == 'P') {
717 $this->setError('ERROR: You can\'t set pending status if user is suspend or active');
722 $res = db_query_params ('UPDATE users SET status=$1 WHERE user_id=$2',
727 $this->setError(_('ERROR - Could Not Update User Status:') . ' ' .db_error());
731 $this->data_array['status']=$status;
732 if ($status == 'D') {
733 $projects = $this->getGroups() ;
734 foreach ($projects as $p) {
735 $p->removeUser ($this->getID()) ;
739 $hook_params = array ();
740 $hook_params['user'] = $this;
741 $hook_params['user_id'] = $this->getID();
742 $hook_params['status'] = $status;
743 plugin_hook ("user_setstatus", $hook_params);
752 * isActive - whether this user is confirmed and active.
754 * Database field status of 'A' returns true.
755 * @return boolean is_active.
757 function isActive() {
758 if ($this->getStatus()=='A') {
766 * getUnixStatus - Status of activation of unix account.
768 * @return char (N)one, (A)ctive, (S)uspended or (D)eleted
770 function getUnixStatus() {
771 return $this->data_array['unix_status'];
775 * setUnixStatus - Sets status of activation of unix account.
777 * @param string The unix status.
783 * @return boolean success.
785 function setUnixStatus($status) {
788 $res = db_query_params ('UPDATE users SET unix_status=$1 WHERE user_id=$2',
793 $this->setError('ERROR - Could Not Update User Unix Status: '.db_error());
797 if ($status == 'A') {
798 if (!$SYS->sysCheckCreateUser($this->getID())) {
799 $this->setError($SYS->getErrorMessage());
804 if ($SYS->sysCheckUser($this->getID())) {
805 if (!$SYS->sysRemoveUser($this->getID())) {
806 $this->setError($SYS->getErrorMessage());
813 $this->data_array['unix_status']=$status;
820 * getUnixName - the user's unix_name.
822 * @return string This user's unix/login name.
824 function getUnixName() {
825 return strtolower($this->data_array['user_name']);
829 * getUnixPasswd - get the user's password.
831 * @return string This user's unix crypted passwd.
833 function getUnixPasswd() {
834 return $this->data_array['unix_pw'];
838 * getUnixBox - the hostname of the unix box this user has an account on.
840 * @return string This user's shell login machine.
842 function getUnixBox() {
843 return $this->data_array['unix_box'];
847 * getMD5Passwd - the password.
849 * @return string This user's MD5-crypted passwd.
851 function getMD5Passwd() {
852 return $this->data_array['user_pw'];
855 //Added to be compatible with codendi getUserPw function
856 function getUserPw() {
857 return $this->data_array['user_pw'];
861 * getConfirmHash - the confirm hash in the db.
863 * @return string This user's confirmation hash.
865 function getConfirmHash() {
866 return $this->data_array['confirm_hash'];
870 * getEmail - the user's email address.
872 * @return string This user's email address.
874 function getEmail() {
875 return str_replace("\n", "", $this->data_array['email']);
879 * getSha1Email - a SHA1 encoded hash of the email URI (including mailto: prefix)
881 * @return string The SHA1 encoded value for the email
883 function getSha1Email() {
884 return sha1('mailto:'.$this->getEmail());
888 * getNewEmail - while changing an email address, it is stored here until confirmation.
890 * getNewEmail is a private operation for email change.
892 * @return string This user's new (not yet confirmed) email address.
895 function getNewEmail() {
896 return $this->data_array['email_new'];
900 * setEmail - set a new email address, which must be confirmed.
902 * @param string The email address.
903 * @return boolean success.
905 function setEmail($email) {
907 if (!strcasecmp($this->getEmail(), $email)) {
911 if (!$email || !validate_email($email)) {
912 $this->setError('ERROR: Invalid Email');
916 if (forge_get_config('require_unique_email')) {
917 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)',
918 array ($this->getID(),
919 strtolower($email)))) > 0) {
920 $this->setError(_('User with this email already exists.'));
926 $res = db_query_params ('UPDATE users SET email=$1 WHERE user_id=$2',
931 $this->setError('ERROR - Could Not Update User Email: '.db_error());
935 $hook_params = array ();
936 $hook_params['user'] = $this;
937 $hook_params['user_id'] = $this->getID();
938 $hook_params['user_email'] = $email;
939 plugin_hook("user_setemail", $hook_params);
941 if (!$this->fetchData($this->getId())) {
952 * setNewEmailAndHash - setNewEmailAndHash is a private operation for email change.
954 * @param string The email address.
955 * @param string The email hash.
956 * @return boolean success.
958 function setNewEmailAndHash($email, $hash='') {
961 $hash = substr(md5(strval(time()) . strval(util_randbytes())), 0, 16);
964 if (!$email || !validate_email($email)) {
965 $this->setError('ERROR - Invalid Email');
969 if (forge_get_config('require_unique_email')) {
970 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)',
971 array ($this->getID(),
972 strtolower($email)))) > 0) {
973 $this->setError(_('User with this email already exists.'));
977 $res = db_query_params ('UPDATE users SET confirm_hash=$1, email_new=$2 WHERE user_id=$3',
982 $this->setError('ERROR - Could Not Update User Email And Hash: '.db_error());
985 $this->data_array['email_new'] = $email;
986 $this->data_array['confirm_hash'] = $hash;
992 * getRealName - get the user's real name.
994 * @return string This user's real name.
996 function getRealName() {
997 return $this->data_array['realname'];
1001 * setRealName - set the user's real name.
1003 * @return string boolean.
1005 function setRealName($realname) {
1006 $res=db_query_params('UPDATE users SET realname=$1 WHERE user_id=$2',
1007 array($realname, $this->getID()));
1008 if (!$res || db_affected_rows($res) < 1) {
1009 $this->setError('ERROR - Could Not Update real name of user : '.db_error());
1012 $this->data_array['realname'] = $realname;
1017 * getFirstName - get the user's first name.
1019 * @return string This user's first name.
1021 function getFirstName() {
1022 return $this->data_array['firstname'];
1026 * getLastName - get the user's last name.
1028 * @return string This user's last name.
1030 function getLastName() {
1031 return $this->data_array['lastname'];
1035 * getAddDate - this user's unix time when account was opened.
1037 * @return int This user's unix time when account was opened.
1039 function getAddDate() {
1040 return $this->data_array['add_date'];
1044 * getTimeZone - this user's timezone setting.
1046 * @return string This user's timezone setting.
1048 function getTimeZone() {
1049 return $this->data_array['timezone'];
1053 * getCountryCode - this user's ccode setting.
1055 * @return string This user's ccode setting.
1057 function getCountryCode() {
1058 return $this->data_array['ccode'];
1062 * getShell - this user's preferred shell.
1064 * @return string This user's preferred shell.
1066 function getShell() {
1067 return $this->data_array['shell'];
1071 * setShell - sets user's preferred shell.
1073 * @param string The users preferred shell.
1074 * @return boolean success.
1076 function setShell($shell) {
1079 $shells = account_getavailableshells();
1081 if (!in_array($shell, $shells)) {
1082 $this->setError( sprintf(_('ERROR: Invalid Shell %s'), $shell) );
1087 $res = db_query_params ('UPDATE users SET shell=$1 WHERE user_id=$2',
1091 $this->setError(_('ERROR - Could Not Update User Unix Shell:') . ' ' .db_error());
1095 // Now change LDAP attribute, but only if corresponding
1096 // entry exists (i.e. if user have shell access)
1097 if ($SYS->sysCheckUser($this->getID()))
1099 if (!$SYS->sysUserSetAttribute($this->getID(),"loginShell",$shell)) {
1100 $this->setError($SYS->getErrorMessage());
1105 $this->data_array['shell']=$shell;
1112 * getUnixUID() - Get the unix UID of the user
1114 * @return int This user's UID.
1116 function getUnixUID() {
1117 return $this->data_array['unix_uid'];
1121 * getUnixGID() - Get the unix GID of the user
1123 * @return int This user's GID.
1125 function getUnixGID() {
1126 return $this->data_array['unix_gid'];
1130 * getLanguage - this user's language_id from supported_languages table.
1132 * @return int This user's language_id.
1134 function getLanguage() {
1135 return $this->data_array['language'];
1139 * getJabberAddress - this user's optional jabber address.
1141 * @return string This user's jabber address.
1143 function getJabberAddress() {
1144 return $this->data_array['jabber_address'];
1148 * getJabberOnly - whether this person wants updates sent ONLY to jabber.
1150 * @return boolean This user's jabber preference.
1152 function getJabberOnly() {
1153 return $this->data_array['jabber_only'];
1157 * getAddress - get this user's address.
1159 * @return text This user's address.
1161 function getAddress() {
1162 return $this->data_array['address'];
1166 * getAddress2 - get this user's address2.
1168 * @return text This user's address2.
1170 function getAddress2() {
1171 return $this->data_array['address2'];
1175 * getPhone - get this person's phone number.
1177 * @return text This user's phone number.
1179 function getPhone() {
1180 return $this->data_array['phone'];
1184 * getFax - get this person's fax number.
1186 * @return text This user's fax.
1189 return $this->data_array['fax'];
1193 * getTitle - get this person's title.
1195 * @return text This user's title.
1197 function getTitle() {
1198 return $this->data_array['title'];
1202 * getGroups - get an array of groups this user is a member of.
1204 * @return array Array of groups.
1206 function &getGroups($onlylocal = true) {
1208 foreach ($this->getRoles() as $r) {
1210 if ($r instanceof RoleExplicit
1211 && $r->getHomeProject() != NULL) {
1212 $ids[] = $r->getHomeProject()->getID();
1215 foreach ($r->getLinkedProjects() as $p) {
1216 $ids[] = $p->getID();
1220 return group_get_objects(array_values(array_unique($ids))) ;
1224 * getAuthorizedKeys - the SSH authorized keys set by the user.
1226 * @return string This user's SSH authorized (public) keys.
1228 function getAuthorizedKeys() {
1229 return $this->data_array['authorized_keys'];
1233 * addAuthorizedKey - add the SSH authorized key for the user.
1235 * @param string The user public key.
1236 * @return boolean success.
1238 function addAuthorizedKey($key) {
1240 $key = preg_replace("/\r\n/", "\n", $key); // Convert to Unix EOL
1241 $key = preg_replace("/\n+/", "\n", $key); // Remove empty lines
1242 $tempfile = tempnam("/tmp", "authkey");
1243 $ft = fopen($tempfile, 'w');
1246 $returnExec = array();
1247 exec("/usr/bin/ssh-keygen -lf ".$tempfile, $returnExec);
1249 $returnExecExploded = explode(' ', $returnExec[0]);
1250 $fingerprint = $returnExecExploded[1];
1252 $explodedKey = explode(' ', $key);
1253 $existingKeys = $this->getAuthorizedKeys();
1254 foreach ($existingKeys as $existingKey) {
1255 if ($existingKey['fingerprint'] == $fingerprint) {
1256 $this->setError(_('SSH Key already in use'));
1260 $res = db_query_params('insert into sshkeys (userid, fingerprint, upload, sshkey, name, algorithm)
1261 values ($1, $2, $3, $4, $5, $6)',
1262 array($this->getID(), $fingerprint, $now, $key, $explodedKey[2], $explodedKey[0]));
1264 $this->setError(_('ERROR - Could Not Add User SSH Key:').db_error());
1267 $keyid = db_insertid($res, 'sshkeys', 'id_sshkeys');
1268 $this->data_array['authorized_keys'][$keyid]['fingerprint'] = $fingerprint;
1269 $this->data_array['authorized_keys'][$keyid]['upload'] = $now;
1270 $this->data_array['authorized_keys'][$keyid]['sshkey'] = $key;
1271 $this->data_array['authorized_keys'][$keyid]['deploy'] = 0;
1272 $this->data_array['authorized_keys'][$keyid]['keyid'] = $keyid;
1277 function deleteAuthorizedKey($keyid) {
1278 $res = db_query_params('update sshkeys set deleted = 1 where id_sshkeys =$1 and userid = $2',
1279 array($keyid, $this->getID()));
1281 $this->setError(_('ERROR - Could Not Delete User SSH Key:').db_error());
1284 unset($this->data_array['authorized_keys'][$keyid]);
1290 * setLoggedIn($val) - Really only used by session code.
1292 * @param boolean The session value.
1294 function setLoggedIn($val=true) {
1295 $this->is_logged_in = $val;
1298 $this->is_super_user = forge_check_global_perm_for_user($this, 'forge_admin') ;
1303 * isLoggedIn - only used by session code.
1305 * @return boolean is_logged_in.
1307 function isLoggedIn() {
1308 return $this->is_logged_in;
1312 * deletePreference - delete a preference for this user.
1314 * @param string The unique field name for this preference.
1315 * @return boolean success.
1317 function deletePreference($preference_name) {
1318 $preference_name=strtolower(trim($preference_name));
1319 unset($this->user_pref["$preference_name"]);
1320 $res = db_query_params('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1321 array ($this->getID(),
1323 return ((!$res || db_affected_rows($res) < 1) ? false : true);
1327 * setPreference - set a new preference for this user.
1329 * @param string The unique field name for this preference.
1330 * @param string The value you are setting this preference to.
1331 * @return boolean success.
1333 function setPreference($preference_name,$value) {
1334 $preference_name=strtolower(trim($preference_name));
1335 //delete pref if not value passed in
1336 unset($this->user_pref);
1337 if (!isset($value)) {
1338 $result = db_query_params ('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1339 array ($this->getID(),
1340 $preference_name)) ;
1342 $result = db_query_params ('UPDATE user_preferences SET preference_value=$1,set_date=$2 WHERE user_id=$3 AND preference_name=$4',
1346 $preference_name)) ;
1347 if (db_affected_rows($result) < 1) {
1349 $result = db_query_params ('INSERT INTO user_preferences (user_id,preference_name,preference_value,set_date) VALUES ($1,$2,$3,$4)',
1350 array ($this->getID(),
1356 return ((!$result || db_affected_rows($result) < 1) ? false : true);
1360 * getPreference - get a specific preference.
1362 * @param string The unique field name for this preference.
1363 * @return string|bool the preference string or false on failure.
1365 function getPreference($preference_name) {
1366 $preference_name=strtolower(trim($preference_name));
1368 First check to see if we have already fetched the preferences
1370 if (isset($this->user_pref)) {
1371 //echo "\n\nPrefs were fetched already";
1372 if (isset($this->user_pref["$preference_name"])) {
1373 //we have fetched prefs - return part of array
1374 return $this->user_pref["$preference_name"];
1376 //we have fetched prefs, but this pref hasn't been set
1380 //we haven't returned prefs - go to the db
1381 $result = db_query_params ('SELECT preference_name,preference_value FROM user_preferences WHERE user_id=$1',
1382 array ($this->getID())) ;
1383 if (db_numrows($result) < 1) {
1384 //echo "\n\nNo Prefs Found";
1388 //iterate and put the results into an array
1389 for ($i=0; $i<db_numrows($result); $i++) {
1390 $pref["".db_result($result,$i,'preference_name').""]=db_result($result,$i,'preference_value');
1392 $this->user_pref = $pref;
1394 if (array_key_exists($preference_name,$this->user_pref)) {
1395 //we have fetched prefs - return part of array
1396 return $this->user_pref["$preference_name"];
1398 //we have fetched prefs, but this pref hasn't been set
1406 * setPasswd - Changes user's password.
1408 * @param string The plaintext password.
1409 * @return boolean success.
1411 function setPasswd($passwd) {
1413 if (!account_pwvalid($passwd)) {
1414 $this->setError('Error: '.$GLOBALS['register_error']);
1419 $md5_pw = md5 ($passwd) ;
1420 $unix_pw = account_genunixpw ($passwd) ;
1422 $res = db_query_params ('UPDATE users SET user_pw=$1, unix_pw=$2 WHERE user_id=$3',
1427 if (!$res || db_affected_rows($res) < 1) {
1428 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1432 // Now change LDAP password, but only if corresponding
1433 // entry exists (i.e. if user have shell access)
1434 if ($SYS->sysCheckUser($this->getID())) {
1435 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix_pw)) {
1436 $this->setError($SYS->getErrorMessage());
1442 $hook_params = array ();
1443 $hook_params['user'] = $this;
1444 $hook_params['user_id'] = $this->getID();
1445 $hook_params['user_password'] = $passwd;
1446 plugin_hook ("user_setpasswd", $hook_params);
1452 * setMD5Passwd - Changes user's MD5 password.
1454 * @param string $md5 The MD5-hashed password.
1455 * @return boolean success.
1457 function setMD5Passwd($md5) {
1460 $res = db_query_params('UPDATE users SET user_pw=$1 WHERE user_id=$2',
1461 array($md5, $this->getID()));
1463 if (!$res || db_affected_rows($res) < 1) {
1464 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1474 * setUnixPasswd - Changes user's Unix-hashed password.
1476 * @param string $unix The Unix-hashed password.
1477 * @return boolean success.
1479 function setUnixPasswd($unix) {
1484 $res = db_query_params('UPDATE users SET unix_pw=$1 WHERE user_id=$1',
1488 if (!$res || db_affected_rows($res) < 1) {
1489 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1494 // Now change system password, but only if corresponding
1495 // entry exists (i.e. if user have shell access)
1496 if ($SYS->sysCheckUser($this->getID())) {
1497 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix)) {
1498 $this->setError($SYS->getErrorMessage());
1509 * usesRatings - whether user participates in rating system.
1511 * @return boolean success.
1513 function usesRatings() {
1514 return !$this->data_array['block_ratings'];
1518 * usesTooltips - whether user enables or not tooltips.
1520 * @return boolean success.
1522 function usesTooltips() {
1523 return $this->data_array['tooltips'];
1527 * getPlugins - get a list of all available user plugins
1529 * @return array array containing plugin_id => plugin_name
1531 function getPlugins() {
1532 if (!isset($this->plugins_data)) {
1533 $this->plugins_data = array () ;
1534 $res = db_query_params ('SELECT user_plugin.plugin_id, plugins.plugin_name
1535 FROM user_plugin, plugins
1536 WHERE user_plugin.user_id=$1
1537 AND user_plugin.plugin_id=plugins.plugin_id',
1538 array ($this->getID())) ;
1539 $rows = db_numrows($res);
1541 for ($i=0; $i<$rows; $i++) {
1542 $plugin_id = db_result($res,$i,'plugin_id');
1543 $this->plugins_data[$plugin_id] = db_result($res,$i,'plugin_name');
1546 return $this->plugins_data ;
1550 * usesPlugin - returns true if the user uses a particular plugin
1552 * @param string name of the plugin
1553 * @return boolean whether plugin is being used or not
1555 function usesPlugin($pluginname) {
1556 $plugins_data = $this->getPlugins() ;
1557 foreach ($plugins_data as $p_name) {
1558 if ($p_name == $pluginname) {
1566 * setPluginUse - enables/disables plugins for the user
1568 * @param string name of the plugin
1569 * @param boolean the new state
1570 * @return string database result
1572 function setPluginUse($pluginname, $val=true) {
1573 if ($val == $this->usesPlugin($pluginname)) {
1574 // State is already good, returning
1577 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1578 array($pluginname));
1579 $rows = db_numrows($res);
1581 // Error: no plugin by that name
1584 $plugin_id = db_result($res,0,'plugin_id');
1586 unset ($this->plugins_data);
1588 return db_query_params('INSERT INTO user_plugin (user_id,plugin_id) VALUES ($1,$2)',
1589 array($this->getID(),
1592 return db_query_params('DELETE FROM user_plugin WHERE user_id=$1 AND plugin_id=$2',
1593 array($this->getID(),
1599 * getMailingsPrefs - Get activity status for one of the site mailings.
1601 * @param string The id of mailing ('mail_va' for community mailings, 'mail_siteupdates' for site mailings)
1602 * @return boolean success.
1604 function getMailingsPrefs($mailing_id) {
1605 if ($mailing_id == 'va') {
1606 return $this->data_array['mail_va'];
1607 } elseif ($mailing_id == 'site') {
1608 return $this->data_array['mail_siteupdates'];
1615 * unsubscribeFromMailings - Disable email notifications for user.
1617 * @param boolean If false, disable general site mailings, else - all.
1618 * @return boolean success.
1620 function unsubscribeFromMailings($all = false) {
1621 $res1 = $res2 = $res3 = true;
1622 $res1 = db_query_params ('UPDATE users SET mail_siteupdates=0, mail_va=0 WHERE user_id=$1',
1623 array ($this->getID())) ;
1625 $res2 = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
1626 array ($this->getID())) ;
1627 $res3 = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
1628 array ($this->getID())) ;
1631 return $res1 && $res2 && $res3;
1635 * getThemeID - get the theme_id for this user.
1637 * @return int The theme_id.
1639 function getThemeID() {
1640 return $this->data_array['theme_id'];
1644 * setUpTheme - get the theme path
1646 * @return string The theme path.
1648 function setUpTheme() {
1650 // An optimization in session_getdata lets us pre-fetch this in most cases.....
1652 if (!isset($this->data_array['dirname']) || !$this->data_array['dirname']) {
1653 $res = db_query_params ('SELECT dirname FROM themes WHERE theme_id=$1',
1654 array ($this->getThemeID())) ;
1655 $this->theme=db_result($res,0,'dirname');
1657 $this->theme=$this->data_array['dirname'];
1659 if (is_file(forge_get_config('themes_root').'/'.$this->theme.'/Theme.class.php')) {
1660 $GLOBALS['sys_theme']=$this->theme;
1662 $this->theme=forge_get_config('default_theme');
1664 return $this->theme;
1668 * getRole() - Get user Role object.
1670 * @param object group object
1671 * @return object Role object
1673 function getRole(&$g) {
1674 if (is_int ($g) || is_string($g)) {
1677 $group_id = $g->getID();
1679 foreach ($this->getRoles () as $r) {
1680 if ($r instanceof RoleExplicit ) {
1681 $homeproj = $r->getHomeProject();
1683 if ($homeproj->getID() == $group_id) {
1692 function getRoles() {
1693 return RBACEngine::getInstance()->getAvailableRolesForUser($this);
1697 function isMember($g, $type = 0){
1698 if (is_int ($g) || is_string($g)) {
1699 $group = group_get_object ($g) ;
1703 $group_id = $group->getID() ;
1709 foreach ($this->getGroups() as $p) {
1710 if ($p->getID() == $group_id) {
1718 return forge_check_perm_for_user($this, 'pm_admin', $group_id);
1722 return forge_check_perm_for_user($this, 'forum_admin', $group_id);
1725 //admin for this group
1726 return forge_check_perm_for_user($this, 'project_admin', $group_id);
1730 return forge_check_perm_for_user($this, 'docman', $group_id, 'admin');
1736 * setAdminNotification - send an email to all admins (used in verify.php)
1738 * @return boolean True
1740 function setAdminNotification() {
1741 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('forge_admin', -1);
1742 foreach ($admins as $admin) {
1743 $admin_email = $admin->getEmail();
1744 setup_gettext_for_user($admin);
1745 $message = sprintf(_('New User %1$s registered and validated
1749 $this->getUnixName() , $this->getRealName(), $this->getEmail());
1750 util_send_message($admin_email, sprintf(_('New %1$s User'), forge_get_config ('forge_name')), $message);
1751 setup_gettext_from_context();
1762 EVERYTHING BELOW HERE IS DEPRECATED
1765 DO NOT USE FOR ANY NEW CODE
1774 * user_ismember() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1775 * Replace user_ismember(1[, 'A']) with forge_check_global_perm('forge_admin')
1776 * Replace user_ismember($group_id, 'A') with forge_check_perm('project_admin', $group_id)
1777 * For now, keep user_ismember($group_id) alone
1778 * @param int The Group ID
1779 * @param int The Type
1783 function user_ismember($group_id,$type=0) {
1784 if (!session_loggedin()) {
1788 return session_get_user()->isMember($group_id, $type) ;
1792 * user_getname() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1794 * @param int The User ID
1798 function user_getname($user_id = false) {
1799 // use current user if one is not passed in
1801 if (session_loggedin()) {
1802 $user=&user_get_object(user_getid());
1804 return $user->getUnixName();
1806 return 'Error getting user';
1809 return 'No User Id';
1812 $user=&user_get_object($user_id);
1814 return $user->getUnixName();
1816 return 'Invalid User';
1821 class UserComparator {
1822 var $criterion = 'name' ;
1824 function Compare ($a, $b) {
1825 switch ($this->criterion) {
1828 $namecmp = strcoll ($a->getRealName(), $b->getRealName()) ;
1829 if ($namecmp != 0) {
1832 /* If several projects share a same real name */
1833 return strcoll ($a->getUnixName(), $b->getUnixName()) ;
1836 return strcmp ($a->getUnixName(), $b->getUnixName()) ;
1839 $aid = $a->getID() ;
1840 $bid = $b->getID() ;
1844 return ($a < $b) ? -1 : 1;
1850 function sortUserList (&$list, $criterion='name') {
1851 $cmp = new UserComparator () ;
1852 $cmp->criterion = $criterion ;
1854 return usort ($list, array ($cmp, 'Compare')) ;
1859 // c-file-style: "bsd"