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