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.
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.
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
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
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.
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.
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 ********************************************************************************/
38 /*********************************************************************************
40 * Description: TODO: To be written.
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42 * All Rights Reserved.
43 * Contributor(s): ______________________________________..
44 ********************************************************************************/
46 require_once('include/SugarObjects/templates/person/Person.php');
49 // User is used to store customer information.
50 class User extends Person {
62 var $modified_user_id;
65 var $modified_by_name;
77 var $address_postalcode;
83 var $authenticated = false;
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
94 var $receive_notifications;
98 var $team_exists = false;
99 var $table_name = "users";
100 var $module_dir = 'Users';
101 var $object_name = "User";
102 var $user_preferences;
104 var $importable = true;
105 var $_userPreferenceFocus;
107 var $encodeFields = Array ("first_name", "last_name", "description");
109 // This is used to retrieve related fields from form posts.
110 var $additional_column_fields = array ('reports_to_name'
116 var $new_schema = true;
121 $this->_loadUserPreferencesFocus();
124 protected function _loadUserPreferencesFocus()
126 $this->_userPreferenceFocus = new UserPreference($this);
130 * returns an admin user
132 public function getSystemUser()
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',
146 * convenience function to get user's default signature
148 function getDefaultSignature() {
149 if($defaultId = $this->getPreference('signature_default')) {
150 return $this->getSignature($defaultId);
157 * retrieves the signatures for a user
158 * @param string id ID of user_signature
159 * @return array ID, signature, and signature_html
161 public function getSignature($id)
163 $signatures = $this->getSignaturesArray();
165 return $signatures[$id];
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);
173 $sig = array(""=>"");
175 while($a = $this->db->fetchByAssoc($r)) {
183 * retrieves any signatures that the User may have created as <select>
185 public function getSignatures(
191 $sig = $this->getSignaturesArray();
193 foreach ($sig as $key => $arr)
195 $sigs[$key] = !empty($arr['name']) ? $arr['name'] : '';
200 $change = ($forSettings) ? "onChange='displaySignatureEdit();'" : "onChange='setSigEditButtonVisibility();'";
203 $id = (!$forSettings) ? 'signature_id' : 'signature_idDisplay';
205 $out = "<select {$change} id='{$id}' name='{$id}'>";
206 $out .= get_select_options_with_id($sigs, $defaultSig).'</select>';
212 * returns buttons and JS for signatures
214 function getSignatureButtons($jscall='', $defaultDisplay=false) {
217 $jscall = empty($jscall) ? 'open_email_signature_form' : $jscall;
219 $butts = "<input class='button' onclick='javascript:{$jscall}(\"\", \"{$this->id}\");' value='{$mod_strings['LBL_BUTTON_CREATE']}' type='button'> ";
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">
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">
231 * performs a rudimentary check to verify if a given user has setup personal
236 public function hasPersonalEmail()
238 $focus = new InboundEmail;
239 $focus->retrieve_by_string_fields(array('group_id' => $this->id));
241 return !empty($focus->id);
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.
248 function getUserPrivGuid() {
249 $userPrivGuid = $this->getPreference('userPrivGuid', 'global', $this);
251 return $userPrivGuid;
253 $this->setUserPrivGuid();
254 if (!isset ($_SESSION['setPrivGuid'])) {
255 $_SESSION['setPrivGuid'] = true;
256 $userPrivGuid = $this->getUserPrivGuid();
257 return $userPrivGuid;
259 sugar_die("Breaking Infinite Loop Condition: Could not setUserPrivGuid.");
264 function setUserPrivGuid() {
265 $privGuid = create_guid();
266 //($name, $value, $nosession=0)
267 $this->setPreference('userPrivGuid', $privGuid, 0, 'global', $this);
271 * Interface for the User object to calling the UserPreference::setPreference() method in modules/UserPreferences/UserPreference.php
273 * @see UserPreference::setPreference()
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
280 public function setPreference(
288 if ( func_num_args() > 4 ) {
289 $user = func_get_arg(4);
290 $GLOBALS['log']->deprecated('User::setPreferences() should not be used statically.');
295 $user->_userPreferenceFocus->setPreference($name, $value, $category);
299 * Interface for the User object to calling the UserPreference::resetPreferences() method in modules/UserPreferences/UserPreference.php
301 * @see UserPreference::resetPreferences()
303 * @param string $category category to reset
305 public function resetPreferences(
310 if ( func_num_args() > 1 ) {
311 $user = func_get_arg(1);
312 $GLOBALS['log']->deprecated('User::resetPreferences() should not be used statically.');
317 $user->_userPreferenceFocus->resetPreferences($category);
321 * Interface for the User object to calling the UserPreference::savePreferencesToDB() method in modules/UserPreferences/UserPreference.php
323 * @see UserPreference::savePreferencesToDB()
325 public function savePreferencesToDB()
328 if ( func_num_args() > 0 ) {
329 $user = func_get_arg(0);
330 $GLOBALS['log']->deprecated('User::savePreferencesToDB() should not be used statically.');
335 $user->_userPreferenceFocus->savePreferencesToDB();
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?
343 public function reloadPreferences($category = 'global')
345 return $this->_userPreferenceFocus->reloadPreferences($category = 'global');
349 * Interface for the User object to calling the UserPreference::getUserDateTimePreferences() method in modules/UserPreferences/UserPreference.php
351 * @see UserPreference::getUserDateTimePreferences()
353 * @return array 'date' - date format for user ; 'time' - time format for user
355 public function getUserDateTimePreferences()
358 if ( func_num_args() > 0 ) {
359 $user = func_get_arg(0);
360 $GLOBALS['log']->deprecated('User::getUserDateTimePreferences() should not be used statically.');
365 return $user->_userPreferenceFocus->getUserDateTimePreferences();
369 * Interface for the User object to calling the UserPreference::loadPreferences() method in modules/UserPreferences/UserPreference.php
371 * @see UserPreference::loadPreferences()
373 * @param string $category name of the category to retreive, defaults to global scope
374 * @return bool successful?
376 public function loadPreferences(
381 if ( func_num_args() > 1 ) {
382 $user = func_get_arg(1);
383 $GLOBALS['log']->deprecated('User::loadPreferences() should not be used statically.');
388 return $user->_userPreferenceFocus->loadPreferences($category);
392 * Interface for the User object to calling the UserPreference::setPreference() method in modules/UserPreferences/UserPreference.php
394 * @see UserPreference::getPreference()
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)
400 public function getPreference(
406 if ( func_num_args() > 2 ) {
407 $user = func_get_arg(2);
408 $GLOBALS['log']->deprecated('User::getPreference() should not be used statically.');
413 return $user->_userPreferenceFocus->getPreference($name, $category);
417 * Get WHERE clause that fetches all users counted for licensing purposes
420 public static function getLicensedUsersWhere()
422 return "deleted=0 AND status='Active' AND user_name IS NOT NULL AND is_group=0 AND portal_only=0 AND ".$GLOBALS['db']->convert('user_name', 'length').">0";
426 function save($check_notify = false) {
427 $isUpdate = !empty($this->id) && !$this->new_with_id;
430 $query = "SELECT count(id) as total from users WHERE ".self::getLicensedUsersWhere();
433 // wp: do not save user_preferences in this table, see user_preferences module
434 $this->user_preferences = '';
436 // if this is an admin user, do not allow is_group or portal_only flag to be set.
437 if ($this->is_admin) {
439 $this->portal_only = 0;
446 parent::save($check_notify);
450 $this->savePreferencesToDB();
455 * @return boolean true if the user is a member of the role_name, false otherwise
456 * @param string $role_name - Must be the exact name of the acl_role
457 * @param string $user_id - The user id to check for the role membership, empty string if current user
458 * @desc Determine whether or not a user is a member of an ACL Role. This function caches the
459 * results in the session or to prevent running queries after the first time executed.
460 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
461 * All Rights Reserved..
462 * Contributor(s): ______________________________________..
464 function check_role_membership($role_name, $user_id = ''){
466 global $current_user;
469 $user_id = $current_user->id;
471 // Check the Sugar External Cache to see if this users memberships were cached
472 $role_array = sugar_cache_retrieve("RoleMemberships_".$user_id);
474 // If we are pulling the roles for the current user
475 if($user_id == $current_user->id){
476 // If the Session doesn't contain the values
477 if(!isset($_SESSION['role_memberships'])){
478 // This means the external cache already had it loaded
479 if(!empty($role_array))
480 $_SESSION['role_memberships'] = $role_array;
482 $_SESSION['role_memberships'] = ACLRole::getUserRoleNames($user_id);
483 $role_array = $_SESSION['role_memberships'];
486 // else the session had the values, so we assign to the role array
488 $role_array = $_SESSION['role_memberships'];
492 // If the external cache didn't contain the values, we get them and put them in cache
494 $role_array = ACLRole::getUserRoleNames($user_id);
495 sugar_cache_put("RoleMemberships_".$user_id, $role_array);
499 // If the role doesn't exist in the list of the user's roles
500 if(!empty($role_array) && in_array($role_name, $role_array))
506 function get_summary_text() {
507 //$this->_create_proper_name_field();
512 * @return string encrypted password for storage in DB and comparison against DB password.
513 * @param string $user_name - Must be non null and at least 2 characters
514 * @param string $user_password - Must be non null and at least 1 character.
515 * @desc Take an unencrypted username and password and return the encrypted password
516 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
517 * All Rights Reserved..
518 * Contributor(s): ______________________________________..
520 function encrypt_password($user_password) {
521 // encrypt the password.
522 $salt = substr($this->user_name, 0, 2);
523 $encrypted_password = crypt($user_password, $salt);
525 return $encrypted_password;
529 * Authenicates the user; returns true if successful
534 public function authenticate_user(
538 $password = $GLOBALS['db']->quote($password);
539 $user_name = $GLOBALS['db']->quote($this->user_name);
540 $query = "SELECT * from $this->table_name where user_name='$user_name' AND user_hash='$password' AND (portal_only IS NULL OR portal_only !='1') AND (is_group IS NULL OR is_group !='1') ";
541 //$result = $this->db->requireSingleResult($query, false);
542 $result = $this->db->limitQuery($query,0,1,false);
543 $a = $this->db->fetchByAssoc($result);
544 // set the ID in the seed user. This can be used for retrieving the full user record later
546 // already logging this in load_user() method
547 //$GLOBALS['log']->fatal("SECURITY: failed login by $this->user_name");
550 $this->id = $a['id'];
556 * retrieves an User bean
557 * preformat name & full_name attribute with first/last
558 * loads User's preferences
560 * @param string id ID of the User
561 * @param bool encode encode the result
562 * @return object User bean
563 * @return null null if no User found
565 function retrieve($id, $encode = true) {
566 $ret = parent::retrieve($id, $encode);
568 if (isset ($_SESSION)) {
569 $this->loadPreferences();
575 function retrieve_by_email_address($email) {
577 $email1= strtoupper($email);
580 select id from users where id in ( SELECT er.bean_id AS id FROM email_addr_bean_rel er,
581 email_addresses ea WHERE ea.id = er.email_address_id
582 AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = 'Users' AND email_address_caps IN ('{$email}') )
586 $res=$this->db->query($q);
587 $row=$this->db->fetchByAssoc($res);
589 if (!empty($row['id'])) {
590 return $this->retrieve($row['id']);
595 function bean_implements($interface) {
597 case 'ACL':return true;
604 * Load a user based on the user_name in $this
605 * @return -- this if load was successul and null if load failed.
606 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
607 * All Rights Reserved..
608 * Contributor(s): ______________________________________..
610 function load_user($user_password) {
612 unset($GLOBALS['login_error']);
613 if(isset ($_SESSION['loginattempts'])) {
614 $_SESSION['loginattempts'] += 1;
616 $_SESSION['loginattempts'] = 1;
618 if($_SESSION['loginattempts'] > 5) {
619 $GLOBALS['log']->fatal('SECURITY: '.$this->user_name.' has attempted to login '.$_SESSION['loginattempts'].' times from IP address: '.$_SERVER['REMOTE_ADDR'].'.');
622 $GLOBALS['log']->debug("Starting user load for $this->user_name");
624 if (!isset ($this->user_name) || $this->user_name == "" || !isset ($user_password) || $user_password == "")
627 $user_hash = strtolower(md5($user_password));
628 if($this->authenticate_user($user_hash)) {
629 $query = "SELECT * from $this->table_name where id='$this->id'";
631 $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed');
634 $r = $this->db->limitQuery($query, 0, 1, false);
635 $a = $this->db->fetchByAssoc($r);
636 if(empty($a) || !empty ($GLOBALS['login_error'])) {
637 $GLOBALS['log']->fatal('SECURITY: User authentication for '.$this->user_name.' failed - could not Load User from Database');
641 // Get the fields for the user
644 // If there is no user_hash is not present or is out of date, then create a new one.
645 if (!isset ($row['user_hash']) || $row['user_hash'] != $user_hash) {
646 $query = "UPDATE $this->table_name SET user_hash='$user_hash' where id='{$row['id']}'";
647 $this->db->query($query, true, "Error setting new hash for {$row['user_name']}: ");
650 // now fill in the fields.
651 foreach ($this->column_fields as $field) {
652 $GLOBALS['log']->info($field);
654 if (isset ($row[$field])) {
655 $GLOBALS['log']->info("=".$row[$field]);
657 $this-> $field = $row[$field];
661 $this->loadPreferences();
664 require_once ('modules/Versions/CheckVersions.php');
665 $invalid_versions = get_invalid_versions();
667 if (!empty ($invalid_versions)) {
668 if (isset ($invalid_versions['Rebuild Relationships'])) {
669 unset ($invalid_versions['Rebuild Relationships']);
671 // flag for pickup in DisplayWarnings.php
672 $_SESSION['rebuild_relationships'] = true;
675 if (isset ($invalid_versions['Rebuild Extensions'])) {
676 unset ($invalid_versions['Rebuild Extensions']);
678 // flag for pickup in DisplayWarnings.php
679 $_SESSION['rebuild_extensions'] = true;
682 $_SESSION['invalid_versions'] = $invalid_versions;
684 $this->fill_in_additional_detail_fields();
685 if ($this->status != "Inactive")
686 $this->authenticated = true;
688 unset ($_SESSION['loginattempts']);
693 * Verify that the current password is correct and write the new password to the DB.
695 * @param string $user name - Must be non null and at least 1 character.
696 * @param string $user_password - Must be non null and at least 1 character.
697 * @param string $new_password - Must be non null and at least 1 character.
698 * @return boolean - If passwords pass verification and query succeeds, return true, else return false.
700 function change_password(
703 $system_generated = '0'
707 global $current_user;
708 $GLOBALS['log']->debug("Starting password change for $this->user_name");
710 if (!isset ($new_password) || $new_password == "") {
711 $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$current_user['user_name'].$mod_strings['ERR_PASSWORD_CHANGE_FAILED_2'];
715 $old_user_hash = strtolower(md5($user_password));
717 if (!$current_user->isAdminForModule('Users')) {
718 //check old password first
719 $query = "SELECT user_name FROM $this->table_name WHERE user_hash='$old_user_hash' AND id='$this->id'";
720 $result = $this->db->query($query, true);
721 $row = $this->db->fetchByAssoc($result);
722 $GLOBALS['log']->debug("select old password query: $query");
723 $GLOBALS['log']->debug("return result of $row");
725 $GLOBALS['log']->warn("Incorrect old password for ".$this->user_name."");
726 $this->error_string = $mod_strings['ERR_PASSWORD_INCORRECT_OLD_1'].$this->user_name.$mod_strings['ERR_PASSWORD_INCORRECT_OLD_2'];
731 $user_hash = strtolower(md5($new_password));
732 $this->setPreference('loginexpiration','0');
734 $now = TimeDate::getInstance()->nowDb();
735 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='$system_generated', pwd_last_changed='$now' where id='$this->id'";
736 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
737 $_SESSION['hasExpiredPassword'] = '0';
741 function is_authenticated() {
742 return $this->authenticated;
745 function fill_in_additional_list_fields() {
746 $this->fill_in_additional_detail_fields();
749 function fill_in_additional_detail_fields() {
752 $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";
753 $result = $this->db->query($query, true, "Error filling in additional detail fields");
755 $row = $this->db->fetchByAssoc($result);
758 $this->reports_to_name = stripslashes($row['first_name'].' '.$row['last_name']);
760 $this->reports_to_name = '';
763 $this->_create_proper_name_field();
766 public function retrieve_user_id(
770 $userFocus = new User;
771 $userFocus->retrieve_by_string_fields(array('user_name'=>$user_name));
772 if ( empty($userFocus->id) )
775 return $userFocus->id;
779 * @return -- returns a list of all users in the system.
780 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
781 * All Rights Reserved..
782 * Contributor(s): ______________________________________..
784 function verify_data($ieVerified=true) {
785 global $mod_strings, $current_user;
788 if (!empty ($this->id)) {
789 // Make sure the user doesn't report to themselves.
790 $reports_to_self = 0;
791 $check_user = $this->reports_to_id;
792 $already_seen_list = array ();
793 while (!empty ($check_user)) {
794 if (isset ($already_seen_list[$check_user])) {
795 // This user doesn't actually report to themselves
796 // But someone above them does.
797 $reports_to_self = 1;
800 if ($check_user == $this->id) {
801 $reports_to_self = 1;
804 $already_seen_list[$check_user] = 1;
805 $query = "SELECT reports_to_id FROM users WHERE id='".$this->db->quote($check_user)."'";
806 $result = $this->db->query($query, true, "Error checking for reporting-loop");
807 $row = $this->db->fetchByAssoc($result);
808 echo ("fetched: ".$row['reports_to_id']." from ".$check_user."<br>");
809 $check_user = $row['reports_to_id'];
812 if ($reports_to_self == 1) {
813 $this->error_string .= $mod_strings['ERR_REPORT_LOOP'];
818 $query = "SELECT user_name from users where user_name='$this->user_name' AND deleted=0";
819 if(!empty($this->id))$query .= " AND id<>'$this->id'";
820 $result = $this->db->query($query, true, "Error selecting possible duplicate users: ");
821 $dup_users = $this->db->fetchByAssoc($result);
823 if (!empty($dup_users)) {
824 $this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'].$this->user_name.$mod_strings['ERR_USER_NAME_EXISTS_2'];
828 if (is_admin($current_user)) {
829 $remaining_admins = $this->db->getOne("SELECT COUNT(*) as c from users where is_admin = 1 AND deleted=0");
831 if (($remaining_admins <= 1) && ($this->is_admin != '1') && ($this->id == $current_user->id)) {
832 $GLOBALS['log']->debug("Number of remaining administrator accounts: {$remaining_admins}");
833 $this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'].$this->user_name.$mod_strings['ERR_LAST_ADMIN_2'];
837 ///////////////////////////////////////////////////////////////////////
838 //// InboundEmail verification failure
841 $this->error_string .= '<br />'.$mod_strings['ERR_EMAIL_NO_OPTS'];
847 function get_list_view_data() {
849 global $current_user, $mod_strings;
850 // Bug #48555 Not User Name Format of User's locale.
851 $this->_create_proper_name_field();
853 $user_fields = $this->get_list_view_array();
855 $user_fields['IS_ADMIN_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
856 elseif (!$this->is_admin) $user_fields['IS_ADMIN'] = '';
858 $user_fields['IS_GROUP_IMAGE'] = SugarThemeRegistry::current()->getImage('check_inline', '',null,null,'.gif',$mod_strings['LBL_CHECKMARK']);
860 $user_fields['IS_GROUP_IMAGE'] = '';
861 $user_fields['NAME'] = empty ($this->name) ? '' : $this->name;
863 $user_fields['REPORTS_TO_NAME'] = $this->reports_to_name;
865 $user_fields['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this);
870 function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
880 * Returns all active and inactive users
881 * @return Array of all users in the system
884 public static function getAllUsers()
886 $active_users = get_user_array(FALSE);
887 $inactive_users = get_user_array(FALSE, "Inactive");
888 $result = $active_users + $inactive_users;
893 function create_export_query($order_by, $where) {
894 include('modules/Users/field_arrays.php');
897 foreach($fields_array['User']['export_fields'] as $field) {
898 $cols .= (empty($cols)) ? '' : ', ';
902 $query = "SELECT {$cols} FROM users ";
904 $where_auto = " users.deleted = 0";
907 $query .= " WHERE $where AND ".$where_auto;
909 $query .= " WHERE ".$where_auto;
911 // admin for module user is not be able to export a super-admin
912 global $current_user;
913 if(!$current_user->is_admin){
914 $query .= " AND users.is_admin=0";
918 $query .= " ORDER BY $order_by";
920 $query .= " ORDER BY users.user_name";
925 /** Returns a list of the associated users
926 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
927 * All Rights Reserved..
928 * Contributor(s): ______________________________________..
930 function get_meetings() {
931 // First, get the list of IDs.
932 $query = "SELECT meeting_id as id from meetings_users where user_id='$this->id' AND deleted=0";
933 return $this->build_related_list($query, new Meeting());
935 function get_calls() {
936 // First, get the list of IDs.
937 $query = "SELECT call_id as id from calls_users where user_id='$this->id' AND deleted=0";
938 return $this->build_related_list($query, new Call());
942 * generates Javascript to display I-E mail counts, both personal and group
944 function displayEmailCounts() {
946 $new = translate('LBL_NEW', 'Emails');
947 $default = 'index.php?module=Emails&action=ListView&assigned_user_id='.$this->id;
949 $verts = array('Love', 'Links', 'Pipeline', 'RipCurl', 'SugarLite');
951 if($this->hasPersonalEmail()) {
952 $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\'');
953 $a = $this->db->fetchByAssoc($r);
954 if(in_array($theme, $verts)) {
957 $count .= ' ';
959 $count .= '<a href='.$default.'&type=inbound>'.translate('LBL_LIST_TITLE_MY_INBOX', 'Emails').': ('.$a['c'].' '.$new.')</a>';
961 if(!in_array($theme, $verts)) {
966 $r = $this->db->query('SELECT id FROM users WHERE users.is_group = 1 AND deleted = 0');
969 while($a = $this->db->fetchByAssoc($r)) {
970 if($groupIds != '') {$groupIds .= ', ';}
971 $groupIds .= "'".$a['id']."'";
975 if(strlen($groupIds) > 0) {
976 $groupQuery = 'SELECT count(*) AS c FROM emails ';
977 $groupQuery .= ' WHERE emails.deleted=0 AND emails.assigned_user_id IN ('.$groupIds.') AND emails.type = \'inbound\' AND emails.status = \'unread\'';
978 $r = $this->db->query($groupQuery);
979 if(is_resource($r)) {
980 $a = $this->db->fetchByAssoc($r);
986 if(in_array($theme, $verts)) $count .= '<br />';
987 if(empty($count)) $count .= ' ';
988 $count .= '<a href=index.php?module=Emails&action=ListViewGroup>'.translate('LBL_LIST_TITLE_GROUP_INBOX', 'Emails').': ('.$total.' '.$new.')</a>';
990 $out = '<script type="text/javascript" language="Javascript">';
991 $out .= 'var welcome = document.getElementById("welcome");';
992 $out .= 'var welcomeContent = welcome.innerHTML;';
993 $out .= 'welcome.innerHTML = welcomeContent + "'.$count.'";';
999 function getPreferredEmail() {
1001 $nameEmail = $this->getUsersNameAndEmail();
1002 $prefAddr = $nameEmail['email'];
1003 $fullName = $nameEmail['name'];
1004 if (empty ($prefAddr)) {
1005 $nameEmail = $this->getSystemDefaultNameAndEmail();
1006 $prefAddr = $nameEmail['email'];
1007 $fullName = $nameEmail['name'];
1009 $fullName = from_html($fullName);
1010 $ret['name'] = $fullName;
1011 $ret['email'] = $prefAddr;
1015 function getUsersNameAndEmail()
1017 // Bug #48555 Not User Name Format of User's locale.
1018 $this->_create_proper_name_field();
1020 $prefAddr = $this->emailAddress->getPrimaryAddress($this);
1022 if (empty ($prefAddr)) {
1023 $prefAddr = $this->emailAddress->getReplyToAddress($this);
1025 return array('email' => $prefAddr , 'name' => $this->name);
1029 function getSystemDefaultNameAndEmail() {
1031 $email = new Email();
1032 $return = $email->getSystemDefaultEmail();
1033 $prefAddr = $return['email'];
1034 $fullName = $return['name'];
1035 return array('email' => $prefAddr , 'name' => $fullName);
1039 * sets User email default in config.php if not already set by install - i.
1042 function setDefaultsInConfig() {
1043 global $sugar_config;
1044 $sugar_config['email_default_client'] = 'sugar';
1045 $sugar_config['email_default_editor'] = 'html';
1046 ksort($sugar_config);
1047 write_array_to_file('sugar_config', $sugar_config, 'config.php');
1048 return $sugar_config;
1052 * returns User's email address based on descending order of preferences
1054 * @param string id GUID of target user if needed
1055 * @return array Assoc array for an email and name
1057 function getEmailInfo($id='') {
1061 $user->retrieve($id);
1065 $fromName = $user->getPreference('mail_fromname');
1066 if(empty($fromName)) {
1067 // cn: bug 8586 - localized name format
1068 $fromName = $user->full_name;
1072 $fromaddr = $user->getPreference('mail_fromaddress');
1073 if(empty($fromaddr)) {
1074 if(!empty($user->email1) && isset($user->email1)) {
1075 $fromaddr = $user->email1;
1076 } elseif(!empty($user->email2) && isset($user->email2)) {
1077 $fromaddr = $user->email2;
1079 $r = $user->db->query("SELECT value FROM config WHERE name = 'fromaddress'");
1080 $a = $user->db->fetchByAssoc($r);
1081 $fromddr = $a['value'];
1085 $ret['name'] = $fromName;
1086 $ret['email'] = $fromaddr;
1092 * returns opening <a href=xxxx for a contact, account, etc
1093 * cascades from User set preference to System-wide default
1094 * @return string link
1095 * @param attribute the email addy
1096 * @param focus the parent bean
1098 * @param return_module
1099 * @param return_action
1103 function getEmailLink2($emailAddress, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1105 global $sugar_config;
1107 if(!isset($sugar_config['email_default_client'])) {
1108 $this->setDefaultsInConfig();
1111 $userPref = $this->getPreference('email_link_type');
1112 $defaultPref = $sugar_config['email_default_client'];
1113 if($userPref != '') {
1114 $client = $userPref;
1116 $client = $defaultPref;
1119 if($client == 'sugar') {
1122 $to_addrs_names = '';
1123 $to_addrs_emails = '';
1125 $fullName = !empty($focus->name) ? $focus->name : '';
1127 if(empty($ret_module)) $ret_module = $focus->module_dir;
1128 if(empty($ret_id)) $ret_id = $focus->id;
1129 if($focus->object_name == 'Contact') {
1130 $contact_id = $focus->id;
1131 $to_addrs_ids = $focus->id;
1132 // Bug #48555 Not User Name Format of User's locale.
1133 $focus->_create_proper_name_field();
1134 $fullName = $focus->name;
1135 $to_addrs_names = $fullName;
1136 $to_addrs_emails = $focus->email1;
1139 $emailLinkUrl = 'contact_id='.$contact_id.
1140 '&parent_type='.$focus->module_dir.
1141 '&parent_id='.$focus->id.
1142 '&parent_name='.urlencode($fullName).
1143 '&to_addrs_ids='.$to_addrs_ids.
1144 '&to_addrs_names='.urlencode($to_addrs_names).
1145 '&to_addrs_emails='.urlencode($to_addrs_emails).
1146 '&to_email_addrs='.urlencode($fullName . ' <' . $emailAddress . '>').
1147 '&return_module='.$ret_module.
1148 '&return_action='.$ret_action.
1149 '&return_id='.$ret_id;
1151 //Generate the compose package for the quick create options.
1152 //$json = getJSONobj();
1153 //$composeOptionsLink = $json->encode( array('composeOptionsLink' => $emailLinkUrl,'id' => $focus->id) );
1154 require_once('modules/Emails/EmailUI.php');
1155 $eUi = new EmailUI();
1156 $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1158 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1162 $emailLink = '<a href="mailto:'.$emailAddress.'" class="'.$class.'">';
1169 * returns opening <a href=xxxx for a contact, account, etc
1170 * cascades from User set preference to System-wide default
1171 * @return string link
1172 * @param attribute the email addy
1173 * @param focus the parent bean
1175 * @param return_module
1176 * @param return_action
1180 function getEmailLink($attribute, &$focus, $contact_id='', $ret_module='', $ret_action='DetailView', $ret_id='', $class='') {
1182 global $sugar_config;
1184 if(!isset($sugar_config['email_default_client'])) {
1185 $this->setDefaultsInConfig();
1188 $userPref = $this->getPreference('email_link_type');
1189 $defaultPref = $sugar_config['email_default_client'];
1190 if($userPref != '') {
1191 $client = $userPref;
1193 $client = $defaultPref;
1196 if($client == 'sugar') {
1199 $to_addrs_names = '';
1200 $to_addrs_emails = '';
1202 $fullName = !empty($focus->name) ? $focus->name : '';
1204 if(!empty($focus->$attribute)) {
1205 $email = $focus->$attribute;
1209 if(empty($ret_module)) $ret_module = $focus->module_dir;
1210 if(empty($ret_id)) $ret_id = $focus->id;
1211 if($focus->object_name == 'Contact') {
1212 // Bug #48555 Not User Name Format of User's locale.
1213 $focus->_create_proper_name_field();
1214 $fullName = $focus->name;
1215 $contact_id = $focus->id;
1216 $to_addrs_ids = $focus->id;
1217 $to_addrs_names = $fullName;
1218 $to_addrs_emails = $focus->email1;
1221 $emailLinkUrl = 'contact_id='.$contact_id.
1222 '&parent_type='.$focus->module_dir.
1223 '&parent_id='.$focus->id.
1224 '&parent_name='.urlencode($fullName).
1225 '&to_addrs_ids='.$to_addrs_ids.
1226 '&to_addrs_names='.urlencode($to_addrs_names).
1227 '&to_addrs_emails='.urlencode($to_addrs_emails).
1228 '&to_email_addrs='.urlencode($fullName . ' <' . $email . '>').
1229 '&return_module='.$ret_module.
1230 '&return_action='.$ret_action.
1231 '&return_id='.$ret_id;
1233 //Generate the compose package for the quick create options.
1234 require_once('modules/Emails/EmailUI.php');
1235 $eUi = new EmailUI();
1236 $j_quickComposeOptions = $eUi->generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, true);
1237 $emailLink = "<a href='javascript:void(0);' onclick='SUGAR.quickCompose.init($j_quickComposeOptions);' class='$class'>";
1241 $emailLink = '<a href="mailto:'.$focus->$attribute.'" class="'.$class.'">';
1249 * gets a human-readable explanation of the format macro
1250 * @return string Human readable name format
1252 function getLocaleFormatDesc() {
1254 global $mod_strings;
1255 global $app_strings;
1257 $format['f'] = $mod_strings['LBL_LOCALE_DESC_FIRST'];
1258 $format['l'] = $mod_strings['LBL_LOCALE_DESC_LAST'];
1259 $format['s'] = $mod_strings['LBL_LOCALE_DESC_SALUTATION'];
1260 $format['t'] = $mod_strings['LBL_LOCALE_DESC_TITLE'];
1262 $name['f'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
1263 $name['l'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
1264 $name['s'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
1265 $name['t'] = $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
1267 $macro = $locale->getLocaleFormatMacro();
1271 for($i=0; $i<strlen($macro); $i++) {
1272 if(array_key_exists($macro{$i}, $format)) {
1273 $ret1 .= "<i>".$format[$macro{$i}]."</i>";
1274 $ret2 .= "<i>".$name[$macro{$i}]."</i>";
1276 $ret1 .= $macro{$i};
1277 $ret2 .= $macro{$i};
1280 return $ret1."<br />".$ret2;
1286 * Here are the multi level admin access check functions.
1290 * Helper function to remap some modules around ACL wise
1294 protected function _fixupModuleForACL($module) {
1295 if($module=='ContractTypes') {
1296 $module = 'Contracts';
1298 if(preg_match('/Product[a-zA-Z]*/',$module)) {
1299 $module = 'Products';
1305 * Helper function that enumerates the list of modules and checks if they are an admin/dev.
1306 * The code was just too similar to copy and paste.
1310 protected function _getModulesForACL($type='dev'){
1311 $isDev = $type=='dev';
1312 $isAdmin = $type=='admin';
1315 $myModules = array();
1317 if (!is_array($beanList) ) {
1321 // These modules don't take kindly to the studio trying to play about with them.
1322 static $ignoredModuleList = array('iFrames','Feeds','Home','Dashboard','Calendar','Activities','Reports');
1325 $actions = ACLAction::getUserActions($this->id);
1327 foreach ($beanList as $module=>$val) {
1328 // Remap the module name
1329 $module = $this->_fixupModuleForACL($module);
1330 if (in_array($module,$myModules)) {
1331 // Already have the module in the list
1334 if (in_array($module,$ignoredModuleList)) {
1335 // You can't develop on these modules.
1341 if (($this->isAdmin() && isset($actions[$module][$key]))
1343 $myModules[] = $module;
1350 * Is this user a system wide admin
1354 public function isAdmin() {
1355 if(isset($this->is_admin)
1356 &&($this->is_admin == '1' || $this->is_admin === 'on')){
1362 * Is this user a developer for any module
1366 public function isDeveloperForAnyModule() {
1367 if ($this->isAdmin()) {
1373 * List the modules a user has developer access to
1377 public function getDeveloperModules() {
1378 static $developerModules;
1379 if (!isset($_SESSION[$this->user_name.'_get_developer_modules_for_user']) ) {
1380 $_SESSION[$this->user_name.'_get_developer_modules_for_user'] = $this->_getModulesForACL('dev');
1383 return $_SESSION[$this->user_name.'_get_developer_modules_for_user'];
1386 * Is this user a developer for the specified module
1390 public function isDeveloperForModule($module) {
1391 if ($this->isAdmin()) {
1395 $devModules = $this->getDeveloperModules();
1397 $module = $this->_fixupModuleForACL($module);
1399 if (in_array($module,$devModules) ) {
1406 * List the modules a user has admin access to
1410 public function getAdminModules() {
1411 if (!isset($_SESSION[$this->user_name.'_get_admin_modules_for_user']) ) {
1412 $_SESSION[$this->user_name.'_get_admin_modules_for_user'] = $this->_getModulesForACL('admin');
1415 return $_SESSION[$this->user_name.'_get_admin_modules_for_user'];
1418 * Is this user an admin for the specified module
1422 public function isAdminForModule($module) {
1423 if ($this->isAdmin()) {
1427 $adminModules = $this->getAdminModules();
1429 $module = $this->_fixupModuleForACL($module);
1431 if (in_array($module,$adminModules) ) {
1438 * Whether or not based on the user's locale if we should show the last name first.
1442 public function showLastNameFirst(){
1444 $localeFormat = $locale->getLocaleFormatMacro($this);
1445 if ( strpos($localeFormat,'l') > strpos($localeFormat,'f') ) {
1454 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false)
1455 { //call parent method, specifying for array to be returned
1456 $ret_array = parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, true,$parentbean, $singleSelect);
1458 //if this is being called from webservices, then run additional code
1459 if(!empty($GLOBALS['soap_server_object'])){
1461 //if this is a single select, then secondary queries are being run that may result in duplicate rows being returned through the
1462 //left joins with meetings/tasks/call. We need to change the left joins to include a null check (bug 40250)
1465 //retrieve the 'from' string and make lowercase for easier manipulation
1466 $left_str = strtolower($ret_array['from']);
1467 $lefts = explode('left join', $left_str);
1470 //explode on the left joins and process each one
1471 foreach($lefts as $ljVal){
1472 //grab the join alias
1473 $onPos = strpos( $ljVal, ' on');
1474 if($onPos === false){
1475 $new_left_str .=' '.$ljVal.' ';
1478 $spacePos = strrpos(substr($ljVal, 0, $onPos),' ');
1479 $alias = substr($ljVal,$spacePos,$onPos-$spacePos);
1481 //add null check to end of the Join statement
1482 // Bug #46390 to use id_c field instead of id field for custom tables
1483 if(substr($alias, -5) != '_cstm')
1485 $ljVal =' LEFT JOIN '.$ljVal.' and '.$alias.'.id is null ';
1489 $ljVal =' LEFT JOIN '.$ljVal.' and '.$alias.'.id_c is null ';
1492 //add statement into new string
1493 $new_left_str .= $ljVal;
1495 //replace the old string with the new one
1496 $ret_array['from'] = $new_left_str;
1500 //return array or query string
1506 return $ret_array['select'] . $ret_array['from'] . $ret_array['where']. $ret_array['order_by'];
1513 * Get user first day of week.
1515 * @param [User] $user user object, current user if not specified
1516 * @return int : 0 = Sunday, 1 = Monday, etc...
1518 public function get_first_day_of_week()
1520 $fdow = $this->getPreference('fdow');
1530 * Method for password generation
1533 * @return string password
1535 public static function generatePassword()
1537 $res = $GLOBALS['sugar_config']['passwordsetting'];
1539 //chars to select from
1540 $LOWERCASE = "abcdefghijklmnpqrstuvwxyz";
1541 $NUMBER = "0123456789";
1542 $UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1543 $SPECIAL = '~!@#$%^&*()_+=-{}|';
1545 $charBKT .= $UPPERCASE . $LOWERCASE . $NUMBER;
1549 // Create random characters for the ones that doesnt have requirements
1550 for ($i=0; $i < $length - $condition; $i ++) // loop and create password
1552 $password = $password . substr ($charBKT, rand() % strlen($charBKT), 1);
1559 * Send new password or link to user
1561 * @param string $templateId Id of email template
1562 * @param array $additionalData additional params: link, url, password
1563 * @return array status: true|false, message: error message, if status = false and message = '' it means that send method has returned false
1565 public function sendEmailForPassword($templateId, array $additionalData = array())
1567 global $sugar_config, $current_user;
1568 $mod_strings = return_module_language('', 'Users');
1574 $emailTemp = new EmailTemplate();
1575 $emailTemp->disable_row_level_security = true;
1576 if ($emailTemp->retrieve($templateId) == '')
1578 $result['message'] = $mod_strings['LBL_EMAIL_TEMPLATE_MISSING'];
1582 //replace instance variables in email templates
1583 $htmlBody = $emailTemp->body_html;
1584 $body = $emailTemp->body;
1585 if (isset($additionalData['link']) && $additionalData['link'] == true)
1587 $htmlBody = str_replace('$contact_user_link_guid', $additionalData['url'], $htmlBody);
1588 $body = str_replace('$contact_user_link_guid', $additionalData['url'], $body);
1592 $htmlBody = str_replace('$contact_user_user_hash', $additionalData['password'], $htmlBody);
1593 $body = str_replace('$contact_user_user_hash', $additionalData['password'], $body);
1595 // Bug 36833 - Add replacing of special value $instance_url
1596 $htmlBody = str_replace('$config_site_url', $sugar_config['site_url'], $htmlBody);
1597 $body = str_replace('$config_site_url', $sugar_config['site_url'], $body);
1599 $htmlBody = str_replace('$contact_user_user_name', $this->user_name, $htmlBody);
1600 $htmlBody = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $htmlBody);
1601 $body = str_replace('$contact_user_user_name', $this->user_name, $body);
1602 $body = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $body);
1603 $emailTemp->body_html = $htmlBody;
1604 $emailTemp->body = $body;
1606 $itemail = $this->emailAddress->getPrimaryAddress($this);
1607 //retrieve IT Admin Email
1608 //_ppd( $emailTemp->body_html);
1609 //retrieve email defaults
1610 $emailObj = new Email();
1611 $defaults = $emailObj->getSystemDefaultEmail();
1612 require_once('include/SugarPHPMailer.php');
1613 $mail = new SugarPHPMailer();
1614 $mail->setMailerForSystem();
1615 //$mail->IsHTML(true);
1616 $mail->From = $defaults['email'];
1617 $mail->FromName = $defaults['name'];
1618 $mail->ClearAllRecipients();
1619 $mail->ClearReplyTos();
1620 $mail->Subject = from_html($emailTemp->subject);
1621 if ($emailTemp->text_only != 1)
1623 $mail->IsHTML(true);
1624 $mail->Body = from_html($emailTemp->body_html);
1625 $mail->AltBody = from_html($emailTemp->body);
1629 $mail->Body_html = from_html($emailTemp->body_html);
1630 $mail->Body = from_html($emailTemp->body);
1632 if ($mail->Body == '' && $current_user->is_admin)
1634 global $app_strings;
1635 $result['message'] = $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT'];
1638 if ($mail->Mailer == 'smtp' && $mail->Host =='' && $current_user->is_admin)
1640 $result['message'] = $mod_strings['ERR_SERVER_SMTP_EMPTY'];
1644 $mail->prepForOutbound();
1645 $hasRecipients = false;
1647 if (!empty($itemail))
1651 $mail->AddBCC($itemail);
1655 $mail->AddAddress($itemail);
1657 $hasRecipients = true;
1661 $result['status'] = @$mail->Send();
1664 if ($result['status'] == true)
1666 $emailObj->team_id = 1;
1667 $emailObj->to_addrs = '';
1668 $emailObj->type = 'archived';
1669 $emailObj->deleted = '0';
1670 $emailObj->name = $mail->Subject ;
1671 $emailObj->description = $mail->Body;
1672 $emailObj->description_html = null;
1673 $emailObj->from_addr = $mail->From;
1674 $emailObj->parent_type = 'User';
1675 $emailObj->date_sent = TimeDate::getInstance()->nowDb();
1676 $emailObj->modified_user_id = '1';
1677 $emailObj->created_by = '1';
1678 $emailObj->status = 'sent';
1680 if (!isset($additionalData['link']) || $additionalData['link'] == false)
1682 $user_hash = strtolower(md5($additionalData['password']));
1683 $this->setPreference('loginexpiration', '0');
1684 $this->setPreference('lockout', '');
1685 $this->setPreference('loginfailed', '0');
1686 $this->savePreferencesToDB();
1688 $now=TimeDate::getInstance()->nowDb();
1689 $query = "UPDATE $this->table_name SET user_hash='$user_hash', system_generated_password='1', pwd_last_changed='$now' where id='$this->id'";
1690 $this->db->query($query, true, "Error setting new password for $this->user_name: ");
1697 // Bug #48014 Must to send password to imported user if this action is required
1698 function afterImportSave()
1701 $this->user_hash == false
1703 && !$this->portal_only
1704 && isset($GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON'])
1705 && $GLOBALS['sugar_config']['passwordsetting']['SystemGeneratedPasswordON']
1708 $backUpPost = $_POST;
1710 'userId' => $this->id
1713 require('modules/Users/GeneratePassword.php');
1714 $result = ob_get_clean();
1715 $_POST = $backUpPost;
1716 return $result == true;