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 // if we got this far, it must be good
367 $confirm_hash = substr(md5($password1 . util_randbytes() . microtime()),0,16);
369 $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)
370 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)',
373 account_genunixpw($password1),
374 htmlspecialchars($firstname.' '.$lastname),
375 htmlspecialchars($firstname),
376 htmlspecialchars($lastname),
381 (($mail_site)?"1":"0"),
382 (($mail_va)?"1":"0"),
388 htmlspecialchars($address),
389 htmlspecialchars($address2),
390 htmlspecialchars($phone),
391 htmlspecialchars($fax),
392 htmlspecialchars($title),
397 $this->setError(_('Insert Failed: ') . db_error());
402 $id = db_insertid($result, 'users', 'user_id');
404 $this->setError('Could Not Get USERID: ' .db_error());
409 if (!$this->fetchData($id)) {
414 $hook_params = array();
415 $hook_params['user'] = $this;
416 $hook_params['user_id'] = $this->getID();
417 $hook_params['user_name'] = $unix_name;
418 $hook_params['user_password'] = $password1;
419 plugin_hook("user_create", $hook_params);
422 setup_gettext_from_lang_id($language_id);
423 $this->sendRegistrationEmail();
424 setup_gettext_from_context();
433 * sendRegistrationEmail() - Send email for registration verification
435 * @return bool success or not
437 function sendRegistrationEmail() {
438 $message=stripcslashes(sprintf(_('Thank you for registering on the %3$s web site. You have
439 account with username %1$s created for you. In order
440 to complete your registration, visit the following url:
444 You have 1 week to confirm your account. After this time, your account will be deleted.
446 (If you don\'t see any URL above, it is likely due to a bug in your mail client.
447 Use one below, but make sure it is entered as the single line.)
455 $this->getUnixName(),
456 util_make_url('/account/verify.php?confirm_hash=_'.$this->getConfirmHash()),
457 forge_get_config('forge_name')));
460 sprintf(_('%1$s Account Registration'), forge_get_config('forge_name')),
466 * delete() - remove the User from all his groups.
468 * Remove the User from all his groups and set his status to D.
470 * @param boolean Confirmation of deletion.
471 * @return boolean success or not
473 function delete($sure) {
477 $groups = &$this->getGroups();
478 if (is_array($groups)) {
479 foreach ($groups as $group) {
480 $group->removeUser($this->getID());
485 $res = db_query_params('DELETE FROM artifact_monitor WHERE user_id=$1',
486 array($this->getID()));
488 $this->setError('ERROR - ' . _('Could Not Delete From artifact_monitor:') . ' '.db_error());
492 $res = db_query_params('DELETE FROM artifact_type_monitor WHERE user_id=$1',
493 array($this->getID()));
495 $this->setError('ERROR - ' . _('Could Not Delete From artifact_type_monitor:') . ' ' .db_error());
499 $res = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
500 array($this->getID()));
502 $this->setError('ERROR - ' . _('Could Not Delete From forum_monitored_forums:') . ' '.db_error());
506 $res = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
507 array($this->getID()));
509 $this->setError('ERROR - ' . _('Could Not Delete From filemodule_monitor:') . ' '.db_error());
514 $hook_params = array ();
515 $hook_params['user'] = $this;
516 $hook_params['user_id'] = $this->getID();
517 plugin_hook("user_delete", $hook_params);
519 $this->setStatus('D');
526 * update() - update *common* properties of GFUser object.
528 * Use specific setter to change other properties.
530 * @param string The users first name.
531 * @param string The users last name.
532 * @param int The ID of the users language preference.
533 * @param string The useres timezone preference.
534 * @param string The users preference for receiving site updates by email.
535 * @param string The users preference for receiving community updates by email.
536 * @param string The users preference for being participating in "peer ratings".
537 * @param string The users Jabber account address.
538 * @param int The users Jabber preference.
539 * @param int The users theme_id preference.
540 * @param string The users address.
541 * @param string The users address2.
542 * @param string The users phone.
543 * @param string The users fax.
544 * @param string The users title.
545 * @param string The users ccode.
546 * @param int The users preference for tooltips.
547 * @param string The users email.
549 function update($firstname, $lastname, $language_id, $timezone, $mail_site, $mail_va, $use_ratings,
550 $jabber_address, $jabber_only, $theme_id, $address, $address2, $phone, $fax, $title, $ccode, $tooltips, $email='') {
551 $mail_site = $mail_site ? 1 : 0;
552 $mail_va = $mail_va ? 1 : 0;
553 $block_ratings = $use_ratings ? 0 : 1;
555 if ($jabber_address && !validate_email($jabber_address)) {
556 $this->setError(_('Invalid Jabber Address'));
567 $res = db_query_params('
590 htmlspecialchars($firstname . ' ' .$lastname),
591 htmlspecialchars($firstname),
592 htmlspecialchars($lastname),
600 htmlspecialchars($address),
601 htmlspecialchars($address2),
602 htmlspecialchars($phone),
603 htmlspecialchars($fax),
604 htmlspecialchars($title),
611 $this->setError(_('ERROR - Could Not Update User Object:'). ' ' .db_error());
616 if ($email && $email != $this->getEmail()
617 && !$this->setEmail($email)) {
621 // If there's a transaction from using to not
622 // using ratings, remove all rating made by the
623 // user (ratings by others should not be removed,
624 // as it opens possibility to abuse rate system)
625 if (!$use_ratings && $this->usesRatings()) {
626 db_query_params('DELETE FROM user_ratings WHERE rated_by=$1',
629 if (!$this->fetchData($this->getID())) {
634 $hook_params = array ();
635 $hook_params['user'] = $this;
636 $hook_params['user_id'] = $this->getID();
637 plugin_hook ("user_update", $hook_params);
644 * fetchData - May need to refresh database fields.
646 * If an update occurred and you need to access the updated info.
648 * @param int the User ID data to be fecthed
649 * @return boolean success;
651 function fetchData($user_id) {
652 $res = db_query_params ('SELECT * FROM users WHERE user_id=$1',
654 if (!$res || db_numrows($res) < 1) {
655 $this->setError('GFUser::fetchData():: '.db_error());
658 $this->data_array = db_fetch_array($res);
663 * getID - Simply return the user_id for this object.
665 * @return int This user's user_id number.
668 return $this->data_array['user_id'];
672 * getStatus - get the status of this user.
674 * Statuses include (A)ctive, (P)ending, (S)uspended ,(D)eleted.
676 * @return char This user's status flag.
678 function getStatus() {
679 return $this->data_array['status'];
683 * setStatus - set this user's status.
685 * @param string Status - P, A, S, or D.
686 * @return boolean success.
688 function setStatus($status) {
690 if ($status != 'P' && $status != 'A'
691 && $status != 'S' && $status != 'D') {
692 $this->setError(_('ERROR: Invalid status value'));
695 if ($this->getStatus() != 'P' && $status == 'P') {
696 $this->setError('ERROR: You can\'t set pending status if user is suspend or active');
701 $res = db_query_params ('UPDATE users SET status=$1 WHERE user_id=$2',
706 $this->setError(_('ERROR - Could Not Update User Status:') . ' ' .db_error());
710 $this->data_array['status']=$status;
711 if ($status == 'D') {
712 $projects = $this->getGroups() ;
713 foreach ($projects as $p) {
714 $p->removeUser ($this->getID()) ;
718 $hook_params = array ();
719 $hook_params['user'] = $this;
720 $hook_params['user_id'] = $this->getID();
721 $hook_params['status'] = $status;
722 plugin_hook ("user_setstatus", $hook_params);
731 * isActive - whether this user is confirmed and active.
733 * Database field status of 'A' returns true.
734 * @return boolean is_active.
736 function isActive() {
737 if ($this->getStatus()=='A') {
745 * getUnixStatus - Status of activation of unix account.
747 * @return char (N)one, (A)ctive, (S)uspended or (D)eleted
749 function getUnixStatus() {
750 return $this->data_array['unix_status'];
754 * setUnixStatus - Sets status of activation of unix account.
756 * @param string The unix status.
762 * @return boolean success.
764 function setUnixStatus($status) {
767 $res = db_query_params ('UPDATE users SET unix_status=$1 WHERE user_id=$2',
772 $this->setError('ERROR - Could Not Update User Unix Status: '.db_error());
776 if ($status == 'A') {
777 if (!$SYS->sysCheckCreateUser($this->getID())) {
778 $this->setError($SYS->getErrorMessage());
783 if ($SYS->sysCheckUser($this->getID())) {
784 if (!$SYS->sysRemoveUser($this->getID())) {
785 $this->setError($SYS->getErrorMessage());
792 $this->data_array['unix_status']=$status;
799 * getUnixName - the user's unix_name.
801 * @return string This user's unix/login name.
803 function getUnixName() {
804 return strtolower($this->data_array['user_name']);
808 * getUnixPasswd - get the user's password.
810 * @return string This user's unix crypted passwd.
812 function getUnixPasswd() {
813 return $this->data_array['unix_pw'];
817 * getUnixBox - the hostname of the unix box this user has an account on.
819 * @return string This user's shell login machine.
821 function getUnixBox() {
822 return $this->data_array['unix_box'];
826 * getMD5Passwd - the password.
828 * @return string This user's MD5-crypted passwd.
830 function getMD5Passwd() {
831 return $this->data_array['user_pw'];
834 //Added to be compatible with codendi getUserPw function
835 function getUserPw() {
836 return $this->data_array['user_pw'];
840 * getConfirmHash - the confirm hash in the db.
842 * @return string This user's confirmation hash.
844 function getConfirmHash() {
845 return $this->data_array['confirm_hash'];
849 * getEmail - the user's email address.
851 * @return string This user's email address.
853 function getEmail() {
854 return str_replace("\n", "", $this->data_array['email']);
858 * getSha1Email - a SHA1 encoded hash of the email URI (including mailto: prefix)
860 * @return string The SHA1 encoded value for the email
862 function getSha1Email() {
863 return sha1('mailto:'.$this->getEmail());
867 * getNewEmail - while changing an email address, it is stored here until confirmation.
869 * getNewEmail is a private operation for email change.
871 * @return string This user's new (not yet confirmed) email address.
874 function getNewEmail() {
875 return $this->data_array['email_new'];
879 * setEmail - set a new email address, which must be confirmed.
881 * @param string The email address.
882 * @return boolean success.
884 function setEmail($email) {
886 if (!strcasecmp($this->getEmail(), $email)) {
890 if (!$email || !validate_email($email)) {
891 $this->setError('ERROR: Invalid Email');
895 if (forge_get_config('require_unique_email')) {
896 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)',
897 array ($this->getID(),
898 strtolower($email)))) > 0) {
899 $this->setError(_('User with this email already exists.'));
905 $res = db_query_params ('UPDATE users SET email=$1 WHERE user_id=$2',
910 $this->setError('ERROR - Could Not Update User Email: '.db_error());
914 $hook_params = array ();
915 $hook_params['user'] = $this;
916 $hook_params['user_id'] = $this->getID();
917 $hook_params['user_email'] = $email;
918 plugin_hook("user_setemail", $hook_params);
920 if (!$this->fetchData($this->getId())) {
931 * setNewEmailAndHash - setNewEmailAndHash is a private operation for email change.
933 * @param string The email address.
934 * @param string The email hash.
935 * @return boolean success.
937 function setNewEmailAndHash($email, $hash='') {
940 $hash = substr(md5(strval(time()) . strval(util_randbytes())), 0, 16);
943 if (!$email || !validate_email($email)) {
944 $this->setError('ERROR - Invalid Email');
948 if (forge_get_config('require_unique_email')) {
949 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)',
950 array ($this->getID(),
951 strtolower($email)))) > 0) {
952 $this->setError(_('User with this email already exists.'));
956 $res = db_query_params ('UPDATE users SET confirm_hash=$1, email_new=$2 WHERE user_id=$3',
961 $this->setError('ERROR - Could Not Update User Email And Hash: '.db_error());
964 $this->data_array['email_new'] = $email;
965 $this->data_array['confirm_hash'] = $hash;
971 * getRealName - get the user's real name.
973 * @return string This user's real name.
975 function getRealName() {
976 return $this->data_array['realname'];
980 * setRealName - set the user's real name.
982 * @return string boolean.
984 function setRealName($realname) {
985 $res=db_query_params('UPDATE users SET realname=$1 WHERE user_id=$2',
986 array($realname, $this->getID()));
987 if (!$res || db_affected_rows($res) < 1) {
988 $this->setError('ERROR - Could Not Update real name of user : '.db_error());
991 $this->data_array['realname'] = $realname;
996 * getFirstName - get the user's first name.
998 * @return string This user's first name.
1000 function getFirstName() {
1001 return $this->data_array['firstname'];
1005 * getLastName - get the user's last name.
1007 * @return string This user's last name.
1009 function getLastName() {
1010 return $this->data_array['lastname'];
1014 * getAddDate - this user's unix time when account was opened.
1016 * @return int This user's unix time when account was opened.
1018 function getAddDate() {
1019 return $this->data_array['add_date'];
1023 * getTimeZone - this user's timezone setting.
1025 * @return string This user's timezone setting.
1027 function getTimeZone() {
1028 return $this->data_array['timezone'];
1032 * getCountryCode - this user's ccode setting.
1034 * @return string This user's ccode setting.
1036 function getCountryCode() {
1037 return $this->data_array['ccode'];
1041 * getShell - this user's preferred shell.
1043 * @return string This user's preferred shell.
1045 function getShell() {
1046 return $this->data_array['shell'];
1050 * setShell - sets user's preferred shell.
1052 * @param string The users preferred shell.
1053 * @return boolean success.
1055 function setShell($shell) {
1057 $shells = file('/etc/shells');
1058 $shells[count($shells)] = "/bin/cvssh";
1059 $out_shells = array();
1060 foreach ($shells as $s) {
1061 if (substr($s, 0, 1) == '#') {
1064 $out_shells[] = chop($s);
1066 if (!in_array($shell, $out_shells)) {
1067 $this->setError(_('ERROR: Invalid Shell'));
1072 $res = db_query_params ('UPDATE users SET shell=$1 WHERE user_id=$2',
1076 $this->setError(_('ERROR - Could Not Update User Unix Shell:') . ' ' .db_error());
1080 // Now change LDAP attribute, but only if corresponding
1081 // entry exists (i.e. if user have shell access)
1082 if ($SYS->sysCheckUser($this->getID()))
1084 if (!$SYS->sysUserSetAttribute($this->getID(),"loginShell",$shell)) {
1085 $this->setError($SYS->getErrorMessage());
1090 $this->data_array['shell']=$shell;
1097 * getUnixUID() - Get the unix UID of the user
1099 * @return int This user's UID.
1101 function getUnixUID() {
1102 return $this->data_array['unix_uid'];
1106 * getUnixGID() - Get the unix GID of the user
1108 * @return int This user's GID.
1110 function getUnixGID() {
1111 return $this->data_array['unix_gid'];
1115 * getLanguage - this user's language_id from supported_languages table.
1117 * @return int This user's language_id.
1119 function getLanguage() {
1120 return $this->data_array['language'];
1124 * getJabberAddress - this user's optional jabber address.
1126 * @return string This user's jabber address.
1128 function getJabberAddress() {
1129 return $this->data_array['jabber_address'];
1133 * getJabberOnly - whether this person wants updates sent ONLY to jabber.
1135 * @return boolean This user's jabber preference.
1137 function getJabberOnly() {
1138 return $this->data_array['jabber_only'];
1142 * getAddress - get this user's address.
1144 * @return text This user's address.
1146 function getAddress() {
1147 return $this->data_array['address'];
1151 * getAddress2 - get this user's address2.
1153 * @return text This user's address2.
1155 function getAddress2() {
1156 return $this->data_array['address2'];
1160 * getPhone - get this person's phone number.
1162 * @return text This user's phone number.
1164 function getPhone() {
1165 return $this->data_array['phone'];
1169 * getFax - get this person's fax number.
1171 * @return text This user's fax.
1174 return $this->data_array['fax'];
1178 * getTitle - get this person's title.
1180 * @return text This user's title.
1182 function getTitle() {
1183 return $this->data_array['title'];
1187 * getGroups - get an array of groups this user is a member of.
1189 * @return array Array of groups.
1191 function &getGroups($onlylocal = true) {
1193 foreach ($this->getRoles() as $r) {
1195 if ($r instanceof RoleExplicit
1196 && $r->getHomeProject() != NULL) {
1197 $ids[] = $r->getHomeProject()->getID();
1200 foreach ($r->getLinkedProjects() as $p) {
1201 $ids[] = $p->getID();
1205 return group_get_objects(array_values(array_unique($ids))) ;
1209 * getAuthorizedKeys - the SSH authorized keys set by the user.
1211 * @return string This user's SSH authorized (public) keys.
1213 function getAuthorizedKeys() {
1214 return $this->data_array['authorized_keys'];
1218 * addAuthorizedKey - add the SSH authorized key for the user.
1220 * @param string The user public key.
1221 * @return boolean success.
1223 function addAuthorizedKey($key) {
1225 $key = preg_replace("/\r\n/", "\n", $key); // Convert to Unix EOL
1226 $key = preg_replace("/\n+/", "\n", $key); // Remove empty lines
1227 $tempfile = tempnam("/tmp", "authkey");
1228 $ft = fopen($tempfile, 'w');
1231 $returnExec = array();
1232 exec("/usr/bin/ssh-keygen -lf ".$tempfile, $returnExec);
1234 $returnExecExploded = explode(' ', $returnExec[0]);
1235 $fingerprint = $returnExecExploded[1];
1237 $explodedKey = explode(' ', $key);
1238 $res = db_query_params('insert into sshkeys (userid, fingerprint, upload, sshkey, name, algorithm)
1239 values ($1, $2, $3, $4, $5, $6)',
1240 array($this->getID(), $fingerprint, $now, $key, $explodedKey[2], $explodedKey[0]));
1242 $this->setError(_('ERROR - Could Not Add User SSH Key:').db_error());
1245 $keyid = db_insertid($res, 'sshkeys', 'id_sshkeys');
1246 $this->data_array['authorized_keys'][$keyid]['fingerprint'] = $fingerprint;
1247 $this->data_array['authorized_keys'][$keyid]['upload'] = $now;
1248 $this->data_array['authorized_keys'][$keyid]['sshkey'] = $key;
1249 $this->data_array['authorized_keys'][$keyid]['deploy'] = 0;
1250 $this->data_array['authorized_keys'][$keyid]['keyid'] = $keyid;
1255 function deleteAuthorizedKey($keyid) {
1256 $res = db_query_params('update sshkeys set deleted = 1 where id_sshkeys =$1 and userid = $2',
1257 array($keyid, $this->getID()));
1259 $this->setError(_('ERROR - Could Not Delete User SSH Key:').db_error());
1262 unset($this->data_array['authorized_keys'][$keyid]);
1268 * setLoggedIn($val) - Really only used by session code.
1270 * @param boolean The session value.
1272 function setLoggedIn($val=true) {
1273 $this->is_logged_in = $val;
1276 $this->is_super_user = forge_check_global_perm_for_user($this, 'forge_admin') ;
1281 * isLoggedIn - only used by session code.
1283 * @return boolean is_logged_in.
1285 function isLoggedIn() {
1286 return $this->is_logged_in;
1290 * deletePreference - delete a preference for this user.
1292 * @param string The unique field name for this preference.
1293 * @return boolean success.
1295 function deletePreference($preference_name) {
1296 $preference_name=strtolower(trim($preference_name));
1297 unset($this->user_pref["$preference_name"]);
1298 $res = db_query_params('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1299 array ($this->getID(),
1301 return ((!$res || db_affected_rows($res) < 1) ? false : true);
1305 * setPreference - set a new preference for this user.
1307 * @param string The unique field name for this preference.
1308 * @param string The value you are setting this preference to.
1309 * @return boolean success.
1311 function setPreference($preference_name,$value) {
1312 $preference_name=strtolower(trim($preference_name));
1313 //delete pref if not value passed in
1314 unset($this->user_pref);
1315 if (!isset($value)) {
1316 $result = db_query_params ('DELETE FROM user_preferences WHERE user_id=$1 AND preference_name=$2',
1317 array ($this->getID(),
1318 $preference_name)) ;
1320 $result = db_query_params ('UPDATE user_preferences SET preference_value=$1,set_date=$2 WHERE user_id=$3 AND preference_name=$4',
1324 $preference_name)) ;
1325 if (db_affected_rows($result) < 1) {
1327 $result = db_query_params ('INSERT INTO user_preferences (user_id,preference_name,preference_value,set_date) VALUES ($1,$2,$3,$4)',
1328 array ($this->getID(),
1334 return ((!$result || db_affected_rows($result) < 1) ? false : true);
1338 * getPreference - get a specific preference.
1340 * @param string The unique field name for this preference.
1341 * @return string|bool the preference string or false on failure.
1343 function getPreference($preference_name) {
1344 $preference_name=strtolower(trim($preference_name));
1346 First check to see if we have already fetched the preferences
1348 if (isset($this->user_pref)) {
1349 //echo "\n\nPrefs were fetched already";
1350 if (isset($this->user_pref["$preference_name"])) {
1351 //we have fetched prefs - return part of array
1352 return $this->user_pref["$preference_name"];
1354 //we have fetched prefs, but this pref hasn't been set
1358 //we haven't returned prefs - go to the db
1359 $result = db_query_params ('SELECT preference_name,preference_value FROM user_preferences WHERE user_id=$1',
1360 array ($this->getID())) ;
1361 if (db_numrows($result) < 1) {
1362 //echo "\n\nNo Prefs Found";
1366 //iterate and put the results into an array
1367 for ($i=0; $i<db_numrows($result); $i++) {
1368 $pref["".db_result($result,$i,'preference_name').""]=db_result($result,$i,'preference_value');
1370 $this->user_pref = $pref;
1372 if (array_key_exists($preference_name,$this->user_pref)) {
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
1384 * setPasswd - Changes user's password.
1386 * @param string The plaintext password.
1387 * @return boolean success.
1389 function setPasswd($passwd) {
1391 if (!account_pwvalid($passwd)) {
1392 $this->setError('Error: '.$GLOBALS['register_error']);
1397 $md5_pw = md5 ($passwd) ;
1398 $unix_pw = account_genunixpw ($passwd) ;
1400 $res = db_query_params ('UPDATE users SET user_pw=$1, unix_pw=$2 WHERE user_id=$3',
1405 if (!$res || db_affected_rows($res) < 1) {
1406 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1410 // Now change LDAP password, but only if corresponding
1411 // entry exists (i.e. if user have shell access)
1412 if ($SYS->sysCheckUser($this->getID())) {
1413 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix_pw)) {
1414 $this->setError($SYS->getErrorMessage());
1420 $hook_params = array ();
1421 $hook_params['user'] = $this;
1422 $hook_params['user_id'] = $this->getID();
1423 $hook_params['user_password'] = $passwd;
1424 plugin_hook ("user_setpasswd", $hook_params);
1430 * setMD5Passwd - Changes user's MD5 password.
1432 * @param string The MD5-hashed password.
1433 * @return boolean success.
1435 function setMD5Passwd($md5) {
1441 $res = db_query_params('UPDATE users SET user_pw=$1 WHERE user_id=$2',
1445 if (!$res || db_affected_rows($res) < 1) {
1446 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1456 * setUnixPasswd - Changes user's Unix-hashed password.
1458 * @param string The Unix-hashed password.
1459 * @return boolean success.
1461 function setUnixPasswd($unix) {
1467 $res = db_query_params('UPDATE users SET unix_pw=$1 WHERE user_id=$1',
1471 if (!$res || db_affected_rows($res) < 1) {
1472 $this->setError(_('ERROR - Could Not Change User Password:') . ' ' .db_error());
1477 // Now change system password, but only if corresponding
1478 // entry exists (i.e. if user have shell access)
1479 if ($SYS->sysCheckUser($this->getID())) {
1480 if (!$SYS->sysUserSetAttribute($this->getID(),"userPassword",'{crypt}'.$unix)) {
1481 $this->setError($SYS->getErrorMessage());
1492 * usesRatings - whether user participates in rating system.
1494 * @return boolean success.
1496 function usesRatings() {
1497 return !$this->data_array['block_ratings'];
1501 * usesTooltips - whether user enables or not tooltips.
1503 * @return boolean success.
1505 function usesTooltips() {
1506 return $this->data_array['tooltips'];
1510 * getPlugins - get a list of all available user plugins
1512 * @return array array containing plugin_id => plugin_name
1514 function getPlugins() {
1515 if (!isset($this->plugins_data)) {
1516 $this->plugins_data = array () ;
1517 $res = db_query_params ('SELECT user_plugin.plugin_id, plugins.plugin_name
1518 FROM user_plugin, plugins
1519 WHERE user_plugin.user_id=$1
1520 AND user_plugin.plugin_id=plugins.plugin_id',
1521 array ($this->getID())) ;
1522 $rows = db_numrows($res);
1524 for ($i=0; $i<$rows; $i++) {
1525 $plugin_id = db_result($res,$i,'plugin_id');
1526 $this->plugins_data[$plugin_id] = db_result($res,$i,'plugin_name');
1529 return $this->plugins_data ;
1533 * usesPlugin - returns true if the user uses a particular plugin
1535 * @param string name of the plugin
1536 * @return boolean whether plugin is being used or not
1538 function usesPlugin($pluginname) {
1539 $plugins_data = $this->getPlugins() ;
1540 foreach ($plugins_data as $p_name) {
1541 if ($p_name == $pluginname) {
1549 * setPluginUse - enables/disables plugins for the user
1551 * @param string name of the plugin
1552 * @param boolean the new state
1553 * @return string database result
1555 function setPluginUse($pluginname, $val=true) {
1556 if ($val == $this->usesPlugin($pluginname)) {
1557 // State is already good, returning
1560 $res = db_query_params('SELECT plugin_id FROM plugins WHERE plugin_name=$1',
1561 array($pluginname));
1562 $rows = db_numrows($res);
1564 // Error: no plugin by that name
1567 $plugin_id = db_result($res,0,'plugin_id');
1569 unset ($this->plugins_data);
1571 return db_query_params('INSERT INTO user_plugin (user_id,plugin_id) VALUES ($1,$2)',
1572 array($this->getID(),
1575 return db_query_params('DELETE FROM user_plugin WHERE user_id=$1 AND plugin_id=$2',
1576 array($this->getID(),
1582 * getMailingsPrefs - Get activity status for one of the site mailings.
1584 * @param string The id of mailing ('mail_va' for community mailings, 'mail_siteupdates' for site mailings)
1585 * @return boolean success.
1587 function getMailingsPrefs($mailing_id) {
1588 if ($mailing_id == 'va') {
1589 return $this->data_array['mail_va'];
1590 } else if ($mailing_id == 'site') {
1591 return $this->data_array['mail_siteupdates'];
1598 * unsubscribeFromMailings - Disable email notifications for user.
1600 * @param boolean If false, disable general site mailings, else - all.
1601 * @return boolean success.
1603 function unsubscribeFromMailings($all = false) {
1604 $res1 = $res2 = $res3 = true;
1605 $res1 = db_query_params ('UPDATE users SET mail_siteupdates=0, mail_va=0 WHERE user_id=$1',
1606 array ($this->getID())) ;
1608 $res2 = db_query_params('DELETE FROM forum_monitored_forums WHERE user_id=$1',
1609 array ($this->getID())) ;
1610 $res3 = db_query_params('DELETE FROM filemodule_monitor WHERE user_id=$1',
1611 array ($this->getID())) ;
1614 return $res1 && $res2 && $res3;
1618 * getThemeID - get the theme_id for this user.
1620 * @return int The theme_id.
1622 function getThemeID() {
1623 return $this->data_array['theme_id'];
1627 * setUpTheme - get the theme path
1629 * @return string The theme path.
1631 function setUpTheme() {
1633 // An optimization in session_getdata lets us pre-fetch this in most cases.....
1635 if (!isset($this->data_array['dirname']) || !$this->data_array['dirname']) {
1636 $res = db_query_params ('SELECT dirname FROM themes WHERE theme_id=$1',
1637 array ($this->getThemeID())) ;
1638 $this->theme=db_result($res,0,'dirname');
1640 $this->theme=$this->data_array['dirname'];
1642 if (is_file(forge_get_config('themes_root').'/'.$this->theme.'/Theme.class.php')) {
1643 $GLOBALS['sys_theme']=$this->theme;
1645 $this->theme=forge_get_config('default_theme');
1647 return $this->theme;
1651 * getRole() - Get user Role object.
1653 * @param object group object
1654 * @return object Role object
1656 function getRole(&$g) {
1657 if (is_int ($g) || is_string($g)) {
1660 $group_id = $g->getID();
1662 foreach ($this->getRoles () as $r) {
1663 if ($r instanceof RoleExplicit ) {
1664 $homeproj = $r->getHomeProject();
1666 if ($homeproj->getID() == $group_id) {
1675 function getRoles() {
1676 return RBACEngine::getInstance()->getAvailableRolesForUser($this);
1680 function isMember($g, $type = 0){
1681 if (is_int ($g) || is_string($g)) {
1682 $group = group_get_object ($g) ;
1686 $group_id = $group->getID() ;
1692 foreach ($this->getGroups() as $p) {
1693 if ($p->getID() == $group_id) {
1701 return forge_check_perm_for_user($this, 'pm_admin', $group_id);
1705 return forge_check_perm_for_user($this, 'forum_admin', $group_id);
1708 //admin for this group
1709 return forge_check_perm_for_user($this, 'project_admin', $group_id);
1713 return forge_check_perm_for_user($this, 'docman', $group_id, 'admin');
1719 * setAdminNotification - send an email to all admins (used in verify.php)
1721 * @return boolean True
1723 function setAdminNotification() {
1724 $admins = RBACEngine::getInstance()->getUsersByAllowedAction('forge_admin', -1);
1725 foreach ($admins as $admin) {
1726 $admin_email = $admin->getEmail();
1727 setup_gettext_for_user($admin);
1728 $message = sprintf(_('New User %1$s registered and validated
1732 $this->getUnixName() , $this->getRealName(), $this->getEmail());
1733 util_send_message($admin_email, sprintf(_('New %1$s User'), forge_get_config ('forge_name')), $message);
1734 setup_gettext_from_context();
1745 EVERYTHING BELOW HERE IS DEPRECATED
1748 DO NOT USE FOR ANY NEW CODE
1757 * user_ismember() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1758 * Replace user_ismember(1[, 'A']) with forge_check_global_perm('forge_admin')
1759 * Replace user_ismember($group_id, 'A') with forge_check_perm('project_admin', $group_id)
1760 * For now, keep user_ismember($group_id) alone
1761 * @param int The Group ID
1762 * @param int The Type
1766 function user_ismember($group_id,$type=0) {
1767 if (!session_loggedin()) {
1771 return session_get_user()->isMember($group_id, $type) ;
1775 * user_getname() - DEPRECATED; DO NOT USE! (TODO: document what should be used instead)
1777 * @param int The User ID
1781 function user_getname($user_id = false) {
1782 // use current user if one is not passed in
1784 if (session_loggedin()) {
1785 $user=&user_get_object(user_getid());
1787 return $user->getUnixName();
1789 return 'Error getting user';
1792 return 'No User Id';
1795 $user=&user_get_object($user_id);
1797 return $user->getUnixName();
1799 return 'Invalid User';
1804 class UserComparator {
1805 var $criterion = 'name' ;
1807 function Compare ($a, $b) {
1808 switch ($this->criterion) {
1811 $namecmp = strcoll ($a->getRealName(), $b->getRealName()) ;
1812 if ($namecmp != 0) {
1815 /* If several projects share a same real name */
1816 return strcoll ($a->getUnixName(), $b->getUnixName()) ;
1819 return strcmp ($a->getUnixName(), $b->getUnixName()) ;
1822 $aid = $a->getID() ;
1823 $bid = $b->getID() ;
1827 return ($a < $b) ? -1 : 1;
1833 function sortUserList (&$list, $criterion='name') {
1834 $cmp = new UserComparator () ;
1835 $cmp->criterion = $criterion ;
1837 return usort ($list, array ($cmp, 'Compare')) ;
1842 // c-file-style: "bsd"