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