]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Users/User.php
Release 6.4.1
[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 $signatures[$id];
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 $password
532          * @return bool
533          */
534         public function authenticate_user(
535             $password
536             )
537         {
538                 $password = $GLOBALS['db']->quote($password);
539                 $user_name = $GLOBALS['db']->quote($this->user_name);
540                 $query = "SELECT * from $this->table_name where user_name='$user_name' AND user_hash='$password' AND (portal_only IS NULL OR portal_only !='1') AND (is_group IS NULL OR is_group !='1') ";
541                 //$result = $this->db->requireSingleResult($query, false);
542                 $result = $this->db->limitQuery($query,0,1,false);
543                 $a = $this->db->fetchByAssoc($result);
544                 // set the ID in the seed user.  This can be used for retrieving the full user record later
545                 if (empty ($a)) {
546                         // already logging this in load_user() method
547                         //$GLOBALS['log']->fatal("SECURITY: failed login by $this->user_name");
548                         return false;
549                 } else {
550                         $this->id = $a['id'];
551                         return true;
552                 }
553         }
554
555     /**
556      * retrieves an User bean
557      * preformat name & full_name attribute with first/last
558      * loads User's preferences
559      *
560      * @param string id ID of the User
561      * @param bool encode encode the result
562      * @return object User bean
563      * @return null null if no User found
564      */
565         function retrieve($id, $encode = true) {
566                 $ret = parent::retrieve($id, $encode);
567                 if ($ret) {
568                         if (isset ($_SESSION)) {
569                                 $this->loadPreferences();
570                         }
571                 }
572                 return $ret;
573         }
574
575         function retrieve_by_email_address($email) {
576
577                 $email1= strtoupper($email);
578                 $q=<<<EOQ
579
580                 select id from users where id in ( SELECT  er.bean_id AS id FROM email_addr_bean_rel er,
581                         email_addresses ea WHERE ea.id = er.email_address_id
582                     AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = 'Users' AND email_address_caps IN ('{$email}') )
583 EOQ;
584
585
586                 $res=$this->db->query($q);
587                 $row=$this->db->fetchByAssoc($res);
588
589                 if (!empty($row['id'])) {
590                         return $this->retrieve($row['id']);
591                 }
592                 return '';
593         }
594
595    function bean_implements($interface) {
596         switch($interface){
597             case 'ACL':return true;
598         }
599         return false;
600     }
601
602
603         /**
604          * Load a user based on the user_name in $this
605          * @return -- this if load was successul and null if load failed.
606          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
607          * All Rights Reserved..
608          * Contributor(s): ______________________________________..
609          */
610         function load_user($user_password) {
611                 global $login_error;
612                 unset($GLOBALS['login_error']);
613                 if(isset ($_SESSION['loginattempts'])) {
614                         $_SESSION['loginattempts'] += 1;
615                 } else {
616                         $_SESSION['loginattempts'] = 1;
617                 }
618                 if($_SESSION['loginattempts'] > 5) {
619                         $GLOBALS['log']->fatal('SECURITY: '.$this->user_name.' has attempted to login '.$_SESSION['loginattempts'].' times from IP address: '.$_SERVER['REMOTE_ADDR'].'.');
620                 }
621
622                 $GLOBALS['log']->debug("Starting user load for $this->user_name");
623
624                 if (!isset ($this->user_name) || $this->user_name == "" || !isset ($user_password) || $user_password == "")
625                         return null;
626
627                 $user_hash = strtolower(md5($user_password));
628                 if($this->authenticate_user($user_hash)) {
629                         $query = "SELECT * from $this->table_name where id='$this->id'";
630                 } else {
631                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed');
632                         return null;
633                 }
634                 $r = $this->db->limitQuery($query, 0, 1, false);
635                 $a = $this->db->fetchByAssoc($r);
636                 if(empty($a) || !empty ($GLOBALS['login_error'])) {
637                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed - could not Load User from Database');
638                         return null;
639                 }
640
641                 // Get the fields for the user
642                 $row = $a;
643
644                 // If there is no user_hash is not present or is out of date, then create a new one.
645                 if (!isset ($row['user_hash']) || $row['user_hash'] != $user_hash) {
646                         $query = "UPDATE $this->table_name SET user_hash='$user_hash' where id='{$row['id']}'";
647                         $this->db->query($query, true, "Error setting new hash for {$row['user_name']}: ");
648                 }
649
650                 // now fill in the fields.
651                 foreach ($this->column_fields as $field) {
652                         $GLOBALS['log']->info($field);
653
654                         if (isset ($row[$field])) {
655                                 $GLOBALS['log']->info("=".$row[$field]);
656
657                                 $this-> $field = $row[$field];
658                         }
659                 }
660
661                 $this->loadPreferences();
662
663
664                 require_once ('modules/Versions/CheckVersions.php');
665                 $invalid_versions = get_invalid_versions();
666
667                 if (!empty ($invalid_versions)) {
668                         if (isset ($invalid_versions['Rebuild Relationships'])) {
669                                 unset ($invalid_versions['Rebuild Relationships']);
670
671                                 // flag for pickup in DisplayWarnings.php
672                                 $_SESSION['rebuild_relationships'] = true;
673                         }
674
675                         if (isset ($invalid_versions['Rebuild Extensions'])) {
676                                 unset ($invalid_versions['Rebuild Extensions']);
677
678                                 // flag for pickup in DisplayWarnings.php
679                                 $_SESSION['rebuild_extensions'] = true;
680                         }
681
682                         $_SESSION['invalid_versions'] = $invalid_versions;
683                 }
684                 $this->fill_in_additional_detail_fields();
685                 if ($this->status != "Inactive")
686                         $this->authenticated = true;
687
688                 unset ($_SESSION['loginattempts']);
689                 return $this;
690         }
691
692         /**
693          * Verify that the current password is correct and write the new password to the DB.
694          *
695          * @param string $user name - Must be non null and at least 1 character.
696          * @param string $user_password - Must be non null and at least 1 character.
697          * @param string $new_password - Must be non null and at least 1 character.
698          * @return boolean - If passwords pass verification and query succeeds, return true, else return false.
699          */
700         function change_password(
701             $user_password,
702             $new_password,
703             $system_generated = '0'
704             )
705         {
706             global $mod_strings;
707                 global $current_user;
708                 $GLOBALS['log']->debug("Starting password change for $this->user_name");
709
710                 if (!isset ($new_password) || $new_password == "") {
711                         $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user->user_name.$mod_strings['ERR_PASSWORD_CHANGE_FAILED_2'];
712                         return false;
713                 }
714
715                 // Check new password against rules set by admin
716                 if (!$this->check_password_rules($new_password)) {
717                     $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user->user_name.$mod_strings['ERR_PASSWORD_CHANGE_FAILED_3'];
718                     return false;
719                 }
720
721                 $old_user_hash = strtolower(md5($user_password));
722
723                 if (!$current_user->isAdminForModule('Users')) {
724                         //check old password first
725                         $query = "SELECT user_name FROM $this->table_name WHERE user_hash='$old_user_hash' AND id='$this->id'";
726                         $result = $this->db->query($query, true);
727                         $row = $this->db->fetchByAssoc($result);
728                         $GLOBALS['log']->debug("select old password query: $query");
729                         $GLOBALS['log']->debug("return result of $row");
730             if ($row == null) {
731                                 $GLOBALS['log']->warn("Incorrect old password for ".$this->user_name."");
732                                 $this->error_string = $mod_strings['ERR_PASSWORD_INCORRECT_OLD_1'].$this->user_name.$mod_strings['ERR_PASSWORD_INCORRECT_OLD_2'];
733                                 return false;
734                         }
735                 }
736
737         $user_hash = strtolower(md5($new_password));
738         $this->setPreference('loginexpiration','0');
739         //set new password
740         $now = TimeDate::getInstance()->nowDb();
741                 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='$system_generated', pwd_last_changed='$now' where id='$this->id'";
742                 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
743         $_SESSION['hasExpiredPassword'] = '0';
744                 return true;
745         }
746         
747         /**
748          * Check new password against rules set by admin
749          * @param string $password
750          * @return boolean
751          */
752         function check_password_rules($password) {
753             $length = mb_strlen($password);
754         
755             // Min length
756             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"]) && $GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"] > 0 && $length < $GLOBALS["sugar_config"]["passwordsetting"]["minpwdlength"]) {
757                 return false;
758             }
759         
760             // Max length
761             if(!empty($GLOBALS['sugar_config']['passwordsetting']['maxpwdlength']) && $GLOBALS['sugar_config']['passwordsetting']['maxpwdlength'] > 0 && $length > $GLOBALS['sugar_config']['passwordsetting']['maxpwdlength']) {
762                 return false;
763             }
764         
765             // One lower case
766             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onelower"]) && !preg_match('/[a-z]+/', $password)){
767                 return false;
768             }
769         
770             // One upper case
771             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["oneupper"]) && !preg_match('/[A-Z]+/', $password)){
772                 return false;
773             }
774         
775             // One number
776             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onenumber"]) && !preg_match('/[0-9]+/', $password)){
777                 return false;
778             }
779         
780             // One special character
781             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["onespecial"]) && !preg_match('/[|}{~!@#$%^&*()_+=-]+/', $password)){
782                 return false;
783             }
784         
785             // Custom regex
786             if(!empty($GLOBALS["sugar_config"]["passwordsetting"]["customregex"]) && !preg_match($GLOBALS["sugar_config"]["passwordsetting"]["customregex"], $password)){
787                 return false;
788             }
789         
790             return true;
791         }
792         
793         function is_authenticated() {
794                 return $this->authenticated;
795         }
796
797         function fill_in_additional_list_fields() {
798                 $this->fill_in_additional_detail_fields();
799         }
800
801         function fill_in_additional_detail_fields() {
802                 global $locale;
803
804                 $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";
805                 $result = $this->db->query($query, true, "Error filling in additional detail fields");
806
807                 $row = $this->db->fetchByAssoc($result);
808
809                 if ($row != null) {
810                         $this->reports_to_name = stripslashes($row['first_name'].' '.$row['last_name']);
811                 } else {
812                         $this->reports_to_name = '';
813                 }
814
815                 $this->_create_proper_name_field();
816         }
817
818         public function retrieve_user_id(
819             $user_name
820             )
821         {
822             $userFocus = new User;
823             $userFocus->retrieve_by_string_fields(array('user_name'=>$user_name));
824             if ( empty($userFocus->id) )
825                 return false;
826
827         return $userFocus->id;
828         }
829
830         /**
831          * @return -- returns a list of all users in the system.
832          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
833          * All Rights Reserved..
834          * Contributor(s): ______________________________________..
835          */
836         function verify_data($ieVerified=true) {
837                 global $mod_strings, $current_user;
838                 $verified = TRUE;
839
840                 if (!empty ($this->id)) {
841                         // Make sure the user doesn't report to themselves.
842                         $reports_to_self = 0;
843                         $check_user = $this->reports_to_id;
844                         $already_seen_list = array ();
845                         while (!empty ($check_user)) {
846                                 if (isset ($already_seen_list[$check_user])) {
847                                         // This user doesn't actually report to themselves
848                                         // But someone above them does.
849                                         $reports_to_self = 1;
850                                         break;
851                                 }
852                                 if ($check_user == $this->id) {
853                                         $reports_to_self = 1;
854                                         break;
855                                 }
856                                 $already_seen_list[$check_user] = 1;
857                                 $query = "SELECT reports_to_id FROM users WHERE id='".$this->db->quote($check_user)."'";
858                                 $result = $this->db->query($query, true, "Error checking for reporting-loop");
859                                 $row = $this->db->fetchByAssoc($result);
860                                 echo ("fetched: ".$row['reports_to_id']." from ".$check_user."<br>");
861                                 $check_user = $row['reports_to_id'];
862                         }
863
864                         if ($reports_to_self == 1) {
865                                 $this->error_string .= $mod_strings['ERR_REPORT_LOOP'];
866                                 $verified = FALSE;
867                         }
868                 }
869
870                 $query = "SELECT user_name from users where user_name='$this->user_name' AND deleted=0";
871                 if(!empty($this->id))$query .=  " AND id<>'$this->id'";
872                 $result = $this->db->query($query, true, "Error selecting possible duplicate users: ");
873                 $dup_users = $this->db->fetchByAssoc($result);
874
875                 if (!empty($dup_users)) {
876                         $this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'].$this->user_name.$mod_strings['ERR_USER_NAME_EXISTS_2'];
877                         $verified = FALSE;
878                 }
879
880                 if (is_admin($current_user)) {
881                     $remaining_admins = $this->db->getOne("SELECT COUNT(*) as c from users where is_admin = 1 AND deleted=0");
882
883                         if (($remaining_admins <= 1) && ($this->is_admin != '1') && ($this->id == $current_user->id)) {
884                                 $GLOBALS['log']->debug("Number of remaining administrator accounts: {$remaining_admins}");
885                                 $this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'].$this->user_name.$mod_strings['ERR_LAST_ADMIN_2'];
886                                 $verified = FALSE;
887                         }
888                 }
889                 ///////////////////////////////////////////////////////////////////////
890                 ////    InboundEmail verification failure
891                 if(!$ieVerified) {
892                         $verified = false;
893                         $this->error_string .= '<br />'.$mod_strings['ERR_EMAIL_NO_OPTS'];
894                 }
895
896                 return $verified;
897         }
898
899         function get_list_view_data() {
900
901                 global $current_user, $mod_strings;
902         // Bug #48555 Not User Name Format of User's locale.
903         $this->_create_proper_name_field();
904
905                 $user_fields = $this->get_list_view_array();
906                 if ($this->is_admin)
907                         $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
908                 elseif (!$this->is_admin) $user_fields['IS_ADMIN'] = '';
909                 if ($this->is_group)
910                         $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
911                 else
912                         $user_fields['IS_GROUP_IMAGE'] = '';
913
914
915         if ($this->is_admin) {
916                         $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',translate('LBL_CHECKMARK', 'Users'));
917         } elseif (!$this->is_admin) {
918               $user_fields['IS_ADMIN'] = '';
919         }
920
921         if ($this->is_group) {
922                 $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',translate('LBL_CHECKMARK', 'Users'));
923         } else {
924             $user_fields['NAME'] = empty ($this->name) ? '' : $this->name;
925         }
926
927                 $user_fields['REPORTS_TO_NAME'] = $this->reports_to_name;
928
929                 $user_fields['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this);
930
931                 return $user_fields;
932         }
933
934         function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
935                 return $list_form;
936         }
937
938
939
940         
941     /**
942      * getAllUsers
943      *
944      * Returns all active and inactive users
945      * @return Array of all users in the system
946      */
947
948     public static function getAllUsers()
949     {
950         $active_users = get_user_array(FALSE);
951         $inactive_users = get_user_array(FALSE, "Inactive");
952         $result = $active_users + $inactive_users;
953         asort($result);
954         return $result;
955     }
956
957         function create_export_query($order_by, $where) {
958                 include('modules/Users/field_arrays.php');
959
960                 $cols = '';
961                 foreach($fields_array['User']['export_fields'] as $field) {
962                         $cols .= (empty($cols)) ? '' : ', ';
963                         $cols .= $field;
964                 }
965
966                 $query = "SELECT {$cols} FROM users ";
967
968                 $where_auto = " users.deleted = 0";
969
970                 if ($where != "")
971                         $query .= " WHERE $where AND ".$where_auto;
972                 else
973                         $query .= " WHERE ".$where_auto;
974
975                 // admin for module user is not be able to export a super-admin
976                 global $current_user;
977                 if(!$current_user->is_admin){
978                         $query .= " AND users.is_admin=0";
979                 }
980
981                 if ($order_by != "")
982                         $query .= " ORDER BY $order_by";
983                 else
984                         $query .= " ORDER BY users.user_name";
985
986                 return $query;
987         }
988
989         /** Returns a list of the associated users
990          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
991          * All Rights Reserved..
992          * Contributor(s): ______________________________________..
993         */
994         function get_meetings() {
995                 // First, get the list of IDs.
996                 $query = "SELECT meeting_id as id from meetings_users where user_id='$this->id' AND deleted=0";
997                 return $this->build_related_list($query, new Meeting());
998         }
999         function get_calls() {
1000                 // First, get the list of IDs.
1001                 $query = "SELECT call_id as id from calls_users where user_id='$this->id' AND deleted=0";
1002                 return $this->build_related_list($query, new Call());
1003         }
1004
1005         /**
1006          * generates Javascript to display I-E mail counts, both personal and group
1007          */
1008         function displayEmailCounts() {
1009                 global $theme;
1010                 $new = translate('LBL_NEW', 'Emails');
1011                 $default = 'index.php?module=Emails&action=ListView&assigned_user_id='.$this->id;
1012                 $count = '';
1013                 $verts = array('Love', 'Links', 'Pipeline', 'RipCurl', 'SugarLite');
1014
1015                 if($this->hasPersonalEmail()) {
1016                         $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\'');
1017                         $a = $this->db->fetchByAssoc($r);
1018                         if(in_array($theme, $verts)) {
1019                                 $count .= '<br />';
1020                         } else {
1021                                 $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
1022                         }
1023                         $count .= '<a href='.$default.'&type=inbound>'.translate('LBL_LIST_TITLE_MY_INBOX', 'Emails').': ('.$a['c'].' '.$new.')</a>';
1024
1025                         if(!in_array($theme, $verts)) {
1026                                 $count .= ' - ';
1027                         }
1028                 }
1029
1030                 $r = $this->db->query('SELECT id FROM users WHERE users.is_group = 1 AND deleted = 0');
1031                 $groupIds = '';
1032                 $groupNew = '';
1033                 while($a = $this->db->fetchByAssoc($r)) {
1034                         if($groupIds != '') {$groupIds .= ', ';}
1035                         $groupIds .= "'".$a['id']."'";
1036                 }
1037
1038                 $total = 0;
1039                 if(strlen($groupIds) > 0) {
1040                         $groupQuery = 'SELECT count(*) AS c FROM emails ';
1041                         $groupQuery .= ' WHERE emails.deleted=0 AND emails.assigned_user_id IN ('.$groupIds.') AND emails.type = \'inbound\' AND emails.status = \'unread\'';
1042                         $r = $this->db->query($groupQuery);
1043                         if(is_resource($r)) {
1044                                 $a = $this->db->fetchByAssoc($r);
1045                                 if($a['c'] > 0) {
1046                                         $total = $a['c'];
1047                                 }
1048                         }
1049                 }
1050                 if(in_array($theme, $verts)) $count .= '<br />';
1051                 if(empty($count)) $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
1052                 $count .= '<a href=index.php?module=Emails&action=ListViewGroup>'.translate('LBL_LIST_TITLE_GROUP_INBOX', 'Emails').': ('.$total.' '.$new.')</a>';
1053
1054                 $out  = '<script type="text/javascript" language="Javascript">';
1055                 $out .= 'var welcome = document.getElementById("welcome");';
1056                 $out .= 'var welcomeContent = welcome.innerHTML;';
1057                 $out .= 'welcome.innerHTML = welcomeContent + "'.$count.'";';
1058                 $out .= '</script>';
1059
1060                 echo $out;
1061         }
1062
1063         function getPreferredEmail() {
1064                 $ret = array ();
1065                 $nameEmail = $this->getUsersNameAndEmail();
1066                 $prefAddr = $nameEmail['email'];
1067                 $fullName = $nameEmail['name'];
1068                 if (empty ($prefAddr)) {
1069                         $nameEmail = $this->getSystemDefaultNameAndEmail();
1070                         $prefAddr = $nameEmail['email'];
1071                         $fullName = $nameEmail['name'];
1072                 } // if
1073                 $fullName = from_html($fullName);
1074                 $ret['name'] = $fullName;
1075                 $ret['email'] = $prefAddr;
1076                 return $ret;
1077         }
1078
1079         function getUsersNameAndEmail()
1080         {
1081             // Bug #48555 Not User Name Format of User's locale.
1082             $this->_create_proper_name_field();
1083
1084                 $prefAddr = $this->emailAddress->getPrimaryAddress($this);
1085
1086                 if (empty ($prefAddr)) {
1087                         $prefAddr = $this->emailAddress->getReplyToAddress($this);
1088                 }
1089                 return array('email' => $prefAddr , 'name' => $this->name);
1090
1091         } // fn
1092
1093         function getSystemDefaultNameAndEmail() {
1094
1095                 $email = new Email();
1096                 $return = $email->getSystemDefaultEmail();
1097                 $prefAddr = $return['email'];
1098                 $fullName = $return['name'];
1099                 return array('email' => $prefAddr , 'name' => $fullName);
1100         } // fn
1101
1102         /**
1103          * sets User email default in config.php if not already set by install - i.
1104          * e., upgrades
1105          */
1106         function setDefaultsInConfig() {
1107                 global $sugar_config;
1108                 $sugar_config['email_default_client'] = 'sugar';
1109                 $sugar_config['email_default_editor'] = 'html';
1110                 ksort($sugar_config);
1111                 write_array_to_file('sugar_config', $sugar_config, 'config.php');
1112                 return $sugar_config;
1113         }
1114
1115     /**
1116      * returns User's email address based on descending order of preferences
1117      *
1118      * @param string id GUID of target user if needed
1119      * @return array Assoc array for an email and name
1120      */
1121     function getEmailInfo($id='') {
1122         $user = $this;
1123         if(!empty($id)) {
1124             $user = new User();
1125             $user->retrieve($id);
1126         }
1127
1128         // from name
1129         $fromName = $user->getPreference('mail_fromname');
1130         if(empty($fromName)) {
1131                 // cn: bug 8586 - localized name format
1132             $fromName = $user->full_name;
1133         }
1134
1135         // from address
1136         $fromaddr = $user->getPreference('mail_fromaddress');
1137         if(empty($fromaddr)) {
1138             if(!empty($user->email1) && isset($user->email1)) {
1139                 $fromaddr = $user->email1;
1140             } elseif(!empty($user->email2) && isset($user->email2)) {
1141                 $fromaddr = $user->email2;
1142             } else {
1143                 $r = $user->db->query("SELECT value FROM config WHERE name = 'fromaddress'");
1144                 $a = $user->db->fetchByAssoc($r);
1145                 $fromddr = $a['value'];
1146             }
1147         }
1148
1149         $ret['name'] = $fromName;
1150         $ret['email'] = $fromaddr;
1151
1152         return $ret;
1153     }
1154
1155         /**
1156          * returns opening <a href=xxxx for a contact, account, etc
1157          * cascades from User set preference to System-wide default
1158          * @return string       link
1159          * @param attribute the email addy
1160          * @param focus the parent bean
1161          * @param contact_id
1162          * @param return_module
1163          * @param return_action
1164          * @param return_id
1165          * @param class
1166          */
1167         function getEmailLink2($emailAddress, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1168                 $emailLink = '';
1169                 global $sugar_config;
1170
1171                 if(!isset($sugar_config['email_default_client'])) {
1172                         $this->setDefaultsInConfig();
1173                 }
1174
1175                 $userPref = $this->getPreference('email_link_type');
1176                 $defaultPref = $sugar_config['email_default_client'];
1177                 if($userPref != '') {
1178                         $client = $userPref;
1179                 } else {
1180                         $client = $defaultPref;
1181                 }
1182
1183                 if($client == 'sugar') {
1184                         $email = '';
1185                         $to_addrs_ids = '';
1186                         $to_addrs_names = '';
1187                         $to_addrs_emails = '';
1188
1189                         $fullName = !empty($focus->name) ? $focus->name : '';
1190
1191                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1192                         if(empty($ret_id)) $ret_id = $focus->id;
1193                         if($focus->object_name == 'Contact') {
1194                                 $contact_id = $focus->id;
1195                                 $to_addrs_ids = $focus->id;
1196                                 // Bug #48555 Not User Name Format of User's locale.
1197                                 $focus->_create_proper_name_field();
1198                             $fullName = $focus->name;
1199                             $to_addrs_names = $fullName;
1200                                 $to_addrs_emails = $focus->email1;
1201                         }
1202
1203                         $emailLinkUrl = 'contact_id='.$contact_id.
1204                                 '&parent_type='.$focus->module_dir.
1205                                 '&parent_id='.$focus->id.
1206                                 '&parent_name='.urlencode($fullName).
1207                                 '&to_addrs_ids='.$to_addrs_ids.
1208                                 '&to_addrs_names='.urlencode($to_addrs_names).
1209                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1210                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $emailAddress . '&gt;').
1211                                 '&return_module='.$ret_module.
1212                                 '&return_action='.$ret_action.
1213                                 '&return_id='.$ret_id;
1214
1215                 //Generate the compose package for the quick create options.
1216                 //$json = getJSONobj();
1217                 //$composeOptionsLink = $json->encode( array('composeOptionsLink' => $emailLinkUrl,'id' => $focus->id) );
1218                         require_once('modules/Emails/EmailUI.php');
1219             $eUi = new EmailUI();
1220             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1221
1222                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1223
1224                 } else {
1225                         // straight mailto:
1226                         $emailLink = '<a href="mailto:'.$emailAddress.'" class="'.$class.'">';
1227                 }
1228
1229                 return $emailLink;
1230         }
1231
1232         /**
1233          * returns opening <a href=xxxx for a contact, account, etc
1234          * cascades from User set preference to System-wide default
1235          * @return string       link
1236          * @param attribute the email addy
1237          * @param focus the parent bean
1238          * @param contact_id
1239          * @param return_module
1240          * @param return_action
1241          * @param return_id
1242          * @param class
1243          */
1244         function getEmailLink($attribute, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1245             $emailLink = '';
1246                 global $sugar_config;
1247
1248                 if(!isset($sugar_config['email_default_client'])) {
1249                         $this->setDefaultsInConfig();
1250                 }
1251
1252                 $userPref = $this->getPreference('email_link_type');
1253                 $defaultPref = $sugar_config['email_default_client'];
1254                 if($userPref != '') {
1255                         $client = $userPref;
1256                 } else {
1257                         $client = $defaultPref;
1258                 }
1259
1260                 if($client == 'sugar') {
1261                         $email = '';
1262                         $to_addrs_ids = '';
1263                         $to_addrs_names = '';
1264                         $to_addrs_emails = '';
1265
1266             $fullName = !empty($focus->name) ? $focus->name : '';
1267
1268                         if(!empty($focus->$attribute)) {
1269                                 $email = $focus->$attribute;
1270                         }
1271
1272
1273                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1274                         if(empty($ret_id)) $ret_id = $focus->id;
1275                         if($focus->object_name == 'Contact') {
1276                                 // Bug #48555 Not User Name Format of User's locale.
1277                                 $focus->_create_proper_name_field();
1278                             $fullName = $focus->name;
1279                             $contact_id = $focus->id;
1280                                 $to_addrs_ids = $focus->id;
1281                                 $to_addrs_names = $fullName;
1282                                 $to_addrs_emails = $focus->email1;
1283                         }
1284
1285                         $emailLinkUrl = 'contact_id='.$contact_id.
1286                                 '&parent_type='.$focus->module_dir.
1287                                 '&parent_id='.$focus->id.
1288                                 '&parent_name='.urlencode($fullName).
1289                                 '&to_addrs_ids='.$to_addrs_ids.
1290                                 '&to_addrs_names='.urlencode($to_addrs_names).
1291                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1292                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $email . '&gt;').
1293                                 '&return_module='.$ret_module.
1294                                 '&return_action='.$ret_action.
1295                                 '&return_id='.$ret_id;
1296
1297                         //Generate the compose package for the quick create options.
1298                 require_once('modules/Emails/EmailUI.php');
1299             $eUi = new EmailUI();
1300             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1301                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1302
1303                 } else {
1304                         // straight mailto:
1305                         $emailLink = '<a href="mailto:'.$focus->$attribute.'" class="'.$class.'">';
1306                 }
1307
1308                 return $emailLink;
1309         }
1310
1311
1312         /**
1313          * gets a human-readable explanation of the format macro
1314          * @return string Human readable name format
1315          */
1316         function getLocaleFormatDesc() {
1317                 global $locale;
1318                 global $mod_strings;
1319                 global $app_strings;
1320
1321                 $format['f'] = $mod_strings['LBL_LOCALE_DESC_FIRST'];
1322                 $format['l'] = $mod_strings['LBL_LOCALE_DESC_LAST'];
1323                 $format['s'] = $mod_strings['LBL_LOCALE_DESC_SALUTATION'];
1324                 $format['t'] = $mod_strings['LBL_LOCALE_DESC_TITLE'];
1325
1326                 $name['f'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
1327                 $name['l'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
1328                 $name['s'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
1329                 $name['t'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
1330
1331                 $macro = $locale->getLocaleFormatMacro();
1332
1333                 $ret1 = '';
1334                 $ret2 = '';
1335                 for($i=0; $i<strlen($macro); $i++) {
1336                         if(array_key_exists($macro{$i}, $format)) {
1337                                 $ret1 .= "<i>".$format[$macro{$i}]."</i>";
1338                                 $ret2 .= "<i>".$name[$macro{$i}]."</i>";
1339                         } else {
1340                                 $ret1 .= $macro{$i};
1341                                 $ret2 .= $macro{$i};
1342                         }
1343                 }
1344                 return $ret1."<br />".$ret2;
1345         }
1346
1347
1348     /*
1349      *
1350      * Here are the multi level admin access check functions.
1351      *
1352      */
1353     /**
1354      * Helper function to remap some modules around ACL wise
1355      *
1356      * @return string
1357      */
1358     protected function _fixupModuleForACL($module) {
1359         if($module=='ContractTypes') {
1360             $module = 'Contracts';
1361         }
1362         if(preg_match('/Product[a-zA-Z]*/',$module)) {
1363             $module = 'Products';
1364         }
1365
1366         return $module;
1367     }
1368     /**
1369      * Helper function that enumerates the list of modules and checks if they are an admin/dev.
1370      * The code was just too similar to copy and paste.
1371      *
1372      * @return array
1373      */
1374     protected function _getModulesForACL($type='dev'){
1375         $isDev = $type=='dev';
1376         $isAdmin = $type=='admin';
1377
1378         global $beanList;
1379         $myModules = array();
1380
1381         if (!is_array($beanList) ) {
1382             return $myModules;
1383         }
1384
1385         // These modules don't take kindly to the studio trying to play about with them.
1386         static $ignoredModuleList = array('iFrames','Feeds','Home','Dashboard','Calendar','Activities','Reports');
1387
1388
1389         $actions = ACLAction::getUserActions($this->id);
1390
1391         foreach ($beanList as $module=>$val) {
1392             // Remap the module name
1393             $module = $this->_fixupModuleForACL($module);
1394             if (in_array($module,$myModules)) {
1395                 // Already have the module in the list
1396                 continue;
1397             }
1398             if (in_array($module,$ignoredModuleList)) {
1399                 // You can't develop on these modules.
1400                 continue;
1401             }
1402
1403             $key = 'module';
1404
1405             if (($this->isAdmin() && isset($actions[$module][$key]))
1406                 ) {
1407                 $myModules[] = $module;
1408             }
1409         }
1410
1411         return $myModules;
1412     }
1413     /**
1414      * Is this user a system wide admin
1415      *
1416      * @return bool
1417      */
1418     public function isAdmin() {
1419         if(isset($this->is_admin)
1420            &&($this->is_admin == '1' || $this->is_admin === 'on')){
1421             return true;
1422         }
1423         return false;
1424     }
1425     /**
1426      * Is this user a developer for any module
1427      *
1428      * @return bool
1429      */
1430     public function isDeveloperForAnyModule() {
1431         if ($this->isAdmin()) {
1432             return true;
1433         }
1434         return false;
1435     }
1436     /**
1437      * List the modules a user has developer access to
1438      *
1439      * @return array
1440      */
1441     public function getDeveloperModules() {
1442         static $developerModules;
1443         if (!isset($_SESSION[$this->user_name.'_get_developer_modules_for_user']) ) {
1444             $_SESSION[$this->user_name.'_get_developer_modules_for_user'] = $this->_getModulesForACL('dev');
1445         }
1446
1447         return $_SESSION[$this->user_name.'_get_developer_modules_for_user'];
1448     }
1449     /**
1450      * Is this user a developer for the specified module
1451      *
1452      * @return bool
1453      */
1454     public function isDeveloperForModule($module) {
1455         if ($this->isAdmin()) {
1456             return true;
1457         }
1458
1459         $devModules = $this->getDeveloperModules();
1460
1461         $module = $this->_fixupModuleForACL($module);
1462
1463         if (in_array($module,$devModules) ) {
1464             return true;
1465         }
1466
1467         return false;
1468     }
1469     /**
1470      * List the modules a user has admin access to
1471      *
1472      * @return array
1473      */
1474     public function getAdminModules() {
1475         if (!isset($_SESSION[$this->user_name.'_get_admin_modules_for_user']) ) {
1476             $_SESSION[$this->user_name.'_get_admin_modules_for_user'] = $this->_getModulesForACL('admin');
1477         }
1478
1479         return $_SESSION[$this->user_name.'_get_admin_modules_for_user'];
1480     }
1481     /**
1482      * Is this user an admin for the specified module
1483      *
1484      * @return bool
1485      */
1486     public function isAdminForModule($module) {
1487         if ($this->isAdmin()) {
1488             return true;
1489         }
1490
1491         $adminModules = $this->getAdminModules();
1492
1493         $module = $this->_fixupModuleForACL($module);
1494
1495         if (in_array($module,$adminModules) ) {
1496             return true;
1497         }
1498
1499         return false;
1500     }
1501         /**
1502          * Whether or not based on the user's locale if we should show the last name first.
1503          *
1504          * @return bool
1505          */
1506         public function showLastNameFirst(){
1507                 global $locale;
1508         $localeFormat = $locale->getLocaleFormatMacro($this);
1509                 if ( strpos($localeFormat,'l') > strpos($localeFormat,'f') ) {
1510                     return false;
1511         }else {
1512                 return true;
1513         }
1514         }
1515
1516
1517
1518    function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false)
1519    {    //call parent method, specifying for array to be returned
1520         $ret_array = parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, true,$parentbean, $singleSelect);
1521
1522         //if this is being called from webservices, then run additional code
1523         if(!empty($GLOBALS['soap_server_object'])){
1524
1525                 //if this is a single select, then secondary queries are being run that may result in duplicate rows being returned through the
1526                 //left joins with meetings/tasks/call.  We need to change the left joins to include a null check (bug 40250)
1527                 if($singleSelect)
1528                 {
1529                         //retrieve the 'from' string and make lowercase for easier manipulation
1530                         $left_str = strtolower($ret_array['from']);
1531                         $lefts = explode('left join', $left_str);
1532                         $new_left_str = '';
1533
1534                         //explode on the left joins and process each one
1535                         foreach($lefts as $ljVal){
1536                                 //grab the join alias
1537                                 $onPos = strpos( $ljVal, ' on');
1538                                 if($onPos === false){
1539                                         $new_left_str .=' '.$ljVal.' ';
1540                                         continue;
1541                                 }
1542                                 $spacePos = strrpos(substr($ljVal, 0, $onPos),' ');
1543                                 $alias = substr($ljVal,$spacePos,$onPos-$spacePos);
1544
1545                                 //add null check to end of the Join statement
1546                         // Bug #46390 to use id_c field instead of id field for custom tables
1547                         if(substr($alias, -5) != '_cstm')
1548                         {
1549                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id is null ';
1550                         }
1551                         else
1552                         {
1553                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id_c is null ';
1554                         }
1555
1556                                 //add statement into new string
1557                                 $new_left_str .= $ljVal;
1558                          }
1559                          //replace the old string with the new one
1560                          $ret_array['from'] = $new_left_str;
1561                 }
1562         }
1563
1564                 //return array or query string
1565                 if($return_array)
1566         {
1567                 return $ret_array;
1568         }
1569
1570         return  $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
1571
1572
1573
1574    }
1575
1576     /**
1577      * Get user first day of week.
1578      *
1579      * @param [User] $user user object, current user if not specified
1580      * @return int : 0 = Sunday, 1 = Monday, etc...
1581      */
1582     public function get_first_day_of_week()
1583     {
1584         $fdow = $this->getPreference('fdow');
1585         if (empty($fdow))
1586         {
1587             $fdow = 0;
1588         }
1589
1590         return $fdow;
1591     }
1592
1593     /**
1594      * Method for password generation
1595      *
1596      * @static
1597      * @return string password
1598      */
1599     public static function generatePassword()
1600     {
1601         $res = $GLOBALS['sugar_config']['passwordsetting'];
1602         $charBKT = '';
1603         //chars to select from
1604         $LOWERCASE = "abcdefghijklmnpqrstuvwxyz";
1605         $NUMBER = "0123456789";
1606         $UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1607         $SPECIAL = '~!@#$%^&*()_+=-{}|';
1608         $condition = 0;
1609         $charBKT .= $UPPERCASE . $LOWERCASE . $NUMBER;
1610         $password = "";
1611             $length = '6';
1612
1613         // Create random characters for the ones that doesnt have requirements
1614         for ($i=0; $i < $length - $condition; $i ++)  // loop and create password
1615         {
1616             $password = $password . substr ($charBKT, rand() % strlen($charBKT), 1);
1617         }
1618
1619         return $password;
1620     }
1621
1622     /**
1623      * Send new password or link to user
1624      *
1625      * @param string $templateId Id of email template
1626      * @param array $additionalData additional params: link, url, password
1627      * @return array status: true|false, message: error message, if status = false and message = '' it means that send method has returned false
1628      */
1629     public function sendEmailForPassword($templateId, array $additionalData = array())
1630     {
1631         global $sugar_config, $current_user;
1632         $mod_strings = return_module_language('', 'Users');
1633         $result = array(
1634             'status' => false,
1635             'message' => ''
1636         );
1637
1638         $emailTemp = new EmailTemplate();
1639         $emailTemp->disable_row_level_security = true;
1640         if ($emailTemp->retrieve($templateId) == '')
1641         {
1642             $result['message'] = $mod_strings['LBL_EMAIL_TEMPLATE_MISSING'];
1643             return $result;
1644         }
1645
1646         //replace instance variables in email templates
1647         $htmlBody = $emailTemp->body_html;
1648         $body = $emailTemp->body;
1649         if (isset($additionalData['link']) && $additionalData['link'] == true)
1650         {
1651             $htmlBody = str_replace('$contact_user_link_guid', $additionalData['url'], $htmlBody);
1652             $body = str_replace('$contact_user_link_guid', $additionalData['url'], $body);
1653         }
1654         else
1655         {
1656             $htmlBody = str_replace('$contact_user_user_hash', $additionalData['password'], $htmlBody);
1657             $body = str_replace('$contact_user_user_hash', $additionalData['password'], $body);
1658         }
1659         // Bug 36833 - Add replacing of special value $instance_url
1660         $htmlBody = str_replace('$config_site_url', $sugar_config['site_url'], $htmlBody);
1661         $body = str_replace('$config_site_url', $sugar_config['site_url'], $body);
1662
1663         $htmlBody = str_replace('$contact_user_user_name', $this->user_name, $htmlBody);
1664         $htmlBody = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $htmlBody);
1665         $body = str_replace('$contact_user_user_name', $this->user_name, $body);
1666         $body = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $body);
1667         $emailTemp->body_html = $htmlBody;
1668         $emailTemp->body = $body;
1669
1670         $itemail = $this->emailAddress->getPrimaryAddress($this);
1671         //retrieve IT Admin Email
1672         //_ppd( $emailTemp->body_html);
1673         //retrieve email defaults
1674         $emailObj = new Email();
1675         $defaults = $emailObj->getSystemDefaultEmail();
1676         require_once('include/SugarPHPMailer.php');
1677         $mail = new SugarPHPMailer();
1678         $mail->setMailerForSystem();
1679         //$mail->IsHTML(true);
1680         $mail->From = $defaults['email'];
1681         $mail->FromName = $defaults['name'];
1682         $mail->ClearAllRecipients();
1683         $mail->ClearReplyTos();
1684         $mail->Subject = from_html($emailTemp->subject);
1685         if ($emailTemp->text_only != 1)
1686         {
1687             $mail->IsHTML(true);
1688             $mail->Body = from_html($emailTemp->body_html);
1689             $mail->AltBody = from_html($emailTemp->body);
1690         }
1691         else
1692         {
1693             $mail->Body_html = from_html($emailTemp->body_html);
1694             $mail->Body = from_html($emailTemp->body);
1695         }
1696         if ($mail->Body == '' && $current_user->is_admin)
1697         {
1698             global $app_strings;
1699             $result['message'] = $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT'];
1700             return $result;
1701         }
1702         if ($mail->Mailer == 'smtp' && $mail->Host =='' && $current_user->is_admin)
1703         {
1704             $result['message'] = $mod_strings['ERR_SERVER_SMTP_EMPTY'];
1705             return $result;
1706         }
1707
1708         $mail->prepForOutbound();
1709         $hasRecipients = false;
1710
1711         if (!empty($itemail))
1712         {
1713             if ($hasRecipients)
1714             {
1715                 $mail->AddBCC($itemail);
1716             }
1717             else
1718             {
1719                 $mail->AddAddress($itemail);
1720             }
1721             $hasRecipients = true;
1722         }
1723         if ($hasRecipients)
1724         {
1725             $result['status'] = @$mail->Send();
1726         }
1727
1728         if ($result['status'] == true)
1729         {
1730             $emailObj->team_id = 1;
1731             $emailObj->to_addrs = '';
1732             $emailObj->type = 'archived';
1733             $emailObj->deleted = '0';
1734             $emailObj->name = $mail->Subject ;
1735             $emailObj->description = $mail->Body;
1736             $emailObj->description_html = null;
1737             $emailObj->from_addr = $mail->From;
1738             $emailObj->parent_type = 'User';
1739             $emailObj->date_sent = TimeDate::getInstance()->nowDb();
1740             $emailObj->modified_user_id = '1';
1741             $emailObj->created_by = '1';
1742             $emailObj->status = 'sent';
1743             $emailObj->save();
1744             if (!isset($additionalData['link']) || $additionalData['link'] == false)
1745             {
1746                 $user_hash = strtolower(md5($additionalData['password']));
1747                 $this->setPreference('loginexpiration', '0');
1748                 $this->setPreference('lockout', '');
1749                 $this->setPreference('loginfailed', '0');
1750                 $this->savePreferencesToDB();
1751                 //set new password
1752                 $now=TimeDate::getInstance()->nowDb();
1753                 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='1', pwd_last_changed='$now' where id='$this->id'";
1754                 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
1755             }
1756         }
1757
1758         return $result;
1759     }
1760
1761     // Bug #48014 Must to send password to imported user if this action is required
1762     function afterImportSave()
1763     {
1764         if(
1765             $this->user_hash == false
1766             && !$this->is_group
1767             && !$this->portal_only
1768             && isset($GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON'])
1769             && $GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON']
1770         )
1771         {
1772             $backUpPost = $_POST;
1773             $_POST = array(
1774                 'userId' => $this->id
1775             );
1776             ob_start();
1777             require('modules/Users/GeneratePassword.php');
1778             $result = ob_get_clean();
1779             $_POST = $backUpPost;
1780             return $result == true;
1781         }
1782     }
1783 }