]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Users/User.php
Release 6.3.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-2011 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         function save($check_notify = false) {
417                 $isUpdate = !empty($this->id) && !$this->new_with_id;
418
419
420                 $query = "SELECT count(id) as total from users WHERE status='Active' AND deleted=0 AND is_group=0 AND portal_only=0";
421
422
423                 // wp: do not save user_preferences in this table, see user_preferences module
424                 $this->user_preferences = '';
425
426                 // if this is an admin user, do not allow is_group or portal_only flag to be set.
427                 if ($this->is_admin) {
428                         $this->is_group = 0;
429                         $this->portal_only = 0;
430                 }
431
432
433
434
435
436                 parent::save($check_notify);
437
438
439
440         $this->savePreferencesToDB();
441         return $this->id;
442         }
443
444         /**
445         * @return boolean true if the user is a member of the role_name, false otherwise
446         * @param string $role_name - Must be the exact name of the acl_role
447         * @param string $user_id - The user id to check for the role membership, empty string if current user
448         * @desc Determine whether or not a user is a member of an ACL Role. This function caches the
449         *       results in the session or to prevent running queries after the first time executed.
450         * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
451         * All Rights Reserved..
452         * Contributor(s): ______________________________________..
453         */
454         function check_role_membership($role_name, $user_id = ''){
455
456                 global $current_user;
457
458                 if(empty($user_id))
459                         $user_id = $current_user->id;
460
461                 // Check the Sugar External Cache to see if this users memberships were cached
462                 $role_array = sugar_cache_retrieve("RoleMemberships_".$user_id);
463
464                 // If we are pulling the roles for the current user
465                 if($user_id == $current_user->id){
466                         // If the Session doesn't contain the values
467                         if(!isset($_SESSION['role_memberships'])){
468                                 // This means the external cache already had it loaded
469                                 if(!empty($role_array))
470                                         $_SESSION['role_memberships'] = $role_array;
471                                 else{
472                                         $_SESSION['role_memberships'] = ACLRole::getUserRoleNames($user_id);
473                                         $role_array = $_SESSION['role_memberships'];
474                                 }
475                         }
476                         // else the session had the values, so we assign to the role array
477                         else{
478                                 $role_array = $_SESSION['role_memberships'];
479                         }
480                 }
481                 else{
482                         // If the external cache didn't contain the values, we get them and put them in cache
483                         if(!$role_array){
484                                 $role_array = ACLRole::getUserRoleNames($user_id);
485                                 sugar_cache_put("RoleMemberships_".$user_id, $role_array);
486                         }
487                 }
488
489                 // If the role doesn't exist in the list of the user's roles
490                 if(!empty($role_array) && in_array($role_name, $role_array))
491                         return true;
492                 else
493                         return false;
494         }
495
496     function get_summary_text() {
497         //$this->_create_proper_name_field();
498         return $this->name;
499         }
500
501         /**
502         * @return string encrypted password for storage in DB and comparison against DB password.
503         * @param string $user_name - Must be non null and at least 2 characters
504         * @param string $user_password - Must be non null and at least 1 character.
505         * @desc Take an unencrypted username and password and return the encrypted password
506          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
507          * All Rights Reserved..
508          * Contributor(s): ______________________________________..
509         */
510         function encrypt_password($user_password) {
511                 // encrypt the password.
512                 $salt = substr($this->user_name, 0, 2);
513                 $encrypted_password = crypt($user_password, $salt);
514
515                 return $encrypted_password;
516         }
517
518         /**
519          * Authenicates the user; returns true if successful
520          *
521          * @param $password
522          * @return bool
523          */
524         public function authenticate_user(
525             $password
526             )
527         {
528                 $password = $GLOBALS['db']->quote($password);
529                 $user_name = $GLOBALS['db']->quote($this->user_name);
530                 $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') ";
531                 //$result = $this->db->requireSingleResult($query, false);
532                 $result = $this->db->limitQuery($query,0,1,false);
533                 $a = $this->db->fetchByAssoc($result);
534                 // set the ID in the seed user.  This can be used for retrieving the full user record later
535                 if (empty ($a)) {
536                         // already logging this in load_user() method
537                         //$GLOBALS['log']->fatal("SECURITY: failed login by $this->user_name");
538                         return false;
539                 } else {
540                         $this->id = $a['id'];
541                         return true;
542                 }
543         }
544
545     /**
546      * retrieves an User bean
547      * preformat name & full_name attribute with first/last
548      * loads User's preferences
549      *
550      * @param string id ID of the User
551      * @param bool encode encode the result
552      * @return object User bean
553      * @return null null if no User found
554      */
555         function retrieve($id, $encode = true) {
556                 $ret = parent::retrieve($id, $encode);
557                 if ($ret) {
558                         if (isset ($_SESSION)) {
559                                 $this->loadPreferences();
560                         }
561                 }
562                 return $ret;
563         }
564
565         function retrieve_by_email_address($email) {
566
567                 $email1= strtoupper($email);
568                 $q=<<<EOQ
569
570                 select id from users where id in ( SELECT  er.bean_id AS id FROM email_addr_bean_rel er,
571                         email_addresses ea WHERE ea.id = er.email_address_id
572                     AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = 'Users' AND email_address_caps IN ('{$email}') )
573 EOQ;
574
575
576                 $res=$this->db->query($q);
577                 $row=$this->db->fetchByAssoc($res);
578
579                 if (!empty($row['id'])) {
580                         return $this->retrieve($row['id']);
581                 }
582                 return '';
583         }
584
585    function bean_implements($interface) {
586         switch($interface){
587             case 'ACL':return true;
588         }
589         return false;
590     }
591
592
593         /**
594          * Load a user based on the user_name in $this
595          * @return -- this if load was successul and null if load failed.
596          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
597          * All Rights Reserved..
598          * Contributor(s): ______________________________________..
599          */
600         function load_user($user_password) {
601                 global $login_error;
602                 unset($GLOBALS['login_error']);
603                 if(isset ($_SESSION['loginattempts'])) {
604                         $_SESSION['loginattempts'] += 1;
605                 } else {
606                         $_SESSION['loginattempts'] = 1;
607                 }
608                 if($_SESSION['loginattempts'] > 5) {
609                         $GLOBALS['log']->fatal('SECURITY: '.$this->user_name.' has attempted to login '.$_SESSION['loginattempts'].' times from IP address: '.$_SERVER['REMOTE_ADDR'].'.');
610                 }
611
612                 $GLOBALS['log']->debug("Starting user load for $this->user_name");
613
614                 if (!isset ($this->user_name) || $this->user_name == "" || !isset ($user_password) || $user_password == "")
615                         return null;
616
617                 $user_hash = strtolower(md5($user_password));
618                 if($this->authenticate_user($user_hash)) {
619                         $query = "SELECT * from $this->table_name where id='$this->id'";
620                 } else {
621                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed');
622                         return null;
623                 }
624                 $r = $this->db->limitQuery($query, 0, 1, false);
625                 $a = $this->db->fetchByAssoc($r);
626                 if(empty($a) || !empty ($GLOBALS['login_error'])) {
627                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed - could not Load User from Database');
628                         return null;
629                 }
630
631                 // Get the fields for the user
632                 $row = $a;
633
634                 // If there is no user_hash is not present or is out of date, then create a new one.
635                 if (!isset ($row['user_hash']) || $row['user_hash'] != $user_hash) {
636                         $query = "UPDATE $this->table_name SET user_hash='$user_hash' where id='{$row['id']}'";
637                         $this->db->query($query, true, "Error setting new hash for {$row['user_name']}: ");
638                 }
639
640                 // now fill in the fields.
641                 foreach ($this->column_fields as $field) {
642                         $GLOBALS['log']->info($field);
643
644                         if (isset ($row[$field])) {
645                                 $GLOBALS['log']->info("=".$row[$field]);
646
647                                 $this-> $field = $row[$field];
648                         }
649                 }
650
651                 $this->loadPreferences();
652
653
654                 require_once ('modules/Versions/CheckVersions.php');
655                 $invalid_versions = get_invalid_versions();
656
657                 if (!empty ($invalid_versions)) {
658                         if (isset ($invalid_versions['Rebuild Relationships'])) {
659                                 unset ($invalid_versions['Rebuild Relationships']);
660
661                                 // flag for pickup in DisplayWarnings.php
662                                 $_SESSION['rebuild_relationships'] = true;
663                         }
664
665                         if (isset ($invalid_versions['Rebuild Extensions'])) {
666                                 unset ($invalid_versions['Rebuild Extensions']);
667
668                                 // flag for pickup in DisplayWarnings.php
669                                 $_SESSION['rebuild_extensions'] = true;
670                         }
671
672                         $_SESSION['invalid_versions'] = $invalid_versions;
673                 }
674                 $this->fill_in_additional_detail_fields();
675                 if ($this->status != "Inactive")
676                         $this->authenticated = true;
677
678                 unset ($_SESSION['loginattempts']);
679                 return $this;
680         }
681
682         /**
683          * Verify that the current password is correct and write the new password to the DB.
684          *
685          * @param string $user name - Must be non null and at least 1 character.
686          * @param string $user_password - Must be non null and at least 1 character.
687          * @param string $new_password - Must be non null and at least 1 character.
688          * @return boolean - If passwords pass verification and query succeeds, return true, else return false.
689          */
690         function change_password(
691             $user_password,
692             $new_password,
693             $system_generated = '0'
694             )
695         {
696             global $mod_strings;
697                 global $current_user;
698                 $GLOBALS['log']->debug("Starting password change for $this->user_name");
699
700                 if (!isset ($new_password) || $new_password == "") {
701                         $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user['user_name'].$mod_strings['ERR_PASSWORD_CHANGE_FAILED_2'];
702                         return false;
703                 }
704
705                 $old_user_hash = strtolower(md5($user_password));
706
707                 if (!$current_user->isAdminForModule('Users')) {
708                         //check old password first
709                         $query = "SELECT user_name FROM $this->table_name WHERE user_hash='$old_user_hash' AND id='$this->id'";
710                         $result = $this->db->query($query, true);
711                         $row = $this->db->fetchByAssoc($result);
712                         $GLOBALS['log']->debug("select old password query: $query");
713                         $GLOBALS['log']->debug("return result of $row");
714             if ($row == null) {
715                                 $GLOBALS['log']->warn("Incorrect old password for ".$this->user_name."");
716                                 $this->error_string = $mod_strings['ERR_PASSWORD_INCORRECT_OLD_1'].$this->user_name.$mod_strings['ERR_PASSWORD_INCORRECT_OLD_2'];
717                                 return false;
718                         }
719                 }
720
721         $user_hash = strtolower(md5($new_password));
722         $this->setPreference('loginexpiration','0');
723         //set new password
724         $now = TimeDate::getInstance()->nowDb();
725                 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='$system_generated', pwd_last_changed='$now' where id='$this->id'";
726                 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
727         $_SESSION['hasExpiredPassword'] = '0';
728                 return true;
729         }
730
731         function is_authenticated() {
732                 return $this->authenticated;
733         }
734
735         function fill_in_additional_list_fields() {
736                 $this->fill_in_additional_detail_fields();
737         }
738
739         function fill_in_additional_detail_fields() {
740                 global $locale;
741
742                 $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";
743                 $result = $this->db->query($query, true, "Error filling in additional detail fields");
744
745                 $row = $this->db->fetchByAssoc($result);
746                 $GLOBALS['log']->debug("additional detail query results: $row");
747
748                 if ($row != null) {
749                         $this->reports_to_name = stripslashes($row['first_name'].' '.$row['last_name']);
750                 } else {
751                         $this->reports_to_name = '';
752                 }
753
754                 $this->_create_proper_name_field();
755         }
756
757         public function retrieve_user_id(
758             $user_name
759             )
760         {
761             $userFocus = new User;
762             $userFocus->retrieve_by_string_fields(array('user_name'=>$user_name));
763             if ( empty($userFocus->id) )
764                 return false;
765
766         return $userFocus->id;
767         }
768
769         /**
770          * @return -- returns a list of all users in the system.
771          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
772          * All Rights Reserved..
773          * Contributor(s): ______________________________________..
774          */
775         function verify_data($ieVerified=true) {
776                 global $mod_strings, $current_user;
777                 $verified = TRUE;
778
779                 if (!empty ($this->id)) {
780                         // Make sure the user doesn't report to themselves.
781                         $reports_to_self = 0;
782                         $check_user = $this->reports_to_id;
783                         $already_seen_list = array ();
784                         while (!empty ($check_user)) {
785                                 if (isset ($already_seen_list[$check_user])) {
786                                         // This user doesn't actually report to themselves
787                                         // But someone above them does.
788                                         $reports_to_self = 1;
789                                         break;
790                                 }
791                                 if ($check_user == $this->id) {
792                                         $reports_to_self = 1;
793                                         break;
794                                 }
795                                 $already_seen_list[$check_user] = 1;
796                                 $query = "SELECT reports_to_id FROM users WHERE id='".$this->db->quote($check_user)."'";
797                                 $result = $this->db->query($query, true, "Error checking for reporting-loop");
798                                 $row = $this->db->fetchByAssoc($result);
799                                 echo ("fetched: ".$row['reports_to_id']." from ".$check_user."<br>");
800                                 $check_user = $row['reports_to_id'];
801                         }
802
803                         if ($reports_to_self == 1) {
804                                 $this->error_string .= $mod_strings['ERR_REPORT_LOOP'];
805                                 $verified = FALSE;
806                         }
807                 }
808
809                 $query = "SELECT user_name from users where user_name='$this->user_name' AND deleted=0";
810                 if(!empty($this->id))$query .=  " AND id<>'$this->id'";
811                 $result = $this->db->query($query, true, "Error selecting possible duplicate users: ");
812                 $dup_users = $this->db->fetchByAssoc($result);
813
814                 if (!empty($dup_users)) {
815                         $this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'].$this->user_name.$mod_strings['ERR_USER_NAME_EXISTS_2'];
816                         $verified = FALSE;
817                 }
818
819                 if (($current_user->is_admin == "on")) {
820             if($this->db->dbType == 'mssql'){
821                 $query = "SELECT user_name from users where is_admin = 1 AND deleted=0";
822             }else{
823                 $query = "SELECT user_name from users where is_admin = 'on' AND deleted=0";
824             }
825                         $result = $this->db->query($query, true, "Error selecting possible duplicate users: ");
826                         $remaining_admins = $this->db->getRowCount($result);
827
828                         if (($remaining_admins <= 1) && ($this->is_admin != "on") && ($this->id == $current_user->id)) {
829                                 $GLOBALS['log']->debug("Number of remaining administrator accounts: {$remaining_admins}");
830                                 $this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'].$this->user_name.$mod_strings['ERR_LAST_ADMIN_2'];
831                                 $verified = FALSE;
832                         }
833                 }
834                 ///////////////////////////////////////////////////////////////////////
835                 ////    InboundEmail verification failure
836                 if(!$ieVerified) {
837                         $verified = false;
838                         $this->error_string .= '<br />'.$mod_strings['ERR_EMAIL_NO_OPTS'];
839                 }
840
841                 return $verified;
842         }
843
844         function get_list_view_data() {
845
846                 global $current_user;
847                 
848                 // Bug #48555 Not User Name Format of User's locale. 
849                 $this->_create_proper_name_field();
850                 
851                 $user_fields = $this->get_list_view_array();
852                 if ($this->is_admin)
853                         $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '');
854                 elseif (!$this->is_admin) $user_fields['IS_ADMIN'] = '';
855                 if ($this->is_group)
856                         $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '');
857                 else
858                         $user_fields['IS_GROUP_IMAGE'] = '';
859                 $user_fields['NAME'] = empty ($this->name) ? '' : $this->name;
860
861                 $user_fields['REPORTS_TO_NAME'] = $this->reports_to_name;
862
863                 $user_fields['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this);
864
865                 return $user_fields;
866         }
867
868         function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
869                 return $list_form;
870         }
871
872
873
874         function create_export_query($order_by, $where) {
875                 include('modules/Users/field_arrays.php');
876
877                 $cols = '';
878                 foreach($fields_array['User']['export_fields'] as $field) {
879                         $cols .= (empty($cols)) ? '' : ', ';
880                         $cols .= $field;
881                 }
882
883                 $query = "SELECT {$cols} FROM users ";
884
885                 $where_auto = " users.deleted = 0";
886
887                 if ($where != "")
888                         $query .= " WHERE $where AND ".$where_auto;
889                 else
890                         $query .= " WHERE ".$where_auto;
891
892                 // admin for module user is not be able to export a super-admin
893                 global $current_user;
894                 if(!$current_user->is_admin){
895                         $query .= " AND users.is_admin=0";
896                 }
897
898                 if ($order_by != "")
899                         $query .= " ORDER BY $order_by";
900                 else
901                         $query .= " ORDER BY users.user_name";
902
903                 return $query;
904         }
905
906         /** Returns a list of the associated users
907          * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
908          * All Rights Reserved..
909          * Contributor(s): ______________________________________..
910         */
911         function get_meetings() {
912                 // First, get the list of IDs.
913                 $query = "SELECT meeting_id as id from meetings_users where user_id='$this->id' AND deleted=0";
914                 return $this->build_related_list($query, new Meeting());
915         }
916         function get_calls() {
917                 // First, get the list of IDs.
918                 $query = "SELECT call_id as id from calls_users where user_id='$this->id' AND deleted=0";
919                 return $this->build_related_list($query, new Call());
920         }
921
922         /**
923          * generates Javascript to display I-E mail counts, both personal and group
924          */
925         function displayEmailCounts() {
926                 global $theme;
927                 $new = translate('LBL_NEW', 'Emails');
928                 $default = 'index.php?module=Emails&action=ListView&assigned_user_id='.$this->id;
929                 $count = '';
930                 $verts = array('Love', 'Links', 'Pipeline', 'RipCurl', 'SugarLite');
931
932                 if($this->hasPersonalEmail()) {
933                         $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\'');
934                         $a = $this->db->fetchByAssoc($r);
935                         if(in_array($theme, $verts)) {
936                                 $count .= '<br />';
937                         } else {
938                                 $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
939                         }
940                         $count .= '<a href='.$default.'&type=inbound>'.translate('LBL_LIST_TITLE_MY_INBOX', 'Emails').': ('.$a['c'].' '.$new.')</a>';
941
942                         if(!in_array($theme, $verts)) {
943                                 $count .= ' - ';
944                         }
945                 }
946
947                 $r = $this->db->query('SELECT id FROM users WHERE users.is_group = 1 AND deleted = 0');
948                 $groupIds = '';
949                 $groupNew = '';
950                 while($a = $this->db->fetchByAssoc($r)) {
951                         if($groupIds != '') {$groupIds .= ', ';}
952                         $groupIds .= "'".$a['id']."'";
953                 }
954
955                 $total = 0;
956                 if(strlen($groupIds) > 0) {
957                         $groupQuery = 'SELECT count(*) AS c FROM emails ';
958                         $groupQuery .= ' WHERE emails.deleted=0 AND emails.assigned_user_id IN ('.$groupIds.') AND emails.type = \'inbound\' AND emails.status = \'unread\'';
959                         $r = $this->db->query($groupQuery);
960                         if(is_resource($r)) {
961                                 $a = $this->db->fetchByAssoc($r);
962                                 if($a['c'] > 0) {
963                                         $total = $a['c'];
964                                 }
965                         }
966                 }
967                 if(in_array($theme, $verts)) $count .= '<br />';
968                 if(empty($count)) $count .= '&nbsp;&nbsp;&nbsp;&nbsp;';
969                 $count .= '<a href=index.php?module=Emails&action=ListViewGroup>'.translate('LBL_LIST_TITLE_GROUP_INBOX', 'Emails').': ('.$total.' '.$new.')</a>';
970
971                 $out  = '<script type="text/javascript" language="Javascript">';
972                 $out .= 'var welcome = document.getElementById("welcome");';
973                 $out .= 'var welcomeContent = welcome.innerHTML;';
974                 $out .= 'welcome.innerHTML = welcomeContent + "'.$count.'";';
975                 $out .= '</script>';
976
977                 echo $out;
978         }
979
980         function getPreferredEmail() {
981                 $ret = array ();
982                 $nameEmail = $this->getUsersNameAndEmail();
983                 $prefAddr = $nameEmail['email'];
984                 $fullName = $nameEmail['name'];
985                 if (empty ($prefAddr)) {
986                         $nameEmail = $this->getSystemDefaultNameAndEmail();
987                         $prefAddr = $nameEmail['email'];
988                         $fullName = $nameEmail['name'];
989                 } // if
990                 $fullName = from_html($fullName);
991                 $ret['name'] = $fullName;
992                 $ret['email'] = $prefAddr;
993                 return $ret;
994         }
995
996         function getUsersNameAndEmail() 
997         {
998             // Bug #48555 Not User Name Format of User's locale. 
999             $this->_create_proper_name_field();
1000
1001                 $prefAddr = $this->emailAddress->getPrimaryAddress($this);
1002
1003                 if (empty ($prefAddr)) {
1004                         $prefAddr = $this->emailAddress->getReplyToAddress($this);
1005                 }
1006                 return array('email' => $prefAddr , 'name' => $this->name);
1007
1008         } // fn
1009
1010         function getSystemDefaultNameAndEmail() {
1011
1012                 $email = new Email();
1013                 $return = $email->getSystemDefaultEmail();
1014                 $prefAddr = $return['email'];
1015                 $fullName = $return['name'];
1016                 return array('email' => $prefAddr , 'name' => $fullName);
1017         } // fn
1018
1019         /**
1020          * sets User email default in config.php if not already set by install - i.
1021          * e., upgrades
1022          */
1023         function setDefaultsInConfig() {
1024                 global $sugar_config;
1025                 $sugar_config['email_default_client'] = 'sugar';
1026                 $sugar_config['email_default_editor'] = 'html';
1027                 ksort($sugar_config);
1028                 write_array_to_file('sugar_config', $sugar_config, 'config.php');
1029                 return $sugar_config;
1030         }
1031
1032     /**
1033      * returns User's email address based on descending order of preferences
1034      *
1035      * @param string id GUID of target user if needed
1036      * @return array Assoc array for an email and name
1037      */
1038     function getEmailInfo($id='') {
1039         $user = $this;
1040         if(!empty($id)) {
1041             $user = new User();
1042             $user->retrieve($id);
1043         }
1044
1045         // from name
1046         $fromName = $user->getPreference('mail_fromname');
1047         if(empty($fromName)) {
1048                 // cn: bug 8586 - localized name format
1049             $fromName = $user->full_name;
1050         }
1051
1052         // from address
1053         $fromaddr = $user->getPreference('mail_fromaddress');
1054         if(empty($fromaddr)) {
1055             if(!empty($user->email1) && isset($user->email1)) {
1056                 $fromaddr = $user->email1;
1057             } elseif(!empty($user->email2) && isset($user->email2)) {
1058                 $fromaddr = $user->email2;
1059             } else {
1060                 $r = $user->db->query("SELECT value FROM config WHERE name = 'fromaddress'");
1061                 $a = $user->db->fetchByAssoc($r);
1062                 $fromddr = $a['value'];
1063             }
1064         }
1065
1066         $ret['name'] = $fromName;
1067         $ret['email'] = $fromaddr;
1068
1069         return $ret;
1070     }
1071
1072         /**
1073          * returns opening <a href=xxxx for a contact, account, etc
1074          * cascades from User set preference to System-wide default
1075          * @return string       link
1076          * @param attribute the email addy
1077          * @param focus the parent bean
1078          * @param contact_id
1079          * @param return_module
1080          * @param return_action
1081          * @param return_id
1082          * @param class
1083          */
1084         function getEmailLink2($emailAddress, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1085                 $emailLink = '';
1086                 global $sugar_config;
1087
1088                 if(!isset($sugar_config['email_default_client'])) {
1089                         $this->setDefaultsInConfig();
1090                 }
1091
1092                 $userPref = $this->getPreference('email_link_type');
1093                 $defaultPref = $sugar_config['email_default_client'];
1094                 if($userPref != '') {
1095                         $client = $userPref;
1096                 } else {
1097                         $client = $defaultPref;
1098                 }
1099
1100                 if($client == 'sugar') {
1101                         $email = '';
1102                         $to_addrs_ids = '';
1103                         $to_addrs_names = '';
1104                         $to_addrs_emails = '';
1105                         
1106             $fullName = !empty($focus->name) ? $focus->name : '';
1107
1108                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1109                         if(empty($ret_id)) $ret_id = $focus->id;
1110                         if($focus->object_name == 'Contact') {
1111                                 $contact_id = $focus->id;
1112                                 $to_addrs_ids = $focus->id;
1113                                 // Bug #48555 Not User Name Format of User's locale. 
1114                                 $focus->_create_proper_name_field();
1115                             $fullName = $focus->name;
1116                             $to_addrs_names = $fullName;
1117                                 $to_addrs_emails = $focus->email1;
1118                         }
1119
1120                         $emailLinkUrl = 'contact_id='.$contact_id.
1121                                 '&parent_type='.$focus->module_dir.
1122                                 '&parent_id='.$focus->id.
1123                                 '&parent_name='.urlencode($fullName).
1124                                 '&to_addrs_ids='.$to_addrs_ids.
1125                                 '&to_addrs_names='.urlencode($to_addrs_names).
1126                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1127                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $emailAddress . '&gt;').
1128                                 '&return_module='.$ret_module.
1129                                 '&return_action='.$ret_action.
1130                                 '&return_id='.$ret_id;
1131
1132                 //Generate the compose package for the quick create options.
1133                 //$json = getJSONobj();
1134                 //$composeOptionsLink = $json->encode( array('composeOptionsLink' => $emailLinkUrl,'id' => $focus->id) );
1135                         require_once('modules/Emails/EmailUI.php');
1136             $eUi = new EmailUI();
1137             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1138
1139                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1140
1141                 } else {
1142                         // straight mailto:
1143                         $emailLink = '<a href="mailto:'.$emailAddress.'" class="'.$class.'">';
1144                 }
1145
1146                 return $emailLink;
1147         }
1148
1149         /**
1150          * returns opening <a href=xxxx for a contact, account, etc
1151          * cascades from User set preference to System-wide default
1152          * @return string       link
1153          * @param attribute the email addy
1154          * @param focus the parent bean
1155          * @param contact_id
1156          * @param return_module
1157          * @param return_action
1158          * @param return_id
1159          * @param class
1160          */
1161         function getEmailLink($attribute, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1162             $emailLink = '';
1163                 global $sugar_config;
1164
1165                 if(!isset($sugar_config['email_default_client'])) {
1166                         $this->setDefaultsInConfig();
1167                 }
1168
1169                 $userPref = $this->getPreference('email_link_type');
1170                 $defaultPref = $sugar_config['email_default_client'];
1171                 if($userPref != '') {
1172                         $client = $userPref;
1173                 } else {
1174                         $client = $defaultPref;
1175                 }
1176
1177                 if($client == 'sugar') {
1178                         $email = '';
1179                         $to_addrs_ids = '';
1180                         $to_addrs_names = '';
1181                         $to_addrs_emails = '';
1182             $fullName = !empty($focus->name) ? $focus->name : '';
1183
1184                         if(!empty($focus->$attribute)) {
1185                                 $email = $focus->$attribute;
1186                         }
1187
1188
1189                         if(empty($ret_module)) $ret_module = $focus->module_dir;
1190                         if(empty($ret_id)) $ret_id = $focus->id;
1191                         if($focus->object_name == 'Contact') {
1192                                 // Bug #48555 Not User Name Format of User's locale. 
1193                                 $focus->_create_proper_name_field();
1194                             $fullName = $focus->name;
1195                             $contact_id = $focus->id;
1196                                 $to_addrs_ids = $focus->id;
1197                                 $to_addrs_names = $fullName;
1198                                 $to_addrs_emails = $focus->email1;
1199                         }
1200
1201                         $emailLinkUrl = 'contact_id='.$contact_id.
1202                                 '&parent_type='.$focus->module_dir.
1203                                 '&parent_id='.$focus->id.
1204                                 '&parent_name='.urlencode($fullName).
1205                                 '&to_addrs_ids='.$to_addrs_ids.
1206                                 '&to_addrs_names='.urlencode($to_addrs_names).
1207                                 '&to_addrs_emails='.urlencode($to_addrs_emails).
1208                                 '&to_email_addrs='.urlencode($fullName . '&nbsp;&lt;' . $email . '&gt;').
1209                                 '&return_module='.$ret_module.
1210                                 '&return_action='.$ret_action.
1211                                 '&return_id='.$ret_id;
1212
1213                         //Generate the compose package for the quick create options.
1214                 require_once('modules/Emails/EmailUI.php');
1215             $eUi = new EmailUI();
1216             $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1217                 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1218
1219                 } else {
1220                         // straight mailto:
1221                         $emailLink = '<a href="mailto:'.$focus->$attribute.'" class="'.$class.'">';
1222                 }
1223
1224                 return $emailLink;
1225         }
1226
1227
1228         /**
1229          * gets a human-readable explanation of the format macro
1230          * @return string Human readable name format
1231          */
1232         function getLocaleFormatDesc() {
1233                 global $locale;
1234                 global $mod_strings;
1235                 global $app_strings;
1236
1237                 $format['f'] = $mod_strings['LBL_LOCALE_DESC_FIRST'];
1238                 $format['l'] = $mod_strings['LBL_LOCALE_DESC_LAST'];
1239                 $format['s'] = $mod_strings['LBL_LOCALE_DESC_SALUTATION'];
1240                 $format['t'] = $mod_strings['LBL_LOCALE_DESC_TITLE'];
1241
1242                 $name['f'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
1243                 $name['l'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
1244                 $name['s'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
1245                 $name['t'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
1246
1247                 $macro = $locale->getLocaleFormatMacro();
1248
1249                 $ret1 = '';
1250                 $ret2 = '';
1251                 for($i=0; $i<strlen($macro); $i++) {
1252                         if(array_key_exists($macro{$i}, $format)) {
1253                                 $ret1 .= "<i>".$format[$macro{$i}]."</i>";
1254                                 $ret2 .= "<i>".$name[$macro{$i}]."</i>";
1255                         } else {
1256                                 $ret1 .= $macro{$i};
1257                                 $ret2 .= $macro{$i};
1258                         }
1259                 }
1260                 return $ret1."<br />".$ret2;
1261         }
1262
1263
1264     /*
1265      *
1266      * Here are the multi level admin access check functions.
1267      *
1268      */
1269     /**
1270      * Helper function to remap some modules around ACL wise
1271      *
1272      * @return string
1273      */
1274     protected function _fixupModuleForACL($module) {
1275         if($module=='ContractTypes') { 
1276             $module = 'Contracts';
1277         }
1278         if(preg_match('/Product[a-zA-Z]*/',$module)) {
1279             $module = 'Products';
1280         }
1281         
1282         return $module;
1283     }
1284     /**
1285      * Helper function that enumerates the list of modules and checks if they are an admin/dev.
1286      * The code was just too similar to copy and paste.
1287      *
1288      * @return array
1289      */
1290     protected function _getModulesForACL($type='dev'){
1291         $isDev = $type=='dev';
1292         $isAdmin = $type=='admin';
1293
1294         global $beanList;
1295         $myModules = array();
1296
1297         if (!is_array($beanList) ) {
1298             return $myModules;
1299         }
1300
1301         // These modules don't take kindly to the studio trying to play about with them.
1302         static $ignoredModuleList = array('iFrames','Feeds','Home','Dashboard','Calendar','Activities','Reports');
1303
1304         
1305         $actions = ACLAction::getUserActions($this->id);
1306         
1307         foreach ($beanList as $module=>$val) {
1308             // Remap the module name
1309             $module = $this->_fixupModuleForACL($module);
1310             if (in_array($module,$myModules)) {
1311                 // Already have the module in the list
1312                 continue;
1313             }
1314             if (in_array($module,$ignoredModuleList)) {
1315                 // You can't develop on these modules.
1316                 continue;
1317             }
1318
1319             $key = 'module';
1320             
1321             if (($this->isAdmin() && isset($actions[$module][$key]))
1322                 ) {
1323                 $myModules[] = $module;
1324             }
1325         }
1326
1327         return $myModules;        
1328     }
1329     /**
1330      * Is this user a system wide admin
1331      *
1332      * @return bool
1333      */
1334     public function isAdmin() {
1335         if(isset($this->is_admin)
1336            &&($this->is_admin == '1' || $this->is_admin === 'on')){
1337             return true;
1338         }
1339         return false;
1340     }
1341     /**
1342      * Is this user a developer for any module
1343      *
1344      * @return bool
1345      */
1346     public function isDeveloperForAnyModule() {
1347         if ($this->isAdmin()) {
1348             return true;
1349         }
1350         return false;
1351     }
1352     /**
1353      * List the modules a user has developer access to
1354      *
1355      * @return array
1356      */
1357     public function getDeveloperModules() {
1358         static $developerModules;
1359         if (!isset($_SESSION[$this->user_name.'_get_developer_modules_for_user']) ) {
1360             $_SESSION[$this->user_name.'_get_developer_modules_for_user'] = $this->_getModulesForACL('dev');
1361         }
1362
1363         return $_SESSION[$this->user_name.'_get_developer_modules_for_user'];
1364     }
1365     /**
1366      * Is this user a developer for the specified module
1367      *
1368      * @return bool
1369      */
1370     public function isDeveloperForModule($module) {
1371         if ($this->isAdmin()) {
1372             return true;
1373         }
1374         
1375         $devModules = $this->getDeveloperModules();
1376         
1377         $module = $this->_fixupModuleForACL($module);
1378
1379         if (in_array($module,$devModules) ) {
1380             return true;
1381         }
1382
1383         return false;
1384     }
1385     /**
1386      * List the modules a user has admin access to
1387      *
1388      * @return array
1389      */
1390     public function getAdminModules() {
1391         if (!isset($_SESSION[$this->user_name.'_get_admin_modules_for_user']) ) {
1392             $_SESSION[$this->user_name.'_get_admin_modules_for_user'] = $this->_getModulesForACL('admin');
1393         }
1394
1395         return $_SESSION[$this->user_name.'_get_admin_modules_for_user'];
1396     }
1397     /**
1398      * Is this user an admin for the specified module
1399      *
1400      * @return bool
1401      */
1402     public function isAdminForModule($module) {
1403         if ($this->isAdmin()) {
1404             return true;
1405         }
1406         
1407         $adminModules = $this->getAdminModules();
1408         
1409         $module = $this->_fixupModuleForACL($module);
1410
1411         if (in_array($module,$adminModules) ) {
1412             return true;
1413         }
1414
1415         return false;
1416     }
1417         /**
1418          * Whether or not based on the user's locale if we should show the last name first.
1419          *
1420          * @return bool
1421          */
1422         public function showLastNameFirst(){
1423                 global $locale;
1424         $localeFormat = $locale->getLocaleFormatMacro($this);
1425                 if ( strpos($localeFormat,'l') > strpos($localeFormat,'f') ) {
1426                     return false;
1427         }else {
1428                 return true;
1429         }
1430         }
1431
1432
1433
1434    function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false)
1435    {    //call parent method, specifying for array to be returned
1436         $ret_array = parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, true,$parentbean, $singleSelect);
1437
1438         //if this is being called from webservices, then run additional code
1439         if(!empty($GLOBALS['soap_server_object'])){
1440
1441                 //if this is a single select, then secondary queries are being run that may result in duplicate rows being returned through the
1442                 //left joins with meetings/tasks/call.  We need to change the left joins to include a null check (bug 40250)
1443                 if($singleSelect)
1444                 {
1445                         //retrieve the 'from' string and make lowercase for easier manipulation
1446                         $left_str = strtolower($ret_array['from']);
1447                         $lefts = explode('left join', $left_str);
1448                         $new_left_str = '';
1449
1450                         //explode on the left joins and process each one
1451                         foreach($lefts as $ljVal){
1452                                 //grab the join alias
1453                                 $onPos = strpos( $ljVal, ' on');
1454                                 if($onPos === false){
1455                                         $new_left_str .=' '.$ljVal.' ';
1456                                         continue;
1457                                 }
1458                                 $spacePos = strrpos(substr($ljVal, 0, $onPos),' ');
1459                                 $alias = substr($ljVal,$spacePos,$onPos-$spacePos);
1460
1461                                 //add null check to end of the Join statement
1462                         // Bug #46390 to use id_c field instead of id field for custom tables
1463                         if(substr($alias, -5) != '_cstm')
1464                         {
1465                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id is null ';
1466                         }
1467                         else
1468                         {
1469                             $ljVal ='  LEFT JOIN '.$ljVal.' and '.$alias.'.id_c is null ';
1470                         }
1471
1472                                 //add statement into new string
1473                                 $new_left_str .= $ljVal;
1474                          }
1475                          //replace the old string with the new one
1476                          $ret_array['from'] = $new_left_str;
1477                 }
1478         }
1479
1480                 //return array or query string
1481                 if($return_array)
1482         {
1483                 return $ret_array;
1484         }
1485
1486         return  $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
1487
1488
1489
1490    }
1491
1492     // Bug #48014 Must to send password to imported user if this action is required
1493     function afterImportSave()
1494     {
1495         if(
1496             $this->user_hash == false
1497             && !$this->is_group
1498             && !$this->portal_only
1499             && isset($GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON'])
1500             && $GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON']
1501         )
1502         {
1503             $backUpPost = $_POST;
1504             $_POST = array(
1505                 'userId' => $this->id
1506             );
1507             ob_start();
1508             require('modules/Users/GeneratePassword.php');
1509             $result = ob_get_clean();
1510             $_POST = $backUpPost;
1511             return $result == true;
1512         }
1513     }
1514 }