]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Users/User.php
Release 6.5.0beta1
[Github/sugarcrm.git] / modules / Users / User.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description: TODO:  To be written.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45
46 require_once('include/SugarObjects/templates/person/Person.php');
47
48
49 // User is used to store customer information.
50 class User extends Person {
51         // Stored fields
52         var $name = '';
53         var $full_name;
54         var $id;
55         var $user_name;
56         var $user_hash;
57         var $salutation;
58         var $first_name;
59         var $last_name;
60         var $date_entered;
61         var $date_modified;
62         var $modified_user_id;
63         var $created_by;
64         var $created_by_name;
65         var $modified_by_name;
66         var $description;
67         var $phone_home;
68         var $phone_mobile;
69         var $phone_work;
70         var $phone_other;
71         var $phone_fax;
72         var $email1;
73         var $email2;
74         var $address_street;
75         var $address_city;
76         var $address_state;
77         var $address_postalcode;
78         var $address_country;
79         var $status;
80         var $title;
81         var $portal_only;
82         var $department;
83         var $authenticated = false;
84         var $error_string;
85         var $is_admin;
86         var $employee_status;
87         var $messenger_id;
88         var $messenger_type;
89         var $is_group;
90         var $accept_status; // to support Meetings
91         //adding a property called team_id so we can populate it for use in the team widget
92         var $team_id;
93
94         var $receive_notifications;
95
96         var $reports_to_name;
97         var $reports_to_id;
98         var $team_exists = false;
99         var $table_name = "users";
100         var $module_dir = 'Users';
101         var $object_name = "User";
102         var $user_preferences;
103
104         var $importable = true;
105         var $_userPreferenceFocus;
106
107         var $encodeFields = Array ("first_name", "last_name", "description");
108
109         // This is used to retrieve related fields from form posts.
110         var $additional_column_fields = array ('reports_to_name'
111         );
112
113         var $emailAddress;
114
115
116         var $new_schema = true;
117
118         function User() {
119                 parent::Person();
120
121                 $this->_loadUserPreferencesFocus();
122         }
123
124         protected function _loadUserPreferencesFocus()
125         {
126             $this->_userPreferenceFocus = new UserPreference($this);
127         }
128
129     /**
130      * returns an admin user
131      */
132     public function getSystemUser()
133     {
134         if (null === $this->retrieve('1'))
135             // handle cases where someone deleted user with id "1"
136             $this->retrieve_by_string_fields(array(
137                 'status' => 'Active',
138                 'is_admin' => '1',
139                 ));
140
141         return $this;
142     }
143
144
145         /**
146          * convenience function to get user's default signature
147          */
148         function getDefaultSignature() {
149                 if($defaultId = $this->getPreference('signature_default')) {
150                         return $this->getSignature($defaultId);
151                 } else {
152                         return array();
153                 }
154         }
155
156         /**
157          * retrieves the signatures for a user
158          * @param string id ID of user_signature
159          * @return array ID, signature, and signature_html
160          */
161         public function getSignature($id)
162         {
163             $signatures = $this->getSignaturesArray();
164
165             return isset($signatures[$id]) ? $signatures[$id] : FALSE;
166         }
167
168         function getSignaturesArray() {
169                 $q = 'SELECT * FROM users_signatures WHERE user_id = \''.$this->id.'\' AND deleted = 0 ORDER BY name ASC';
170                 $r = $this->db->query($q);
171
172                 // provide "none"
173                 $sig = array(""=>"");
174
175                 while($a = $this->db->fetchByAssoc($r)) {
176                         $sig[$a['id']] = $a;
177                 }
178
179                 return $sig;
180         }
181
182         /**
183          * retrieves any signatures that the User may have created as <select>
184          */
185         public function getSignatures(
186             $live = false,
187             $defaultSig = '',
188             $forSettings = false
189             )
190         {
191                 $sig = $this->getSignaturesArray();
192                 $sigs = array();
193                 foreach ($sig as $key => $arr)
194                 {
195                         $sigs[$key] = !empty($arr['name']) ? $arr['name'] : '';
196                 }
197
198                 $change = '';
199                 if(!$live) {
200                         $change = ($forSettings) ? "onChange='displaySignatureEdit();'" : "onChange='setSigEditButtonVisibility();'";
201                 }
202
203                 $id = (!$forSettings) ? 'signature_id' : 'signature_idDisplay';
204
205                 $out  = "<select {$change} id='{$id}' name='{$id}'>";
206                 $out .= get_select_options_with_id($sigs, $defaultSig).'</select>';
207
208                 return $out;
209         }
210
211         /**
212          * returns buttons and JS for signatures
213          */
214         function getSignatureButtons($jscall='', $defaultDisplay=false) {
215                 global $mod_strings;
216
217                 $jscall = empty($jscall) ? 'open_email_signature_form' : $jscall;
218
219                 $butts  = "<input class='button' onclick='javascript:{$jscall}(\"\", \"{$this->id}\");' value='{$mod_strings['LBL_BUTTON_CREATE']}' type='button'>&nbsp;";
220                 if($defaultDisplay) {
221                         $butts .= '<span name="edit_sig" id="edit_sig" style="visibility:inherit;"><input class="button" onclick="javascript:'.$jscall.'(document.getElementById(\'signature_id\', \'\').value)" value="'.$mod_strings['LBL_BUTTON_EDIT'].'" type="button" tabindex="392">&nbsp;
222                                         </span>';
223                 } else {
224                         $butts .= '<span name="edit_sig" id="edit_sig" style="visibility:hidden;"><input class="button" onclick="javascript:'.$jscall.'(document.getElementById(\'signature_id\', \'\').value)" value="'.$mod_strings['LBL_BUTTON_EDIT'].'" type="button" tabindex="392">&nbsp;
225                                         </span>';
226                 }
227                 return $butts;
228         }
229
230         /**
231          * performs a rudimentary check to verify if a given user has setup personal
232          * InboundEmail
233          *
234          * @return bool
235          */
236         public function hasPersonalEmail()
237         {
238             $focus = new InboundEmail;
239             $focus->retrieve_by_string_fields(array('group_id' => $this->id));
240
241             return !empty($focus->id);
242         }
243
244         /* Returns the User's private GUID; this is unassociated with the User's
245          * actual GUID.  It is used to secure file names that must be HTTP://
246          * accesible, but obfusicated.
247          */
248         function getUserPrivGuid() {
249         $userPrivGuid = $this->getPreference('userPrivGuid', 'global', $this);
250                 if ($userPrivGuid) {
251                         return $userPrivGuid;
252                 } else {
253                         $this->setUserPrivGuid();
254                         if (!isset ($_SESSION['setPrivGuid'])) {
255                                 $_SESSION['setPrivGuid'] = true;
256                                 $userPrivGuid = $this->getUserPrivGuid();
257                                 return $userPrivGuid;
258                         } else {
259                                 sugar_die("Breaking Infinite Loop Condition: Could not setUserPrivGuid.");
260                         }
261                 }
262         }
263
264         function setUserPrivGuid() {
265                 $privGuid = create_guid();
266                 //($name, $value, $nosession=0)
267                 $this->setPreference('userPrivGuid', $privGuid, 0, 'global', $this);
268         }
269
270         /**
271          * Interface for the User object to calling the UserPreference::setPreference() method in modules/UserPreferences/UserPreference.php
272          *
273          * @see UserPreference::setPreference()
274          *
275          * @param string $name Name of the preference to set
276          * @param string $value Value to set preference to
277          * @param null $nosession For BC, ignored
278          * @param string $category Name of the category to retrieve
279          */
280         public function setPreference(
281             $name,
282             $value,
283             $nosession = 0,
284             $category = 'global'
285             )
286         {
287             // for BC
288             if ( func_num_args() > 4 ) {
289                 $user = func_get_arg(4);
290                 $GLOBALS['log']->deprecated('User::setPreferences() should not be used statically.');
291             }
292             else
293                 $user = $this;
294
295         $user->_userPreferenceFocus->setPreference($name, $value, $category);
296         }
297
298         /**
299          * Interface for the User object to calling the UserPreference::resetPreferences() method in modules/UserPreferences/UserPreference.php
300          *
301          * @see UserPreference::resetPreferences()
302          *
303          * @param string $category category to reset
304          */
305         public function resetPreferences(
306             $category = null
307             )
308         {
309             // for BC
310             if ( func_num_args() > 1 ) {
311                 $user = func_get_arg(1);
312                 $GLOBALS['log']->deprecated('User::resetPreferences() should not be used statically.');
313             }
314             else
315                 $user = $this;
316
317         $user->_userPreferenceFocus->resetPreferences($category);
318         }
319
320         /**
321          * Interface for the User object to calling the UserPreference::savePreferencesToDB() method in modules/UserPreferences/UserPreference.php
322          *
323          * @see UserPreference::savePreferencesToDB()
324          */
325         public function savePreferencesToDB()
326         {
327         // for BC
328             if ( func_num_args() > 0 ) {
329                 $user = func_get_arg(0);
330                 $GLOBALS['log']->deprecated('User::savePreferencesToDB() should not be used statically.');
331             }
332             else
333                 $user = $this;
334
335         $user->_userPreferenceFocus->savePreferencesToDB();
336         }
337
338         /**
339          * Unconditionally reloads user preferences from the DB and updates the session
340          * @param string $category name of the category to retreive, defaults to global scope
341          * @return bool successful?
342          */
343         public function reloadPreferences($category = 'global')
344         {
345             return $this->_userPreferenceFocus->reloadPreferences($category = 'global');
346         }
347
348         /**
349          * Interface for the User object to calling the UserPreference::getUserDateTimePreferences() method in modules/UserPreferences/UserPreference.php
350          *
351          * @see UserPreference::getUserDateTimePreferences()
352          *
353          * @return array 'date' - date format for user ; 'time' - time format for user
354          */
355         public function getUserDateTimePreferences()
356         {
357         // for BC
358             if ( func_num_args() > 0 ) {
359                 $user = func_get_arg(0);
360                 $GLOBALS['log']->deprecated('User::getUserDateTimePreferences() should not be used statically.');
361             }
362             else
363                 $user = $this;
364
365         return $user->_userPreferenceFocus->getUserDateTimePreferences();
366         }
367
368         /**
369          * Interface for the User object to calling the UserPreference::loadPreferences() method in modules/UserPreferences/UserPreference.php
370          *
371          * @see UserPreference::loadPreferences()
372          *
373          * @param string $category name of the category to retreive, defaults to global scope
374          * @return bool successful?
375          */
376         public function loadPreferences(
377             $category = 'global'
378             )
379         {
380             // for BC
381             if ( func_num_args() > 1 ) {
382                 $user = func_get_arg(1);
383                 $GLOBALS['log']->deprecated('User::loadPreferences() should not be used statically.');
384             }
385             else
386                 $user = $this;
387
388         return $user->_userPreferenceFocus->loadPreferences($category);
389         }
390
391         /**
392          * Interface for the User object to calling the UserPreference::setPreference() method in modules/UserPreferences/UserPreference.php
393          *
394          * @see UserPreference::getPreference()
395          *
396          * @param string $name name of the preference to retreive
397          * @param string $category name of the category to retreive, defaults to global scope
398          * @return mixed the value of the preference (string, array, int etc)
399          */
400         public function getPreference(
401             $name,
402             $category = 'global'
403             )
404         {
405             // for BC
406             if ( func_num_args() > 2 ) {
407                 $user = func_get_arg(2);
408                 $GLOBALS['log']->deprecated('User::getPreference() should not be used statically.');
409             }
410             else
411                 $user = $this;
412
413         return $user->_userPreferenceFocus->getPreference($name, $category);
414         }
415
416    /**
417     * Get WHERE clause that fetches all users counted for licensing purposes
418     * @return string
419     */
420         public static function getLicensedUsersWhere()
421         {
422                 return "deleted=0 AND status='Active' AND user_name IS NOT NULL AND is_group=0 AND portal_only=0  AND ".$GLOBALS['db']->convert('user_name', 'length').">0";
423             return "1<>1";
424         }
425
426         function save($check_notify = false) {
427                 $isUpdate = !empty($this->id) && !$this->new_with_id;
428
429
430                 $query = "SELECT count(id) as total from users WHERE ".self::getLicensedUsersWhere();
431
432
433                 // wp: do not save user_preferences in this table, see user_preferences module
434                 $this->user_preferences = '';
435
436                 // if this is an admin user, do not allow is_group or portal_only flag to be set.
437                 if ($this->is_admin) {
438                         $this->is_group = 0;
439                         $this->portal_only = 0;
440                 }
441
442
443
444
445
446                 parent::save($check_notify);
447
448
449
450         $this->savePreferencesToDB();
451         return $this->id;
452         }
453
454         /**
455         * @return boolean true if the user is a member of the role_name, false otherwise
456         * @param string $role_name - Must be the exact name of the acl_role
457         * @param string $user_id - The user id to check for the role membership, empty string if current user
458         * @desc Determine whether or not a user is a member of an ACL Role. This function caches the
459         *       results in the session or to prevent running queries after the first time executed.
460         * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
461         * All Rights Reserved..
462         * Contributor(s): ______________________________________..
463         */
464         function check_role_membership($role_name, $user_id = ''){
465
466                 global $current_user;
467
468                 if(empty($user_id))
469                         $user_id = $current_user->id;
470
471                 // Check the Sugar External Cache to see if this users memberships were cached
472                 $role_array = sugar_cache_retrieve("RoleMemberships_".$user_id);
473
474                 // If we are pulling the roles for the current user
475                 if($user_id == $current_user->id){
476                         // If the Session doesn't contain the values
477                         if(!isset($_SESSION['role_memberships'])){
478                                 // This means the external cache already had it loaded
479                                 if(!empty($role_array))
480                                         $_SESSION['role_memberships'] = $role_array;
481                                 else{
482                                         $_SESSION['role_memberships'] = ACLRole::getUserRoleNames($user_id);
483                                         $role_array = $_SESSION['role_memberships'];
484                                 }
485                         }
486                         // else the session had the values, so we assign to the role array
487                         else{
488                                 $role_array = $_SESSION['role_memberships'];
489                         }
490                 }
491                 else{
492                         // If the external cache didn't contain the values, we get them and put them in cache
493                         if(!$role_array){
494                                 $role_array = ACLRole::getUserRoleNames($user_id);
495                                 sugar_cache_put("RoleMemberships_".$user_id, $role_array);
496                         }
497                 }
498
499                 // If the role doesn't exist in the list of the user's roles
500                 if(!empty($role_array) && in_array($role_name, $role_array))
501                         return true;
502                 else
503                         return false;
504         }
505
506     function get_summary_text() {
507         //$this->_create_proper_name_field();
508         return $this->name;
509         }
510
511         /**
512         * @return string encrypted password for storage in DB and comparison against DB password.
513         * @param string $user_name - Must be non null and at least 2 characters
514         * @param string $user_password - Must be non null and at least 1 character.
515         * @desc Take an unencrypted username and password and return the encrypted password
516          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
517          * All Rights Reserved..
518          * Contributor(s): ______________________________________..
519         */
520         function encrypt_password($user_password) {
521                 // encrypt the password.
522                 $salt = substr($this->user_name, 0, 2);
523                 $encrypted_password = crypt($user_password, $salt);
524
525                 return $encrypted_password;
526         }
527
528         /**
529          * Authenicates the user; returns true if successful
530          *
531          * @param string $password MD5-encoded password
532          * @return bool
533          */
534         public function authenticate_user($password)
535         {
536             $row = self::findUserPassword($this->user_name, $password);
537             if(empty($row)) {
538                 return false;
539                 } else {
540                         $this->id = $row['id'];
541                         return true;
542                 }
543         }
544
545     /**
546      * retrieves an User bean
547      * preformat name & full_name attribute with first/last
548      * loads User's preferences
549      *
550      * @param string id ID of the User
551      * @param bool encode encode the result
552      * @return object User bean
553      * @return null null if no User found
554      */
555         function retrieve($id, $encode = true) {
556                 $ret = parent::retrieve($id, $encode);
557                 if ($ret) {
558                         if (isset ($_SESSION)) {
559                                 $this->loadPreferences();
560                         }
561                 }
562                 return $ret;
563         }
564
565         function retrieve_by_email_address($email) {
566
567                 $email1= strtoupper($email);
568                 $q=<<<EOQ
569
570                 select id from users where id in ( SELECT  er.bean_id AS id FROM email_addr_bean_rel er,
571                         email_addresses ea WHERE ea.id = er.email_address_id
572                     AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = 'Users' AND email_address_caps IN ('{$email}') )
573 EOQ;
574
575
576                 $res=$this->db->query($q);
577                 $row=$this->db->fetchByAssoc($res);
578
579                 if (!empty($row['id'])) {
580                         return $this->retrieve($row['id']);
581                 }
582                 return '';
583         }
584
585    function bean_implements($interface) {
586         switch($interface){
587             case 'ACL':return true;
588         }
589         return false;
590     }
591
592
593         /**
594          * Load a user based on the user_name in $this
595          * @param string $user_password Password
596          * @param bool $password_encoded Is password md5-encoded or plain text?
597          * @return -- this if load was successul and null if load failed.
598          */
599         function load_user($user_password, $password_encoded = false)
600         {
601                 global $login_error;
602                 unset($GLOBALS['login_error']);
603                 if(isset ($_SESSION['loginattempts'])) {
604                         $_SESSION['loginattempts'] += 1;
605                 } else {
606                         $_SESSION['loginattempts'] = 1;
607                 }
608                 if($_SESSION['loginattempts'] > 5) {
609                         $GLOBALS['log']->fatal('SECURITY: '.$this->user_name.' has attempted to login '.$_SESSION['loginattempts'].' times from IP address: '.$_SERVER['REMOTE_ADDR'].'.');
610                         return null;
611                 }
612
613                 $GLOBALS['log']->debug("Starting user load for $this->user_name");
614
615                 if (!isset ($this->user_name) || $this->user_name == "" || !isset ($user_password) || $user_password == "")
616                         return null;
617
618             if(!$password_encoded) {
619                 $user_password = md5($user_password);
620             }
621         $row = self::findUserPassword($this->user_name, $user_password);
622                 if(empty($row) || !empty ($GLOBALS['login_error'])) {
623                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed - could not Load User from Database');
624                         return null;
625                 }
626
627                 // now fill in the fields.
628                 $this->loadFromRow($row);
629                 $this->loadPreferences();
630
631                 require_once ('modules/Versions/CheckVersions.php');
632                 $invalid_versions = get_invalid_versions();
633
634                 if (!empty ($invalid_versions)) {
635                         if (isset ($invalid_versions['Rebuild Relationships'])) {
636                                 unset ($invalid_versions['Rebuild Relationships']);
637
638                                 // flag for pickup in DisplayWarnings.php
639                                 $_SESSION['rebuild_relationships'] = true;
640                         }
641
642                         if (isset ($invalid_versions['Rebuild Extensions'])) {
643                                 unset ($invalid_versions['Rebuild Extensions']);
644
645                                 // flag for pickup in DisplayWarnings.php
646                                 $_SESSION['rebuild_extensions'] = true;
647                         }
648
649                         $_SESSION['invalid_versions'] = $invalid_versions;
650                 }
651                 if ($this->status != "Inactive")
652                         $this->authenticated = true;
653
654                 unset ($_SESSION['loginattempts']);
655                 return $this;
656         }
657
658         /**
659          * Generate a new hash from plaintext password
660          * @param string $password
661          */
662         public static function getPasswordHash($password)
663         {
664             return crypt(strtolower(md5($password)));
665         }
666
667         /**
668          * Check that password matches existing hash
669          * @param string $password Plaintext password
670          * @param string $user_hash DB hash
671          */
672         public static function checkPassword($password, $user_hash)
673         {
674             return self::checkPasswordMD5(md5($password), $user_hash);
675         }
676
677         /**
678          * Check that md5-encoded password matches existing hash
679          * @param string $password MD5-encoded password
680          * @param string $user_hash DB hash
681          * @return bool Match or not?
682          */
683         public static function checkPasswordMD5($password_md5, $user_hash)
684         {
685             if(empty($user_hash)) return false;
686             if($user_hash[0] != '$') {
687                 // Old way - just md5 password
688                 return strtolower($password_md5) == $user_hash;
689             }
690             return crypt(strtolower($password_md5), $user_hash) == $user_hash;
691         }
692
693         /**
694          * Find user with matching password
695          * @param string $name Username
696          * @param string $password MD5-encoded password
697          * @param string $where Limiting query
698          * @return the matching User of false if not found
699          */
700         public static function findUserPassword($name, $password, $where = '')
701         {
702             global $db;
703                 $name = $db->quote($name);
704                 $query = "SELECT * from users where user_name='$name'";
705                 if(!empty($where)) {
706                     $query .= "AND $where";
707                 }
708                 $result = $db->limitQuery($query,0,1,false);
709                 if(!empty($result)) {
710                     $row = $db->fetchByAssoc($result);
711                     if(self::checkPasswordMD5($password, $row['user_hash'])) {
712                         return $row;
713                     }
714                 }
715                 return false;
716         }
717
718         /**
719          * Verify that the current password is correct and write the new password to the DB.
720          *
721          * @param string $user name - Must be non null and at least 1 character.
722          * @param string $user_password - Must be non null and at least 1 character.
723          * @param string $new_password - Must be non null and at least 1 character.
724          * @return boolean - If passwords pass verification and query succeeds, return true, else return false.
725          */
726         function change_password($user_password, $new_password, $system_generated = '0')
727         {
728             global $mod_strings;
729                 global $current_user;
730                 $GLOBALS['log']->debug("Starting password change for $this->user_name");
731
732                 if (!isset ($new_password) || $new_password == "") {
733                         $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user->user_name.$mod_strings['ERR_PASSWORD_CHANGE_FAILED_2'];
734                         return false;
735                 }
736
737                 // Check new password against rules set by admin
738                 if (!$this->check_password_rules($new_password)) {
739                     $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user->user_name.$mod_strings['ERR_PASSWORD_CHANGE_FAILED_3'];
740                     return false;
741                 }
742
743                 $old_user_hash = strtolower(md5($user_password));
744
745                 if (!$current_user->isAdminForModule('Users')) {
746                         //check old password first
747                         $row = self::findUserPassword($this->user_name, md5($user_password));
748             if (empty($row)) {
749                                 $GLOBALS['log']->warn("Incorrect old password for ".$this->user_name."");
750                                 $this->error_string = $mod_strings['ERR_PASSWORD_INCORRECT_OLD_1'].$this->user_name.$mod_strings['ERR_PASSWORD_INCORRECT_OLD_2'];
751                                 return false;
752                         }
753                 }
754
755         $user_hash = self::getPasswordHash($new_password);
756         $this->setPreference('loginexpiration','0');
757         //set new password
758         $now = TimeDate::getInstance()->nowDb();
759                 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='$system_generated', pwd_last_changed='$now' where id='$this->id'";
760                 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
761         $_SESSION['hasExpiredPassword'] = '0';
762                 return true;
763         }
764         
765         /**
766          * Check new password against rules set by admin
767          * @param string $password
768          * @return boolean
769          */
770         function check_password_rules($password) {
771             $length = mb_strlen($password);
772         
773             // Min length
774             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"]) && $GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"] > 0 && $length < $GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"]) {
775                 return false;
776             }
777         
778             // Max length
779             if(!empty($GLOBALS['sugar_config']['passwordsetting']['maxpwdlength']) && $GLOBALS['sugar_config']['passwordsetting']['maxpwdlength'] > 0 && $length > $GLOBALS['sugar_config']['passwordsetting']['maxpwdlength']) {
780                 return false;
781             }
782         
783             // One lower case
784             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onelower"]) && !preg_match('/[a-z]+/', $password)){
785                 return false;
786             }
787         
788             // One upper case
789             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["oneupper"]) && !preg_match('/[A-Z]+/', $password)){
790                 return false;
791             }
792         
793             // One number
794             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onenumber"]) && !preg_match('/[0-9]+/', $password)){
795                 return false;
796             }
797         
798             // One special character
799             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onespecial"]) && !preg_match('/[|}{~!@#$%^&*()_+=-]+/', $password)){
800                 return false;
801             }
802         
803             // Custom regex
804             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["customregex"]) && !preg_match($GLOBALS["sugar_config"]["passwordsetting"]["customregex"], $password)){
805                 return false;
806             }
807         
808             return true;
809         }
810         
811         function is_authenticated() {
812                 return $this->authenticated;
813         }
814
815         function fill_in_additional_list_fields() {
816                 $this->fill_in_additional_detail_fields();
817         }
818
819         function fill_in_additional_detail_fields() {
820                 global $locale;
821
822                 $query = "SELECT u1.first_name, u1.last_name from users  u1, users  u2 where u1.id = u2.reports_to_id AND u2.id = '$this->id' and u1.deleted=0";
823                 $result = $this->db->query($query, true, "Error filling in additional detail fields");
824
825                 $row = $this->db->fetchByAssoc($result);
826
827                 if ($row != null) {
828                         $this->reports_to_name = stripslashes($row['first_name'].' '.$row['last_name']);
829                 } else {
830                         $this->reports_to_name = '';
831                 }
832
833                 $this->_create_proper_name_field();
834         }
835
836         public function retrieve_user_id(
837             $user_name
838             )
839         {
840             $userFocus = new User;
841             $userFocus->retrieve_by_string_fields(array('user_name'=>$user_name));
842             if ( empty($userFocus->id) )
843                 return false;
844
845         return $userFocus->id;
846         }
847
848         /**
849          * @return -- returns a list of all users in the system.
850          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
851          * All Rights Reserved..
852          * Contributor(s): ______________________________________..
853          */
854         function verify_data($ieVerified=true) {
855                 global $mod_strings, $current_user;
856                 $verified = TRUE;
857
858                 if (!empty ($this->id)) {
859                         // Make sure the user doesn't report to themselves.
860                         $reports_to_self = 0;
861                         $check_user = $this->reports_to_id;
862                         $already_seen_list = array ();
863                         while (!empty ($check_user)) {
864                                 if (isset ($already_seen_list[$check_user])) {
865                                         // This user doesn't actually report to themselves
866                                         // But someone above them does.
867                                         $reports_to_self = 1;
868                                         break;
869                                 }
870                                 if ($check_user == $this->id) {
871                                         $reports_to_self = 1;
872                                         break;
873                                 }
874                                 $already_seen_list[$check_user] = 1;
875                                 $query = "SELECT reports_to_id FROM users WHERE id='".$this->db->quote($check_user)."'";
876                                 $result = $this->db->query($query, true, "Error checking for reporting-loop");
877                                 $row = $this->db->fetchByAssoc($result);
878                                 echo ("fetched: ".$row['reports_to_id']." from ".$check_user."<br>");
879                                 $check_user = $row['reports_to_id'];
880                         }
881
882                         if ($reports_to_self == 1) {
883                                 $this->error_string .= $mod_strings['ERR_REPORT_LOOP'];
884                                 $verified = FALSE;
885                         }
886                 }
887
888                 $query = "SELECT user_name from users where user_name='$this->user_name' AND deleted=0";
889                 if(!empty($this->id))$query .=  " AND id<>'$this->id'";
890                 $result = $this->db->query($query, true, "Error selecting possible duplicate users: ");
891                 $dup_users = $this->db->fetchByAssoc($result);
892
893                 if (!empty($dup_users)) {
894                         $this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'].$this->user_name.$mod_strings['ERR_USER_NAME_EXISTS_2'];
895                         $verified = FALSE;
896                 }
897
898                 if (is_admin($current_user)) {
899                     $remaining_admins = $this->db->getOne("SELECT COUNT(*) as c from users where is_admin = 1 AND deleted=0");
900
901                         if (($remaining_admins <= 1) && ($this->is_admin != '1') && ($this->id == $current_user->id)) {
902                                 $GLOBALS['log']->debug("Number of remaining administrator accounts: {$remaining_admins}");
903                                 $this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'].$this->user_name.$mod_strings['ERR_LAST_ADMIN_2'];
904                                 $verified = FALSE;
905                         }
906                 }
907                 ///////////////////////////////////////////////////////////////////////
908                 ////    InboundEmail verification failure
909                 if(!$ieVerified) {
910                         $verified = false;
911                         $this->error_string .= '<br />'.$mod_strings['ERR_EMAIL_NO_OPTS'];
912                 }
913
914                 return $verified;
915         }
916
917         function get_list_view_data() {
918
919                 global $current_user, $mod_strings;
920         // Bug #48555 Not User Name Format of User's locale.
921         $this->_create_proper_name_field();
922
923                 $user_fields = $this->get_list_view_array();
924                 if ($this->is_admin)
925                         $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
926                 elseif (!$this->is_admin) $user_fields['IS_ADMIN'] = '';
927                 if ($this->is_group)
928                         $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
929                 else
930                         $user_fields['IS_GROUP_IMAGE'] = '';
931
932
933         if ($this->is_admin) {
934                         $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',translate('LBL_CHECKMARK', 'Users'));
935         } elseif (!$this->is_admin) {
936               $user_fields['IS_ADMIN'] = '';
937         }
938
939         if ($this->is_group) {
940                 $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',translate('LBL_CHECKMARK', 'Users'));
941         } else {
942             $user_fields['NAME'] = empty ($this->name) ? '' : $this->name;
943         }
944
945                 $user_fields['REPORTS_TO_NAME'] = $this->reports_to_name;
946
947                 $user_fields['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this);
948
949                 return $user_fields;
950         }
951
952         function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
953                 return $list_form;
954         }
955
956
957
958         
959     /**
960      * getAllUsers
961      *
962      * Returns all active and inactive users
963      * @return Array of all users in the system
964      */
965
966     public static function getAllUsers()
967     {
968         $active_users = get_user_array(FALSE);
969         $inactive_users = get_user_array(FALSE, "Inactive");
970         $result = $active_users + $inactive_users;
971         asort($result);
972         return $result;
973     }
974
975         function create_export_query($order_by, $where) {
976                 include('modules/Users/field_arrays.php');
977
978                 $cols = '';
979                 foreach($fields_array['User']['export_fields'] as $field) {
980                         $cols .= (empty($cols)) ? '' : ', ';
981                         $cols .= $field;
982                 }
983
984                 $query = "SELECT {$cols} FROM users ";
985
986                 $where_auto = " users.deleted = 0";
987
988                 if ($where != "")
989                         $query .= " WHERE $where AND ".$where_auto;
990                 else
991                         $query .= " WHERE ".$where_auto;
992
993                 // admin for module user is not be able to export a super-admin
994                 global $current_user;
995                 if(!$current_user->is_admin){
996                         $query .= " AND users.is_admin=0";
997                 }
998
999                 if ($order_by != "")
1000                         $query .= " ORDER BY $order_by";
1001                 else
1002                         $query .= " ORDER BY users.user_name";
1003
1004                 return $query;
1005         }
1006
1007         /** Returns a list of the associated users
1008          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
1009          * All Rights Reserved..
1010          * Contributor(s): ______________________________________..
1011         */
1012         function get_meetings() {
1013                 // First, get the list of IDs.
1014                 $query = "SELECT meeting_id as id from meetings_users where user_id='$this->id' AND deleted=0";
1015                 return $this->build_related_list($query, new Meeting());
1016         }
1017         function get_calls() {
1018                 // First, get the list of IDs.
1019                 $query = "SELECT call_id as id from calls_users where user_id='$this->id' AND deleted=0";
1020                 return $this->build_related_list($query, new Call());
1021         }
1022
1023         /**
1024          * generates Javascript to display I-E mail counts, both personal and group
1025          */
1026         function displayEmailCounts() {
1027                 global $theme;
1028                 $new = translate('LBL_NEW', 'Emails');
1029                 $default = 'index.php?module=Emails&action=ListView&assigned_user_id='.$this->id;
1030                 $count = '';
1031                 $verts = array('Love', 'Links', 'Pipeline', 'RipCurl', 'SugarLite');
1032
1033                 if($this->hasPersonalEmail()) {
1034                         $r = $this->db->query('SELECT count(*) AS c FROM emails WHERE deleted=0 AND assigned_user_id = \''.$this->id.'\' AND type = \'inbound\' AND status = \'unread\'');
1035                         $a = $this->db->fetchByAssoc($r);
1036                         if(in_array($theme, $verts)) {
1037                                 $count .= '<br />';
1038                         } else {
1039                                 $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
1040                         }
1041                         $count .= '<a href='.$default.'&type=inbound>'.translate('LBL_LIST_TITLE_MY_INBOX', 'Emails').': ('.$a['c'].' '.$new.')</a>';
1042
1043                         if(!in_array($theme, $verts)) {
1044                                 $count .= ' - ';
1045                         }
1046                 }
1047
1048                 $r = $this->db->query('SELECT id FROM users WHERE users.is_group = 1 AND deleted = 0');
1049                 $groupIds = '';
1050                 $groupNew = '';
1051                 while($a = $this->db->fetchByAssoc($r)) {
1052                         if($groupIds != '') {$groupIds .= ', ';}
1053                         $groupIds .= "'".$a['id']."'";
1054                 }
1055
1056                 $total = 0;
1057                 if(strlen($groupIds) > 0) {
1058                         $groupQuery = 'SELECT count(*) AS c FROM emails ';
1059                         $groupQuery .= ' WHERE emails.deleted=0 AND emails.assigned_user_id IN ('.$groupIds.') AND emails.type = \'inbound\' AND emails.status = \'unread\'';
1060                         $r = $this->db->query($groupQuery);
1061                         if(is_resource($r)) {
1062                                 $a = $this->db->fetchByAssoc($r);
1063                                 if($a['c'] > 0) {
1064                                         $total = $a['c'];
1065                                 }
1066                         }
1067                 }
1068                 if(in_array($theme, $verts)) $count .= '<br />';
1069                 if(empty($count)) $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
1070                 $count .= '<a href=index.php?module=Emails&action=ListViewGroup>'.translate('LBL_LIST_TITLE_GROUP_INBOX', 'Emails').': ('.$total.' '.$new.')</a>';
1071
1072                 $out  = '<script type="text/javascript" language="Javascript">';
1073                 $out .= 'var welcome = document.getElementById("welcome");';
1074                 $out .= 'var welcomeContent = welcome.innerHTML;';
1075                 $out .= 'welcome.innerHTML = welcomeContent + "'.$count.'";';
1076                 $out .= '</script>';
1077
1078                 echo $out;
1079         }
1080
1081         function getPreferredEmail() {
1082                 $ret = array ();
1083                 $nameEmail = $this->getUsersNameAndEmail();
1084                 $prefAddr = $nameEmail['email'];
1085                 $fullName = $nameEmail['name'];
1086                 if (empty ($prefAddr)) {
1087                         $nameEmail = $this->getSystemDefaultNameAndEmail();
1088                         $prefAddr = $nameEmail['email'];
1089                         $fullName = $nameEmail['name'];
1090                 } // if
1091                 $fullName = from_html($fullName);
1092                 $ret['name'] = $fullName;
1093                 $ret['email'] = $prefAddr;
1094                 return $ret;
1095         }
1096
1097         function getUsersNameAndEmail()
1098         {
1099             // Bug #48555 Not User Name Format of User's locale.
1100             $this->_create_proper_name_field();
1101
1102                 $prefAddr = $this->emailAddress->getPrimaryAddress($this);
1103
1104                 if (empty ($prefAddr)) {
1105                         $prefAddr = $this->emailAddress->getReplyToAddress($this);
1106                 }
1107                 return array('email' => $prefAddr , 'name' => $this->name);
1108
1109         } // fn
1110
1111         function getSystemDefaultNameAndEmail() {
1112
1113                 $email = new Email();
1114                 $return = $email->getSystemDefaultEmail();
1115                 $prefAddr = $return['email'];
1116                 $fullName = $return['name'];
1117                 return array('email' => $prefAddr , 'name' => $fullName);
1118         } // fn
1119
1120         /**
1121          * sets User email default in config.php if not already set by install - i.
1122          * e., upgrades
1123          */
1124         function setDefaultsInConfig() {
1125                 global $sugar_config;
1126                 $sugar_config['email_default_client'] = 'sugar';
1127                 $sugar_config['email_default_editor'] = 'html';
1128                 ksort($sugar_config);
1129                 write_array_to_file('sugar_config', $sugar_config, 'config.php');
1130                 return $sugar_config;
1131         }
1132
1133     /**
1134      * returns User's email address based on descending order of preferences
1135      *
1136      * @param string id GUID of target user if needed
1137      * @return array Assoc array for an email and name
1138      */
1139     function getEmailInfo($id='') {
1140         $user = $this;
1141         if(!empty($id)) {
1142             $user = new User();
1143             $user->retrieve($id);
1144         }
1145
1146         // from name
1147         $fromName = $user->getPreference('mail_fromname');
1148         if(empty($fromName)) {
1149                 // cn: bug 8586 - localized name format
1150             $fromName = $user->full_name;
1151         }
1152
1153         // from address
1154         $fromaddr = $user->getPreference('mail_fromaddress');
1155         if(empty($fromaddr)) {
1156             if(!empty($user->email1) && isset($user->email1)) {
1157                 $fromaddr = $user->email1;
1158             } elseif(!empty($user->email2) && isset($user->email2)) {
1159                 $fromaddr = $user->email2;
1160             } else {
1161                 $r = $user->db->query("SELECT value FROM config WHERE name = 'fromaddress'");
1162                 $a = $user->db->fetchByAssoc($r);
1163                 $fromddr = $a['value'];
1164             }
1165         }
1166
1167         $ret['name'] = $fromName;
1168         $ret['email'] = $fromaddr;
1169
1170         return $ret;
1171     }
1172
1173         /**
1174          * returns opening <a href=xxxx for a contact, account, etc
1175          * cascades from User set preference to System-wide default
1176          * @return string       link
1177          * @param attribute the email addy
1178          * @param focus the parent bean
1179          * @param contact_id
1180          * @param return_module
1181          * @param return_action
1182          * @param return_id
1183          * @param class
1184          */
1185         function getEmailLink2($emailAddress, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1186                 $emailLink = '';
1187                 global $sugar_config;
1188
1189                 if(!isset($sugar_config['email_default_client'])) {
1190                         $this->setDefaultsInConfig();
1191                 }
1192
1193                 $userPref = $this->getPreference('email_link_type');
1194                 $defaultPref = $sugar_config['email_default_client'];
1195                 if($userPref != '') {
1196                         $client = $userPref;
1197                 } else {
1198                         $client = $defaultPref;
1199                 }
1200
1201                 if($client == 'sugar') {
1202                         $email = '';
1203                         $to_addrs_ids = '';
1204                         $to_addrs_names = '';
1205                         $to_addrs_emails = '';
1206
1207                         $fullName = !empty($focus->name) ? $focus->name : '';
1208
1209                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1210                         if(empty($ret_id)) $ret_id = $focus->id;
1211                         if($focus->object_name == 'Contact') {
1212                                 $contact_id = $focus->id;
1213                                 $to_addrs_ids = $focus->id;
1214                                 // Bug #48555 Not User Name Format of User's locale.
1215                                 $focus->_create_proper_name_field();
1216                             $fullName = $focus->name;
1217                             $to_addrs_names = $fullName;
1218                                 $to_addrs_emails = $focus->email1;
1219                         }
1220
1221                         $emailLinkUrl = 'contact_id='.$contact_id.
1222                                 '&parent_type='.$focus->module_dir.
1223                                 '&parent_id='.$focus->id.
1224                                 '&parent_name='.urlencode($fullName).
1225                                 '&to_addrs_ids='.$to_addrs_ids.
1226                                 '&to_addrs_names='.urlencode($to_addrs_names).
1227                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1228                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $emailAddress . '&gt;').
1229                                 '&return_module='.$ret_module.
1230                                 '&return_action='.$ret_action.
1231                                 '&return_id='.$ret_id;
1232
1233                 //Generate the compose package for the quick create options.
1234                 //$json = getJSONobj();
1235                 //$composeOptionsLink = $json->encode( array('composeOptionsLink' => $emailLinkUrl,'id' => $focus->id) );
1236                         require_once('modules/Emails/EmailUI.php');
1237             $eUi = new EmailUI();
1238             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1239
1240                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1241
1242                 } else {
1243                         // straight mailto:
1244                         $emailLink = '<a href="mailto:'.$emailAddress.'" class="'.$class.'">';
1245                 }
1246
1247                 return $emailLink;
1248         }
1249
1250         /**
1251          * returns opening <a href=xxxx for a contact, account, etc
1252          * cascades from User set preference to System-wide default
1253          * @return string       link
1254          * @param attribute the email addy
1255          * @param focus the parent bean
1256          * @param contact_id
1257          * @param return_module
1258          * @param return_action
1259          * @param return_id
1260          * @param class
1261          */
1262         function getEmailLink($attribute, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1263             $emailLink = '';
1264                 global $sugar_config;
1265
1266                 if(!isset($sugar_config['email_default_client'])) {
1267                         $this->setDefaultsInConfig();
1268                 }
1269
1270                 $userPref = $this->getPreference('email_link_type');
1271                 $defaultPref = $sugar_config['email_default_client'];
1272                 if($userPref != '') {
1273                         $client = $userPref;
1274                 } else {
1275                         $client = $defaultPref;
1276                 }
1277
1278                 if($client == 'sugar') {
1279                         $email = '';
1280                         $to_addrs_ids = '';
1281                         $to_addrs_names = '';
1282                         $to_addrs_emails = '';
1283
1284             $fullName = !empty($focus->name) ? $focus->name : '';
1285
1286                         if(!empty($focus->$attribute)) {
1287                                 $email = $focus->$attribute;
1288                         }
1289
1290
1291                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1292                         if(empty($ret_id)) $ret_id = $focus->id;
1293                         if($focus->object_name == 'Contact') {
1294                                 // Bug #48555 Not User Name Format of User's locale.
1295                                 $focus->_create_proper_name_field();
1296                             $fullName = $focus->name;
1297                             $contact_id = $focus->id;
1298                                 $to_addrs_ids = $focus->id;
1299                                 $to_addrs_names = $fullName;
1300                                 $to_addrs_emails = $focus->email1;
1301                         }
1302
1303                         $emailLinkUrl = 'contact_id='.$contact_id.
1304                                 '&parent_type='.$focus->module_dir.
1305                                 '&parent_id='.$focus->id.
1306                                 '&parent_name='.urlencode($fullName).
1307                                 '&to_addrs_ids='.$to_addrs_ids.
1308                                 '&to_addrs_names='.urlencode($to_addrs_names).
1309                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1310                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $email . '&gt;').
1311                                 '&return_module='.$ret_module.
1312                                 '&return_action='.$ret_action.
1313                                 '&return_id='.$ret_id;
1314
1315                         //Generate the compose package for the quick create options.
1316                 require_once('modules/Emails/EmailUI.php');
1317             $eUi = new EmailUI();
1318             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1319                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1320
1321                 } else {
1322                         // straight mailto:
1323                         $emailLink = '<a href="mailto:'.$focus->$attribute.'" class="'.$class.'">';
1324                 }
1325
1326                 return $emailLink;
1327         }
1328
1329
1330         /**
1331          * gets a human-readable explanation of the format macro
1332          * @return string Human readable name format
1333          */
1334         function getLocaleFormatDesc() {
1335                 global $locale;
1336                 global $mod_strings;
1337                 global $app_strings;
1338
1339                 $format['f'] = $mod_strings['LBL_LOCALE_DESC_FIRST'];
1340                 $format['l'] = $mod_strings['LBL_LOCALE_DESC_LAST'];
1341                 $format['s'] = $mod_strings['LBL_LOCALE_DESC_SALUTATION'];
1342                 $format['t'] = $mod_strings['LBL_LOCALE_DESC_TITLE'];
1343
1344                 $name['f'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
1345                 $name['l'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
1346                 $name['s'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
1347                 $name['t'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
1348
1349                 $macro = $locale->getLocaleFormatMacro();
1350
1351                 $ret1 = '';
1352                 $ret2 = '';
1353                 for($i=0; $i<strlen($macro); $i++) {
1354                         if(array_key_exists($macro{$i}, $format)) {
1355                                 $ret1 .= "<i>".$format[$macro{$i}]."</i>";
1356                                 $ret2 .= "<i>".$name[$macro{$i}]."</i>";
1357                         } else {
1358                                 $ret1 .= $macro{$i};
1359                                 $ret2 .= $macro{$i};
1360                         }
1361                 }
1362                 return $ret1."<br />".$ret2;
1363         }
1364
1365
1366     /*
1367      *
1368      * Here are the multi level admin access check functions.
1369      *
1370      */
1371     /**
1372      * Helper function to remap some modules around ACL wise
1373      *
1374      * @return string
1375      */
1376     protected function _fixupModuleForACL($module) {
1377         if($module=='ContractTypes') {
1378             $module = 'Contracts';
1379         }
1380         if(preg_match('/Product[a-zA-Z]*/',$module)) {
1381             $module = 'Products';
1382         }
1383
1384         return $module;
1385     }
1386     /**
1387      * Helper function that enumerates the list of modules and checks if they are an admin/dev.
1388      * The code was just too similar to copy and paste.
1389      *
1390      * @return array
1391      */
1392     protected function _getModulesForACL($type='dev'){
1393         $isDev = $type=='dev';
1394         $isAdmin = $type=='admin';
1395
1396         global $beanList;
1397         $myModules = array();
1398
1399         if (!is_array($beanList) ) {
1400             return $myModules;
1401         }
1402
1403         // These modules don't take kindly to the studio trying to play about with them.
1404         static $ignoredModuleList = array('iFrames','Feeds','Home','Dashboard','Calendar','Activities','Reports');
1405
1406
1407         $actions = ACLAction::getUserActions($this->id);
1408
1409         foreach ($beanList as $module=>$val) {
1410             // Remap the module name
1411             $module = $this->_fixupModuleForACL($module);
1412             if (in_array($module,$myModules)) {
1413                 // Already have the module in the list
1414                 continue;
1415             }
1416             if (in_array($module,$ignoredModuleList)) {
1417                 // You can't develop on these modules.
1418                 continue;
1419             }
1420
1421             $focus = SugarModule::get($module)->loadBean();
1422             if ( $focus instanceOf SugarBean ) {
1423                 $key = $focus->acltype;
1424             } else {
1425                 $key = 'module';
1426             }
1427
1428             if (($this->isAdmin() && isset($actions[$module][$key]))
1429                 ) {
1430                 $myModules[] = $module;
1431             }
1432         }
1433
1434         return $myModules;
1435     }
1436     /**
1437      * Is this user a system wide admin
1438      *
1439      * @return bool
1440      */
1441     public function isAdmin() {
1442         if(isset($this->is_admin)
1443            &&($this->is_admin == '1' || $this->is_admin === 'on')){
1444             return true;
1445         }
1446         return false;
1447     }
1448     /**
1449      * Is this user a developer for any module
1450      *
1451      * @return bool
1452      */
1453     public function isDeveloperForAnyModule() {
1454         if ($this->isAdmin()) {
1455             return true;
1456         }
1457         return false;
1458     }
1459     /**
1460      * List the modules a user has developer access to
1461      *
1462      * @return array
1463      */
1464     public function getDeveloperModules() {
1465         static $developerModules;
1466         if (!isset($_SESSION[$this->user_name.'_get_developer_modules_for_user']) ) {
1467             $_SESSION[$this->user_name.'_get_developer_modules_for_user'] = $this->_getModulesForACL('dev');
1468         }
1469
1470         return $_SESSION[$this->user_name.'_get_developer_modules_for_user'];
1471     }
1472     /**
1473      * Is this user a developer for the specified module
1474      *
1475      * @return bool
1476      */
1477     public function isDeveloperForModule($module) {
1478         if ($this->isAdmin()) {
1479             return true;
1480         }
1481
1482         $devModules = $this->getDeveloperModules();
1483
1484         $module = $this->_fixupModuleForACL($module);
1485
1486         if (in_array($module,$devModules) ) {
1487             return true;
1488         }
1489
1490         return false;
1491     }
1492     /**
1493      * List the modules a user has admin access to
1494      *
1495      * @return array
1496      */
1497     public function getAdminModules() {
1498         if (!isset($_SESSION[$this->user_name.'_get_admin_modules_for_user']) ) {
1499             $_SESSION[$this->user_name.'_get_admin_modules_for_user'] = $this->_getModulesForACL('admin');
1500         }
1501
1502         return $_SESSION[$this->user_name.'_get_admin_modules_for_user'];
1503     }
1504     /**
1505      * Is this user an admin for the specified module
1506      *
1507      * @return bool
1508      */
1509     public function isAdminForModule($module) {
1510         if ($this->isAdmin()) {
1511             return true;
1512         }
1513
1514         $adminModules = $this->getAdminModules();
1515
1516         $module = $this->_fixupModuleForACL($module);
1517
1518         if (in_array($module,$adminModules) ) {
1519             return true;
1520         }
1521
1522         return false;
1523     }
1524         /**
1525          * Whether or not based on the user's locale if we should show the last name first.
1526          *
1527          * @return bool
1528          */
1529         public function showLastNameFirst(){
1530                 global $locale;
1531         $localeFormat = $locale->getLocaleFormatMacro($this);
1532                 if ( strpos($localeFormat,'l') > strpos($localeFormat,'f') ) {
1533                     return false;
1534         }else {
1535                 return true;
1536         }
1537         }
1538
1539
1540
1541    function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false)
1542    {    //call parent method, specifying for array to be returned
1543         $ret_array = parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, true,$parentbean, $singleSelect);
1544
1545         //if this is being called from webservices, then run additional code
1546         if(!empty($GLOBALS['soap_server_object'])){
1547
1548                 //if this is a single select, then secondary queries are being run that may result in duplicate rows being returned through the
1549                 //left joins with meetings/tasks/call.  We need to change the left joins to include a null check (bug 40250)
1550                 if($singleSelect)
1551                 {
1552                         //retrieve the 'from' string and make lowercase for easier manipulation
1553                         $left_str = strtolower($ret_array['from']);
1554                         $lefts = explode('left join', $left_str);
1555                         $new_left_str = '';
1556
1557                         //explode on the left joins and process each one
1558                         foreach($lefts as $ljVal){
1559                                 //grab the join alias
1560                                 $onPos = strpos( $ljVal, ' on');
1561                                 if($onPos === false){
1562                                         $new_left_str .=' '.$ljVal.' ';
1563                                         continue;
1564                                 }
1565                                 $spacePos = strrpos(substr($ljVal, 0, $onPos),' ');
1566                                 $alias = substr($ljVal,$spacePos,$onPos-$spacePos);
1567
1568                                 //add null check to end of the Join statement
1569                         // Bug #46390 to use id_c field instead of id field for custom tables
1570                         if(substr($alias, -5) != '_cstm')
1571                         {
1572                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id is null ';
1573                         }
1574                         else
1575                         {
1576                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id_c is null ';
1577                         }
1578
1579                                 //add statement into new string
1580                                 $new_left_str .= $ljVal;
1581                          }
1582                          //replace the old string with the new one
1583                          $ret_array['from'] = $new_left_str;
1584                 }
1585         }
1586
1587                 //return array or query string
1588                 if($return_array)
1589         {
1590                 return $ret_array;
1591         }
1592
1593         return  $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
1594
1595
1596
1597    }
1598
1599     /**
1600      * Get user first day of week.
1601      *
1602      * @param [User] $user user object, current user if not specified
1603      * @return int : 0 = Sunday, 1 = Monday, etc...
1604      */
1605     public function get_first_day_of_week()
1606     {
1607         $fdow = $this->getPreference('fdow');
1608         if (empty($fdow))
1609         {
1610             $fdow = 0;
1611         }
1612
1613         return $fdow;
1614     }
1615
1616     /**
1617      * Method for password generation
1618      *
1619      * @static
1620      * @return string password
1621      */
1622     public static function generatePassword()
1623     {
1624         $res = $GLOBALS['sugar_config']['passwordsetting'];
1625         $charBKT = '';
1626         //chars to select from
1627         $LOWERCASE = "abcdefghijklmnpqrstuvwxyz";
1628         $NUMBER = "0123456789";
1629         $UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1630         $SPECIAL = '~!@#$%^&*()_+=-{}|';
1631         $condition = 0;
1632         $charBKT .= $UPPERCASE . $LOWERCASE . $NUMBER;
1633         $password = "";
1634             $length = '6';
1635
1636         // Create random characters for the ones that doesnt have requirements
1637         for ($i=0; $i < $length - $condition; $i ++)  // loop and create password
1638         {
1639             $password = $password . substr ($charBKT, rand() % strlen($charBKT), 1);
1640         }
1641
1642         return $password;
1643     }
1644
1645     /**
1646      * Send new password or link to user
1647      *
1648      * @param string $templateId Id of email template
1649      * @param array $additionalData additional params: link, url, password
1650      * @return array status: true|false, message: error message, if status = false and message = '' it means that send method has returned false
1651      */
1652     public function sendEmailForPassword($templateId, array $additionalData = array())
1653     {
1654         global $sugar_config, $current_user;
1655         $mod_strings = return_module_language('', 'Users');
1656         $result = array(
1657             'status' => false,
1658             'message' => ''
1659         );
1660
1661         $emailTemp = new EmailTemplate();
1662         $emailTemp->disable_row_level_security = true;
1663         if ($emailTemp->retrieve($templateId) == '')
1664         {
1665             $result['message'] = $mod_strings['LBL_EMAIL_TEMPLATE_MISSING'];
1666             return $result;
1667         }
1668
1669         //replace instance variables in email templates
1670         $htmlBody = $emailTemp->body_html;
1671         $body = $emailTemp->body;
1672         if (isset($additionalData['link']) && $additionalData['link'] == true)
1673         {
1674             $htmlBody = str_replace('$contact_user_link_guid', $additionalData['url'], $htmlBody);
1675             $body = str_replace('$contact_user_link_guid', $additionalData['url'], $body);
1676         }
1677         else
1678         {
1679             $htmlBody = str_replace('$contact_user_user_hash', $additionalData['password'], $htmlBody);
1680             $body = str_replace('$contact_user_user_hash', $additionalData['password'], $body);
1681         }
1682         // Bug 36833 - Add replacing of special value $instance_url
1683         $htmlBody = str_replace('$config_site_url', $sugar_config['site_url'], $htmlBody);
1684         $body = str_replace('$config_site_url', $sugar_config['site_url'], $body);
1685
1686         $htmlBody = str_replace('$contact_user_user_name', $this->user_name, $htmlBody);
1687         $htmlBody = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $htmlBody);
1688         $body = str_replace('$contact_user_user_name', $this->user_name, $body);
1689         $body = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $body);
1690         $emailTemp->body_html = $htmlBody;
1691         $emailTemp->body = $body;
1692
1693         $itemail = $this->emailAddress->getPrimaryAddress($this);
1694         //retrieve IT Admin Email
1695         //_ppd( $emailTemp->body_html);
1696         //retrieve email defaults
1697         $emailObj = new Email();
1698         $defaults = $emailObj->getSystemDefaultEmail();
1699         require_once('include/SugarPHPMailer.php');
1700         $mail = new SugarPHPMailer();
1701         $mail->setMailerForSystem();
1702         //$mail->IsHTML(true);
1703         $mail->From = $defaults['email'];
1704         $mail->FromName = $defaults['name'];
1705         $mail->ClearAllRecipients();
1706         $mail->ClearReplyTos();
1707         $mail->Subject = from_html($emailTemp->subject);
1708         if ($emailTemp->text_only != 1)
1709         {
1710             $mail->IsHTML(true);
1711             $mail->Body = from_html($emailTemp->body_html);
1712             $mail->AltBody = from_html($emailTemp->body);
1713         }
1714         else
1715         {
1716             $mail->Body_html = from_html($emailTemp->body_html);
1717             $mail->Body = from_html($emailTemp->body);
1718         }
1719         if ($mail->Body == '' && $current_user->is_admin)
1720         {
1721             global $app_strings;
1722             $result['message'] = $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT'];
1723             return $result;
1724         }
1725         if ($mail->Mailer == 'smtp' && $mail->Host =='' && $current_user->is_admin)
1726         {
1727             $result['message'] = $mod_strings['ERR_SERVER_SMTP_EMPTY'];
1728             return $result;
1729         }
1730
1731         $mail->prepForOutbound();
1732         $hasRecipients = false;
1733
1734         if (!empty($itemail))
1735         {
1736             if ($hasRecipients)
1737             {
1738                 $mail->AddBCC($itemail);
1739             }
1740             else
1741             {
1742                 $mail->AddAddress($itemail);
1743             }
1744             $hasRecipients = true;
1745         }
1746         if ($hasRecipients)
1747         {
1748             $result['status'] = @$mail->Send();
1749         }
1750
1751         if ($result['status'] == true)
1752         {
1753             $emailObj->team_id = 1;
1754             $emailObj->to_addrs = '';
1755             $emailObj->type = 'archived';
1756             $emailObj->deleted = '0';
1757             $emailObj->name = $mail->Subject ;
1758             $emailObj->description = $mail->Body;
1759             $emailObj->description_html = null;
1760             $emailObj->from_addr = $mail->From;
1761             $emailObj->parent_type = 'User';
1762             $emailObj->date_sent = TimeDate::getInstance()->nowDb();
1763             $emailObj->modified_user_id = '1';
1764             $emailObj->created_by = '1';
1765             $emailObj->status = 'sent';
1766             $emailObj->save();
1767             if (!isset($additionalData['link']) || $additionalData['link'] == false)
1768             {
1769                 $user_hash = strtolower(md5($additionalData['password']));
1770                 $this->setPreference('loginexpiration', '0');
1771                 $this->setPreference('lockout', '');
1772                 $this->setPreference('loginfailed', '0');
1773                 $this->savePreferencesToDB();
1774                 //set new password
1775                 $now=TimeDate::getInstance()->nowDb();
1776                 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='1', pwd_last_changed='$now' where id='$this->id'";
1777                 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
1778             }
1779         }
1780
1781         return $result;
1782     }
1783
1784     // Bug #48014 Must to send password to imported user if this action is required
1785     function afterImportSave()
1786     {
1787         if(
1788             $this->user_hash == false
1789             && !$this->is_group
1790             && !$this->portal_only
1791             && isset($GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON'])
1792             && $GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON']
1793         )
1794         {
1795             $backUpPost = $_POST;
1796             $_POST = array(
1797                 'userId' => $this->id
1798             );
1799             ob_start();
1800             require('modules/Users/GeneratePassword.php');
1801             $result = ob_get_clean();
1802             $_POST = $backUpPost;
1803             return $result == true;
1804         }
1805     }
1806 }