[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/Users/ -> Users.php (source)

   1  <?php
   2  /*********************************************************************************
   3   * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
   4   * ("License"); You may not use this file except in compliance with the
   5   * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
   6   * Software distributed under the License is distributed on an  "AS IS"  basis,
   7   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
   8   * the specific language governing rights and limitations under the License.
   9   * The Original Code is:  SugarCRM Open Source
  10   * The Initial Developer of the Original Code is SugarCRM, Inc.
  11   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
  12   * All Rights Reserved.
  13   * Contributor(s): ______________________________________.
  14   ********************************************************************************/
  15  
  16  /*********************************************
  17   * With modifications by
  18   * Daniel Jabbour
  19   * iWebPress Incorporated, www.iwebpress.com
  20   * djabbour - a t - iwebpress - d o t - com
  21   ********************************************/
  22  
  23  /*********************************************************************************
  24   * $Header: /advent/projects/wesat/vtiger_crm/sugarcrm/modules/Users/Users.php,v 1.10 2005/04/19 14:40:48 ray Exp $
  25   * Description: TODO:  To be written.
  26   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  27   * All Rights Reserved.
  28   * Contributor(s): ______________________________________..
  29   ********************************************************************************/
  30  
  31  require_once ('include/logging.php');
  32  require_once ('include/database/PearDatabase.php');
  33  require_once ('include/utils/UserInfoUtil.php');
  34  require_once  'data/CRMEntity.php';
  35  require_once ('modules/Calendar/Activity.php');
  36  require_once ('modules/Contacts/Contacts.php');
  37  require_once ('data/Tracker.php');
  38  require_once  'include/utils/CommonUtils.php';
  39  require_once  'include/Webservices/Utils.php';
  40  require_once ('modules/Users/UserTimeZonesArray.php');
  41  require_once  'includes/runtime/Cache.php';
  42  
  43  // User is used to store customer information.
  44  /** Main class for the user module
  45   *
  46   */
  47  class Users extends CRMEntity {
  48      var $log;
  49      /**
  50       * @var PearDatabase
  51       */
  52      var $db;
  53      // Stored fields
  54      var $id;
  55      var $authenticated = false;
  56      var $error_string;
  57      var $is_admin;
  58      var $deleted;
  59  
  60      var $tab_name = Array('vtiger_users','vtiger_attachments','vtiger_user2role','vtiger_asteriskextensions');
  61      var $tab_name_index = Array('vtiger_users'=>'id','vtiger_attachments'=>'attachmentsid','vtiger_user2role'=>'userid','vtiger_asteriskextensions'=>'userid');
  62  
  63      var $table_name = "vtiger_users";
  64      var $table_index= 'id';
  65  
  66      // This is the list of fields that are in the lists.
  67      var $list_link_field= 'last_name';
  68  
  69      var $list_mode;
  70      var $popup_type;
  71  
  72      var $search_fields = Array(
  73              'Name'=>Array('vtiger_users'=>'last_name'),
  74              'Email'=>Array('vtiger_users'=>'email1'),
  75              'Email2'=>Array('vtiger_users'=>'email2')
  76      );
  77      var $search_fields_name = Array(
  78              'Name'=>'last_name',
  79              'Email'=>'email1',
  80              'Email2'=>'email2'
  81      );
  82  
  83      var $module_name = "Users";
  84  
  85      var $object_name = "User";
  86      var $user_preferences;
  87      var $homeorder_array = array('HDB','ALVT','PLVT','QLTQ','CVLVT','HLT','GRT','OLTSO','ILTI','MNL','OLTPO','LTFAQ', 'UA', 'PA');
  88  
  89      var $encodeFields = Array("first_name", "last_name", "description");
  90  
  91      // This is used to retrieve related fields from form posts.
  92      var $additional_column_fields = Array('reports_to_name');
  93  
  94      var $sortby_fields = Array('status','email1','email2','phone_work','is_admin','user_name','last_name');
  95  
  96      // This is the list of vtiger_fields that are in the lists.
  97      var $list_fields = Array(
  98              'First Name'=>Array('vtiger_users'=>'first_name'),
  99              'Last Name'=>Array('vtiger_users'=>'last_name'),
 100              'Role Name'=>Array('vtiger_user2role'=>'roleid'),
 101              'User Name'=>Array('vtiger_users'=>'user_name'),
 102              'Status'=>Array('vtiger_users'=>'status'),
 103              'Email'=>Array('vtiger_users'=>'email1'),
 104              'Email2'=>Array('vtiger_users'=>'email2'),
 105              'Admin'=>Array('vtiger_users'=>'is_admin'),
 106              'Phone'=>Array('vtiger_users'=>'phone_work')
 107      );
 108      var $list_fields_name = Array(
 109              'Last Name'=>'last_name',
 110              'First Name'=>'first_name',
 111              'Role Name'=>'roleid',
 112              'User Name'=>'user_name',
 113              'Status'=>'status',
 114              'Email'=>'email1',
 115              'Email2'=>'email2',
 116              'Admin'=>'is_admin',
 117              'Phone'=>'phone_work'
 118      );
 119  
 120      //Default Fields for Email Templates -- Pavani
 121      var $emailTemplate_defaultFields = array('first_name','last_name','title','department','phone_home','phone_mobile','signature','email1','email2','address_street','address_city','address_state','address_country','address_postalcode');
 122  
 123      var $popup_fields = array('last_name');
 124  
 125      // This is the list of fields that are in the lists.
 126      var $default_order_by = "user_name";
 127      var $default_sort_order = 'ASC';
 128  
 129      var $record_id;
 130      var $new_schema = true;
 131  
 132      var $DEFAULT_PASSWORD_CRYPT_TYPE; //'BLOWFISH', /* before PHP5.3*/ MD5;
 133  
 134      //Default Widgests
 135      var $default_widgets = array('PLVT', 'CVLVT', 'UA');
 136  
 137      /** constructor function for the main user class
 138       instantiates the Logger class and PearDatabase Class
 139       *
 140       */
 141  
 142      function Users() {
 143          $this->log = LoggerManager::getLogger('user');
 144          $this->log->debug("Entering Users() method ...");
 145          $this->db = PearDatabase::getInstance();
 146          $this->DEFAULT_PASSWORD_CRYPT_TYPE = (version_compare(PHP_VERSION, '5.3.0') >= 0)?
 147                  'PHP5.3MD5': 'MD5';
 148          $this->column_fields = getColumnFields('Users');
 149          $this->column_fields['currency_name'] = '';
 150          $this->column_fields['currency_code'] = '';
 151          $this->column_fields['currency_symbol'] = '';
 152          $this->column_fields['conv_rate'] = '';
 153          $this->log->debug("Exiting Users() method ...");
 154      }
 155  
 156      // Mike Crowe Mod --------------------------------------------------------Default ordering for us
 157      /**
 158       * Function to get sort order
 159       * return string  $sorder    - sortorder string either 'ASC' or 'DESC'
 160       */
 161      function getSortOrder() {
 162          global $log;
 163          $log->debug("Entering getSortOrder() method ...");
 164          if(isset($_REQUEST['sorder']))
 165              $sorder = $this->db->sql_escape_string($_REQUEST['sorder']);
 166          else
 167              $sorder = (($_SESSION['USERS_SORT_ORDER'] != '')?($_SESSION['USERS_SORT_ORDER']):($this->default_sort_order));
 168          $log->debug("Exiting getSortOrder method ...");
 169          return $sorder;
 170      }
 171  
 172      /**
 173       * Function to get order by
 174       * return string  $order_by    - fieldname(eg: 'subject')
 175       */
 176      function getOrderBy() {
 177          global $log;
 178          $log->debug("Entering getOrderBy() method ...");
 179  
 180          $use_default_order_by = '';
 181          if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) {
 182              $use_default_order_by = $this->default_order_by;
 183          }
 184  
 185          if (isset($_REQUEST['order_by']))
 186              $order_by = $this->db->sql_escape_string($_REQUEST['order_by']);
 187          else
 188              $order_by = (($_SESSION['USERS_ORDER_BY'] != '')?($_SESSION['USERS_ORDER_BY']):($use_default_order_by));
 189          $log->debug("Exiting getOrderBy method ...");
 190          return $order_by;
 191      }
 192      // Mike Crowe Mod --------------------------------------------------------
 193  
 194      /** Function to set the user preferences in the session
 195       * @param $name -- name:: Type varchar
 196       * @param $value -- value:: Type varchar
 197       *
 198       */
 199      function setPreference($name, $value) {
 200          if(!isset($this->user_preferences)) {
 201              if(isset($_SESSION["USER_PREFERENCES"]))
 202                  $this->user_preferences = $_SESSION["USER_PREFERENCES"];
 203              else
 204                  $this->user_preferences = array();
 205          }
 206          if(!array_key_exists($name,$this->user_preferences )|| $this->user_preferences[$name] != $value) {
 207              $this->log->debug("Saving To Preferences:". $name."=".$value);
 208              $this->user_preferences[$name] = $value;
 209              $this->savePreferecesToDB();
 210  
 211          }
 212          $_SESSION[$name] = $value;
 213  
 214  
 215      }
 216  
 217  
 218      /** Function to save the user preferences to db
 219       *
 220       */
 221  
 222      function savePreferecesToDB() {
 223          $data = base64_encode(serialize($this->user_preferences));
 224          $query = "UPDATE $this->table_name SET user_preferences=? where id=?";
 225          $result =& $this->db->pquery($query, array($data, $this->id));
 226          $this->log->debug("SAVING: PREFERENCES SIZE ". strlen($data)."ROWS AFFECTED WHILE UPDATING USER PREFERENCES:".$this->db->getAffectedRowCount($result));
 227          $_SESSION["USER_PREFERENCES"] = $this->user_preferences;
 228      }
 229  
 230      /** Function to load the user preferences from db
 231       *
 232       */
 233      function loadPreferencesFromDB($value) {
 234  
 235          if(isset($value) && !empty($value)) {
 236              $this->log->debug("LOADING :PREFERENCES SIZE ". strlen($value));
 237              $this->user_preferences = unserialize(base64_decode($value));
 238              $_SESSION = array_merge($this->user_preferences, $_SESSION);
 239              $this->log->debug("Finished Loading");
 240              $_SESSION["USER_PREFERENCES"] = $this->user_preferences;
 241  
 242  
 243          }
 244  
 245      }
 246  
 247  	protected function get_user_hash($input) {
 248          return strtolower(md5($input));
 249      }
 250  
 251  
 252      /**
 253       * @return string encrypted password for storage in DB and comparison against DB password.
 254       * @param string $user_name - Must be non null and at least 2 characters
 255       * @param string $user_password - Must be non null and at least 1 character.
 256       * @desc Take an unencrypted username and password and return the encrypted password
 257       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 258       * All Rights Reserved..
 259       * Contributor(s): ______________________________________..
 260       */
 261      function encrypt_password($user_password, $crypt_type='') {
 262          // encrypt the password.
 263          $salt = substr($this->column_fields["user_name"], 0, 2);
 264  
 265          // Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4923
 266          if($crypt_type == '') {
 267              // Try to get the crypt_type which is in database for the user
 268              $crypt_type = $this->get_user_crypt_type();
 269          }
 270  
 271          // For more details on salt format look at: http://in.php.net/crypt
 272          if($crypt_type == 'MD5') {
 273              $salt = '$1$' . $salt . '$';
 274          } elseif($crypt_type == 'BLOWFISH') {
 275              $salt = '$2$' . $salt . '$';
 276          } elseif($crypt_type == 'PHP5.3MD5') {
 277              //only change salt for php 5.3 or higher version for backward
 278              //compactibility.
 279              //crypt API is lot stricter in taking the value for salt.
 280              $salt = '$1$' . str_pad($salt, 9, '0');
 281          }
 282  
 283          $encrypted_password = crypt($user_password, $salt);
 284          return $encrypted_password;
 285      }
 286  
 287  
 288      /** Function to authenticate the current user with the given password
 289       * @param $password -- password::Type varchar
 290       * @returns true if authenticated or false if not authenticated
 291       */
 292      function authenticate_user($password) {
 293          $usr_name = $this->column_fields["user_name"];
 294  
 295          $query = "SELECT * from $this->table_name where user_name=? AND user_hash=?";
 296          $params = array($usr_name, $password);
 297          $result = $this->db->requirePsSingleResult($query, $params, false);
 298  
 299          if(empty($result)) {
 300              $this->log->fatal("SECURITY: failed login by $usr_name");
 301              return false;
 302          }
 303  
 304          return true;
 305      }
 306  
 307      /** Function for validation check
 308       *
 309       */
 310      function validation_check($validate, $md5, $alt='') {
 311          $validate = base64_decode($validate);
 312          if(file_exists($validate) && $handle = fopen($validate, 'rb', true)) {
 313              $buffer = fread($handle, filesize($validate));
 314              if(md5($buffer) == $md5 || (!empty($alt) && md5($buffer) == $alt)) {
 315                  return 1;
 316              }
 317              return -1;
 318  
 319          }else {
 320              return -1;
 321          }
 322  
 323      }
 324  
 325      /** Function for authorization check
 326       *
 327       */
 328      function authorization_check($validate, $authkey, $i) {
 329          $validate = base64_decode($validate);
 330          $authkey = base64_decode($authkey);
 331          if(file_exists($validate) && $handle = fopen($validate, 'rb', true)) {
 332              $buffer = fread($handle, filesize($validate));
 333              if(substr_count($buffer, $authkey) < $i)
 334                  return -1;
 335          }else {
 336              return -1;
 337          }
 338  
 339      }
 340      /**
 341       * Checks the config.php AUTHCFG value for login type and forks off to the proper module
 342       *
 343       * @param string $user_password - The password of the user to authenticate
 344       * @return true if the user is authenticated, false otherwise
 345       */
 346      function doLogin($user_password) {
 347          global $AUTHCFG;
 348          $usr_name = $this->column_fields["user_name"];
 349  
 350          switch (strtoupper($AUTHCFG['authType'])) {
 351              case 'LDAP':
 352                  $this->log->debug("Using LDAP authentication");
 353                  require_once('modules/Users/authTypes/LDAP.php');
 354                  $result = ldapAuthenticate($this->column_fields["user_name"], $user_password);
 355                  if ($result == NULL) {
 356                      return false;
 357                  } else {
 358                      return true;
 359                  }
 360                  break;
 361  
 362              case 'AD':
 363                  $this->log->debug("Using Active Directory authentication");
 364                  require_once('modules/Users/authTypes/adLDAP.php');
 365                  $adldap = new adLDAP();
 366                  if ($adldap->authenticate($this->column_fields["user_name"],$user_password)) {
 367                      return true;
 368                  } else {
 369                      return false;
 370                  }
 371                  break;
 372  
 373              default:
 374                  $this->log->debug("Using integrated/SQL authentication");
 375                  $query = "SELECT crypt_type, user_name FROM $this->table_name WHERE user_name=?";
 376                  $result = $this->db->requirePsSingleResult($query, array($usr_name), false);
 377                  if (empty($result)) {
 378                      return false;
 379                  }
 380                  $crypt_type = $this->db->query_result($result, 0, 'crypt_type');
 381                  $this->column_fields["user_name"] = $this->db->query_result($result, 0, 'user_name');
 382                  $encrypted_password = $this->encrypt_password($user_password, $crypt_type);
 383                  $query = "SELECT 1 from $this->table_name where user_name=? AND user_password=? AND status = ?";
 384                  $result = $this->db->requirePsSingleResult($query, array($usr_name, $encrypted_password, 'Active'), false);
 385                  if (empty($result)) {
 386                      return false;
 387                  } else {
 388                      return true;
 389                  }
 390                  break;
 391          }
 392          return false;
 393      }
 394  
 395  
 396      /**
 397       * Load a user based on the user_name in $this
 398       * @return -- this if load was successul and null if load failed.
 399       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 400       * All Rights Reserved..
 401       * Contributor(s): ______________________________________..
 402       */
 403      function load_user($user_password) {
 404          $usr_name = $this->column_fields["user_name"];
 405          if(isset($_SESSION['loginattempts'])) {
 406              $_SESSION['loginattempts'] += 1;
 407          }else {
 408              $_SESSION['loginattempts'] = 1;
 409          }
 410          if($_SESSION['loginattempts'] > 5) {
 411              $this->log->warn("SECURITY: " . $usr_name . " has attempted to login ".     $_SESSION['loginattempts'] . " times.");
 412          }
 413          $this->log->debug("Starting user load for $usr_name");
 414  
 415          if( !isset($this->column_fields["user_name"]) || $this->column_fields["user_name"] == "" || !isset($user_password) || $user_password == "")
 416              return null;
 417  
 418          $authCheck = false;
 419          $authCheck = $this->doLogin($user_password);
 420  
 421          if(!$authCheck) {
 422              $this->log->warn("User authentication for $usr_name failed");
 423              return null;
 424          }
 425  
 426          // Get the fields for the user
 427          $query = "SELECT * from $this->table_name where user_name='$usr_name'";
 428          $result = $this->db->requireSingleResult($query, false);
 429  
 430          $row = $this->db->fetchByAssoc($result);
 431          $this->column_fields = $row;
 432          $this->id = $row['id'];
 433  
 434          $user_hash = $this->get_user_hash($user_password);
 435  
 436          // If there is no user_hash is not present or is out of date, then create a new one.
 437          if(!isset($row['user_hash']) || $row['user_hash'] != $user_hash) {
 438              $query = "UPDATE $this->table_name SET user_hash=? where id=?";
 439              $this->db->pquery($query, array($user_hash, $row['id']), true, "Error setting new hash for {$row['user_name']}: ");
 440          }
 441          $this->loadPreferencesFromDB($row['user_preferences']);
 442  
 443  
 444          if ($row['status'] != "Inactive") $this->authenticated = true;
 445  
 446          unset($_SESSION['loginattempts']);
 447          return $this;
 448      }
 449  
 450      /**
 451       * Get crypt type to use for password for the user.
 452       * Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4923
 453       */
 454      function get_user_crypt_type() {
 455  
 456          $crypt_res = null;
 457          $crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
 458  
 459          // For backward compatability, we need to make sure to handle this case.
 460          global $adb;
 461          $table_cols = $adb->getColumnNames("vtiger_users");
 462          if(!in_array("crypt_type", $table_cols)) {
 463              return $crypt_type;
 464          }
 465  
 466          if(isset($this->id)) {
 467              // Get the type of crypt used on password before actual comparision
 468              $qcrypt_sql = "SELECT crypt_type from $this->table_name where id=?";
 469              $crypt_res = $this->db->pquery($qcrypt_sql, array($this->id), true);
 470          } else if(isset($this->column_fields["user_name"])) {
 471              $qcrypt_sql = "SELECT crypt_type from $this->table_name where user_name=?";
 472              $crypt_res = $this->db->pquery($qcrypt_sql, array($this->column_fields["user_name"]));
 473          } else {
 474              $crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
 475          }
 476  
 477          if($crypt_res && $this->db->num_rows($crypt_res)) {
 478              $crypt_row = $this->db->fetchByAssoc($crypt_res);
 479              $crypt_type = $crypt_row['crypt_type'];
 480          }
 481          return $crypt_type;
 482      }
 483  
 484      /**
 485       * @param string $user name - Must be non null and at least 1 character.
 486       * @param string $user_password - Must be non null and at least 1 character.
 487       * @param string $new_password - Must be non null and at least 1 character.
 488       * @return boolean - If passwords pass verification and query succeeds, return true, else return false.
 489       * @desc Verify that the current password is correct and write the new password to the DB.
 490       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 491       * All Rights Reserved..
 492       * Contributor(s): ______________________________________..
 493       */
 494      function change_password($user_password, $new_password, $dieOnError = true) {
 495  
 496          $usr_name = $this->column_fields["user_name"];
 497          global $mod_strings;
 498          global $current_user;
 499          $this->log->debug("Starting password change for $usr_name");
 500  
 501          if( !isset($new_password) || $new_password == "") {
 502              $this->error_string = $mod_strings['ERR_PASSWORD_CHANGE_FAILED_1'].$user_name.$mod_strings['ERR_PASSWORD_CHANGE_FAILED_2'];
 503              return false;
 504          }
 505  
 506          if (!is_admin($current_user)) {
 507                #commenting this as the the transaction is already started in vtws_changepassword
 508  //            $this->db->startTransaction();
 509              if(!$this->verifyPassword($user_password)) {
 510                  $this->log->warn("Incorrect old password for $usr_name");
 511                  $this->error_string = $mod_strings['ERR_PASSWORD_INCORRECT_OLD'];
 512                  return false;
 513              }
 514              if($this->db->hasFailedTransaction()) {
 515                  if($dieOnError) {
 516                      die("error verifying old transaction[".$this->db->database->ErrorNo()."] ".
 517                              $this->db->database->ErrorMsg());
 518                  }
 519                  return false;
 520              }
 521          }
 522  
 523  
 524          $user_hash = $this->get_user_hash($new_password);
 525  
 526          //set new password
 527          $crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
 528          $encrypted_new_password = $this->encrypt_password($new_password, $crypt_type);
 529  
 530          $query = "UPDATE $this->table_name SET user_password=?, confirm_password=?, user_hash=?, ".
 531                  "crypt_type=? where id=?";
 532            #commenting this as the the transaction is already started in vtws_changepassword
 533  //        $this->db->startTransaction();
 534          $this->db->pquery($query, array($encrypted_new_password, $encrypted_new_password,
 535                  $user_hash, $crypt_type, $this->id));
 536          if($this->db->hasFailedTransaction()) {
 537              if($dieOnError) {
 538                  die("error setting new password: [".$this->db->database->ErrorNo()."] ".
 539                          $this->db->database->ErrorMsg());
 540              }
 541              return false;
 542          }
 543  
 544          // Fill up the post-save state of the instance.
 545          if (empty($this->column_fields['user_hash'])) {
 546              $this->column_fields['user_hash'] = $user_hash;
 547          }
 548  
 549          $this->column_fields['user_password'] = $encrypted_new_password;
 550          $this->column_fields['confirm_password'] = $encrypted_new_password;
 551  
 552          $this->triggerAfterSaveEventHandlers();
 553          return true;
 554      }
 555  
 556      function de_cryption($data) {
 557          require_once ('include/utils/encryption.php');
 558          $de_crypt = new Encryption();
 559          if(isset($data)) {
 560              $decrypted_password = $de_crypt->decrypt($data);
 561          }
 562          return $decrypted_password;
 563      }
 564      function changepassword($newpassword) {
 565          require_once ('include/utils/encryption.php');
 566          $en_crypt = new Encryption();
 567          if( isset($newpassword)) {
 568              $encrypted_password = $en_crypt->encrypt($newpassword);
 569          }
 570  
 571          return $encrypted_password;
 572      }
 573  
 574      function verifyPassword($password) {
 575          $query = "SELECT user_name,user_password,crypt_type FROM {$this->table_name} WHERE id=?";
 576          $result =$this->db->pquery($query, array($this->id));
 577          $row = $this->db->fetchByAssoc($result);
 578          $this->log->debug("select old password query: $query");
 579          $this->log->debug("return result of $row");
 580          $encryptedPassword = $this->encrypt_password($password, $row['crypt_type']);
 581          if($encryptedPassword != $row['user_password']) {
 582              return false;
 583          }
 584          return true;
 585      }
 586  
 587      function is_authenticated() {
 588          return $this->authenticated;
 589      }
 590  
 591  
 592      /** gives the user id for the specified user name
 593       * @param $user_name -- user name:: Type varchar
 594       * @returns user id
 595       */
 596  
 597      function retrieve_user_id($user_name) {
 598          global $adb;
 599          $query = "SELECT id from vtiger_users where user_name=? AND deleted=0";
 600          $result  =$adb->pquery($query, array($user_name));
 601          $userid = $adb->query_result($result,0,'id');
 602          return $userid;
 603      }
 604  
 605      /**
 606       * @return -- returns a list of all users in the system.
 607       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 608       * All Rights Reserved..
 609       * Contributor(s): ______________________________________..
 610       */
 611      function verify_data() {
 612          $usr_name = $this->column_fields["user_name"];
 613          global $mod_strings;
 614  
 615          $query = "SELECT user_name from vtiger_users where user_name=? AND id<>? AND deleted=0";
 616          $result =$this->db->pquery($query, array($usr_name, $this->id), true, "Error selecting possible duplicate users: ");
 617          $dup_users = $this->db->fetchByAssoc($result);
 618  
 619          $query = "SELECT user_name from vtiger_users where is_admin = 'on' AND deleted=0";
 620          $result =$this->db->pquery($query, array(), true, "Error selecting possible duplicate vtiger_users: ");
 621          $last_admin = $this->db->fetchByAssoc($result);
 622  
 623          $this->log->debug("last admin length: ".count($last_admin));
 624          $this->log->debug($last_admin['user_name']." == ".$usr_name);
 625  
 626          $verified = true;
 627          if($dup_users != null) {
 628              $this->error_string .= $mod_strings['ERR_USER_NAME_EXISTS_1'].$usr_name.''.$mod_strings['ERR_USER_NAME_EXISTS_2'];
 629              $verified = false;
 630          }
 631          if(!isset($_REQUEST['is_admin']) &&
 632                  count($last_admin) == 1 &&
 633                  $last_admin['user_name'] == $usr_name) {
 634              $this->log->debug("last admin length: ".count($last_admin));
 635  
 636              $this->error_string .= $mod_strings['ERR_LAST_ADMIN_1'].$usr_name.$mod_strings['ERR_LAST_ADMIN_2'];
 637              $verified = false;
 638          }
 639  
 640          return $verified;
 641      }
 642  
 643      /** Function to return the column name array
 644       *
 645       */
 646  
 647      function getColumnNames_User() {
 648  
 649          $mergeflds = array("FIRSTNAME","LASTNAME","USERNAME","SECONDARYEMAIL","TITLE","OFFICEPHONE","DEPARTMENT",
 650                  "MOBILE","OTHERPHONE","FAX","EMAIL",
 651                  "HOMEPHONE","OTHEREMAIL","PRIMARYADDRESS",
 652                  "CITY","STATE","POSTALCODE","COUNTRY");
 653          return $mergeflds;
 654      }
 655  
 656  
 657      function fill_in_additional_list_fields() {
 658          $this->fill_in_additional_detail_fields();
 659      }
 660  
 661      function fill_in_additional_detail_fields() {
 662          $query = "SELECT u1.first_name, u1.last_name from vtiger_users u1, vtiger_users u2 where u1.id = u2.reports_to_id AND u2.id = ? and u1.deleted=0";
 663          $result =$this->db->pquery($query, array($this->id), true, "Error filling in additional detail vtiger_fields") ;
 664  
 665          $row = $this->db->fetchByAssoc($result);
 666          $this->log->debug("additional detail query results: $row");
 667  
 668          if($row != null) {
 669              $this->reports_to_name = stripslashes(getFullNameFromArray('Users', $row));
 670          }
 671          else {
 672              $this->reports_to_name = '';
 673          }
 674      }
 675  
 676  
 677      /** Function to get the current user information from the user_privileges file
 678       * @param $userid -- user id:: Type integer
 679       * @returns user info in $this->column_fields array:: Type array
 680       *
 681       */
 682  
 683      function retrieveCurrentUserInfoFromFile($userid) {
 684          checkFileAccessForInclusion('user_privileges/user_privileges_'.$userid.'.php');
 685          require('user_privileges/user_privileges_'.$userid.'.php');
 686          foreach($this->column_fields as $field=>$value_iter) {
 687              if(isset($user_info[$field])) {
 688                  $this->$field = $user_info[$field];
 689                  $this->column_fields[$field] = $user_info[$field];
 690              }
 691          }
 692          $this->id = $userid;
 693          return $this;
 694      }
 695  
 696      /** Function to save the user information into the database
 697       * @param $module -- module name:: Type varchar
 698       *
 699       */
 700      function saveentity($module) {
 701          global $current_user;//$adb added by raju for mass mailing
 702          $insertion_mode = $this->mode;
 703          if(empty($this->column_fields['time_zone'])) {
 704              $dbDefaultTimeZone = DateTimeField::getDBTimeZone();
 705              $this->column_fields['time_zone'] = $dbDefaultTimeZone;
 706              $this->time_zone = $dbDefaultTimeZone;
 707          }
 708          if(empty($this->column_fields['currency_id'])) {
 709              $this->column_fields['currency_id'] = CurrencyField::getDBCurrencyId();
 710          }
 711          if(empty($this->column_fields['date_format'])) {
 712              $this->column_fields['date_format'] = 'yyyy-mm-dd';
 713          }
 714  
 715          if(empty($this->column_fields['start_hour'])) {
 716              $this->column_fields['start_hour'] = '09:00';
 717          }
 718  
 719          if(empty($this->column_fields['dayoftheweek'])) {
 720              $this->column_fields['dayoftheweek'] = 'Sunday';
 721          }
 722  
 723          if(empty($this->column_fields['callduration'])) {
 724              $this->column_fields['callduration'] = 5;
 725          }
 726  
 727          if(empty($this->column_fields['othereventduration'])) {
 728              $this->column_fields['othereventduration'] = 5;
 729          }
 730  
 731          if(empty($this->column_fields['hour_format'])) {
 732              $this->column_fields['hour_format'] = 12;
 733          }
 734  
 735          if(empty($this->column_fields['activity_view'])) {
 736              $this->column_fields['activity_view'] = 'Today';
 737          }
 738  
 739          if(empty($this->column_fields['calendarsharedtype'])) {
 740              $this->column_fields['calendarsharedtype'] = 'public';
 741          }
 742  
 743          if(empty($this->column_fields['default_record_view'])) {
 744              $this->column_fields['default_record_view'] = 'Summary';
 745          }
 746  
 747          if(empty($this->column_fields['status'])) {
 748              $this->column_fields['status'] = 'Active';
 749          }
 750  
 751          if(empty($this->column_fields['currency_decimal_separator'])) {
 752              $this->column_fields['currency_decimal_separator'] = '.';
 753          }
 754  
 755          if(empty($this->column_fields['currency_grouping_separator'])) {
 756              $this->column_fields['currency_grouping_separator'] = ',';
 757          }
 758  
 759          $this->db->println("TRANS saveentity starts $module");
 760          $this->db->startTransaction();
 761          foreach($this->tab_name as $table_name) {
 762              if($table_name == 'vtiger_attachments') {
 763                  $this->insertIntoAttachment($this->id,$module);
 764              }
 765              else {
 766                  $this->insertIntoEntityTable($table_name, $module);
 767              }
 768          }
 769          require_once ('modules/Users/CreateUserPrivilegeFile.php');
 770          createUserPrivilegesfile($this->id);
 771          unset($_SESSION['next_reminder_interval']);
 772          unset($_SESSION['next_reminder_time']);
 773          if($insertion_mode != 'edit') {
 774              $this->createAccessKey();
 775          }
 776          $this->db->completeTransaction();
 777          $this->db->println("TRANS saveentity ends");
 778      }
 779  
 780      function createAccessKey() {
 781          global $adb,$log;
 782  
 783          $log->info("Entering Into function createAccessKey()");
 784          $updateQuery = "update vtiger_users set accesskey=? where id=?";
 785          $insertResult = $adb->pquery($updateQuery,array(vtws_generateRandomAccessKey(16),$this->id));
 786          $log->info("Exiting function createAccessKey()");
 787  
 788      }
 789  
 790      /** Function to insert values in the specifed table for the specified module
 791       * @param $table_name -- table name:: Type varchar
 792       * @param $module -- module:: Type varchar
 793       */
 794      function insertIntoEntityTable($table_name, $module) {
 795          global $log;
 796          $log->info("function insertIntoEntityTable ".$module.' vtiger_table name ' .$table_name);
 797          global $adb, $current_user;
 798          $insertion_mode = $this->mode;
 799          //Checkin whether an entry is already is present in the vtiger_table to update
 800          if($insertion_mode == 'edit') {
 801              $check_query = "select * from ".$table_name." where ".$this->tab_name_index[$table_name]."=?";
 802              $check_result=$this->db->pquery($check_query, array($this->id));
 803  
 804              $num_rows = $this->db->num_rows($check_result);
 805  
 806              if($num_rows <= 0) {
 807                  $insertion_mode = '';
 808              }
 809          }
 810  
 811          // We will set the crypt_type based on the insertion_mode
 812          $crypt_type = '';
 813  
 814          if($insertion_mode == 'edit') {
 815              $update = '';
 816              $update_params = array();
 817              $tabid= getTabid($module);
 818              $sql = "select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,5) and vtiger_field.presence in (0,2)";
 819              $params = array($tabid, $table_name);
 820          }
 821          else {
 822              $column = $this->tab_name_index[$table_name];
 823              if($column == 'id' && $table_name == 'vtiger_users') {
 824                  $currentuser_id = $this->db->getUniqueID("vtiger_users");
 825                  $this->id = $currentuser_id;
 826              }
 827              $qparams = array($this->id);
 828              $tabid= getTabid($module);
 829              $sql = "select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4,5) and vtiger_field.presence in (0,2)";
 830              $params = array($tabid, $table_name);
 831  
 832              $crypt_type = $this->DEFAULT_PASSWORD_CRYPT_TYPE;
 833          }
 834  
 835          $result = $this->db->pquery($sql, $params);
 836          $noofrows = $this->db->num_rows($result);
 837          for($i=0; $i<$noofrows; $i++) {
 838              $fieldname=$this->db->query_result($result,$i,"fieldname");
 839              $columname=$this->db->query_result($result,$i,"columnname");
 840              $uitype=$this->db->query_result($result,$i,"uitype");
 841              $typeofdata=$adb->query_result($result,$i,"typeofdata");
 842  
 843              $typeofdata_array = explode("~",$typeofdata);
 844              $datatype = $typeofdata_array[0];
 845  
 846              if(isset($this->column_fields[$fieldname])) {
 847                  if($uitype == 56) {
 848                      if($this->column_fields[$fieldname] === 'on' || $this->column_fields[$fieldname] == 1) {
 849                          $fldvalue = 1;
 850                      }
 851                      else {
 852                          $fldvalue = 0;
 853                      }
 854  
 855                  }elseif($uitype == 15) {
 856                      if($this->column_fields[$fieldname] == $app_strings['LBL_NOT_ACCESSIBLE']) {
 857                          //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
 858                          $sql="select $columname from  $table_name where ".$this->tab_name_index[$table_name]."=?";
 859                          $res = $adb->pquery($sql,array($this->id));
 860                          $pick_val = $adb->query_result($res,0,$columname);
 861                          $fldvalue = $pick_val;
 862                      }
 863                      else {
 864                          $fldvalue = $this->column_fields[$fieldname];
 865                      }
 866                  }
 867                  elseif($uitype == 33) {
 868                      if(is_array($this->column_fields[$fieldname])) {
 869                          $field_list = implode(' |##| ',$this->column_fields[$fieldname]);
 870                      }else {
 871                          $field_list = $this->column_fields[$fieldname];
 872                      }
 873                      $fldvalue = $field_list;
 874                  }
 875                  elseif($uitype == 99) {
 876                      $plain_text = $this->column_fields[$fieldname];
 877                      $fldvalue = $this->encrypt_password($plain_text, $crypt_type);
 878                      // Update the plain-text value with encrypted value and dependent fields
 879                      $this->column_fields[$fieldname] = $fldvalue;
 880                      $this->column_fields['crypt_type'] = $crypt_type;
 881                      $this->column_fields['user_hash'] = $this->get_user_hash($plain_text);
 882                  }
 883                  else {
 884                      $fldvalue = $this->column_fields[$fieldname];
 885                      $fldvalue = stripslashes($fldvalue);
 886                  }
 887                  $fldvalue = from_html($fldvalue,($insertion_mode == 'edit')?true:false);
 888  
 889  
 890  
 891              }
 892              else {
 893                  $fldvalue = '';
 894              }
 895              if($uitype == 31) {
 896                  $themeList = array_keys(Vtiger_Util_Helper::getAllSkins());
 897                  if(!in_array($fldvalue, $themeList) || $fldvalue == '') {
 898                      global $default_theme;
 899                      if(!empty($default_theme) && in_array($default_theme, $themeList)) {
 900                          $fldvalue = $default_theme;
 901                      } else {
 902                          $fldvalue = $themeList[0];
 903                      }
 904                  }
 905                  if($current_user->id == $this->id) {
 906                      $_SESSION['vtiger_authenticated_user_theme'] = $fldvalue;
 907                  }
 908              } elseif($uitype == 32) {
 909                  $languageList = Vtiger_Language::getAll();
 910                  $languageList = array_keys($languageList);
 911                  if(!in_array($fldvalue, $languageList) || $fldvalue == '') {
 912                      global $default_language;
 913                      if(!empty($default_language) && in_array($default_language, $languageList)) {
 914                          $fldvalue = $default_language;
 915                      } else {
 916                          $fldvalue = $languageList[0];
 917                      }
 918                  }
 919                  if($current_user->id == $this->id) {
 920                      $_SESSION['authenticated_user_language'] = $fldvalue;
 921                  }
 922              }
 923              if($fldvalue=='') {
 924                  $fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
 925                  //$fldvalue =null;
 926              }
 927              if($insertion_mode == 'edit') {
 928                  if($i == 0) {
 929                      $update = $columname."=?";
 930                  }
 931                  else {
 932                      $update .= ', '.$columname."=?";
 933                  }
 934                  array_push($update_params, $fldvalue);
 935              }
 936              else {
 937                  $column .= ", ".$columname;
 938                  array_push($qparams, $fldvalue);
 939              }
 940          }
 941  
 942          if($insertion_mode == 'edit') {
 943              //Check done by Don. If update is empty the the query fails
 944              if(trim($update) != '') {
 945                  $sql1 = "update $table_name set $update where ".$this->tab_name_index[$table_name]."=?";
 946                  array_push($update_params, $this->id);
 947                  $this->db->pquery($sql1, $update_params);
 948              }
 949  
 950          }
 951          else {
 952              // Set the crypt_type being used, to override the DB default constraint as it is not in vtiger_field
 953              if($table_name == 'vtiger_users' && strpos('crypt_type', $column) === false) {
 954                  $column .= ', crypt_type';
 955                  $qparams[]= $crypt_type;
 956              }
 957              // END
 958  
 959              if($table_name == 'vtiger_users' && strpos('user_hash', $column) === false) {
 960                  $column .= ', user_hash';
 961                  $qparams[] = $this->column_fields['user_hash'];
 962              }
 963  
 964              $sql1 = "insert into $table_name ($column) values(". generateQuestionMarks($qparams) .")";
 965              $this->db->pquery($sql1, $qparams);
 966          }
 967      }
 968  
 969  
 970  
 971      /** Function to insert values into the attachment table
 972       * @param $id -- entity id:: Type integer
 973       * @param $module -- module:: Type varchar
 974       */
 975      function insertIntoAttachment($id,$module) {
 976          global $log;
 977          $log->debug("Entering into insertIntoAttachment($id,$module) method.");
 978  
 979          foreach($_FILES as $fileindex => $files) {
 980              if($files['name'] != '' && $files['size'] > 0) {
 981                  $files['original_name'] = vtlib_purify($_REQUEST[$fileindex.'_hidden']);
 982                  $this->uploadAndSaveFile($id,$module,$files);
 983              }
 984          }
 985  
 986          $log->debug("Exiting from insertIntoAttachment($id,$module) method.");
 987      }
 988  
 989      /** Function to retreive the user info of the specifed user id The user info will be available in $this->column_fields array
 990       * @param $record -- record id:: Type integer
 991       * @param $module -- module:: Type varchar
 992       */
 993      function retrieve_entity_info($record, $module) {
 994          global $adb,$log;
 995          $log->debug("Entering into retrieve_entity_info($record, $module) method.");
 996  
 997          if($record == '') {
 998              $log->debug("record is empty. returning null");
 999              return null;
1000          }
1001  
1002          $result = Array();
1003          foreach($this->tab_name_index as $table_name=>$index) {
1004              $result[$table_name] = $adb->pquery("select * from ".$table_name." where ".$index."=?", array($record));
1005          }
1006          $tabid = getTabid($module);
1007          $sql1 =  "select * from vtiger_field where tabid=? and vtiger_field.presence in (0,2)";
1008          $result1 = $adb->pquery($sql1, array($tabid));
1009          $noofrows = $adb->num_rows($result1);
1010          for($i=0; $i<$noofrows; $i++) {
1011              $fieldcolname = $adb->query_result($result1,$i,"columnname");
1012              $tablename = $adb->query_result($result1,$i,"tablename");
1013              $fieldname = $adb->query_result($result1,$i,"fieldname");
1014  
1015              $fld_value = $adb->query_result($result[$tablename],0,$fieldcolname);
1016              $this->column_fields[$fieldname] = $fld_value;
1017              $this->$fieldname = $fld_value;
1018  
1019          }
1020          $this->column_fields["record_id"] = $record;
1021          $this->column_fields["record_module"] = $module;
1022  
1023          $currency_query = "select * from vtiger_currency_info where id=? and currency_status='Active' and deleted=0";
1024          $currency_result = $adb->pquery($currency_query, array($this->column_fields["currency_id"]));
1025          if($adb->num_rows($currency_result) == 0) {
1026              $currency_query = "select * from vtiger_currency_info where id =1";
1027              $currency_result = $adb->pquery($currency_query, array());
1028          }
1029          $currency_array = array("$"=>"&#36;","&euro;"=>"&#8364;","&pound;"=>"&#163;","&yen;"=>"&#165;");
1030          $ui_curr = $currency_array[$adb->query_result($currency_result,0,"currency_symbol")];
1031          if($ui_curr == "")
1032              $ui_curr = $adb->query_result($currency_result,0,"currency_symbol");
1033          $this->column_fields["currency_name"]= $this->currency_name = $adb->query_result($currency_result,0,"currency_name");
1034          $this->column_fields["currency_code"]= $this->currency_code = $adb->query_result($currency_result,0,"currency_code");
1035          $this->column_fields["currency_symbol"]= $this->currency_symbol = $ui_curr;
1036          $this->column_fields["conv_rate"]= $this->conv_rate = $adb->query_result($currency_result,0,"conversion_rate");
1037          if($this->column_fields['no_of_currency_decimals'] == '')
1038              $this->column_fields['no_of_currency_decimals'] = $this->no_of_currency_decimals = getCurrencyDecimalPlaces();
1039  
1040          // TODO - This needs to be cleaned up once default values for fields are picked up in a cleaner way.
1041          // This is just a quick fix to ensure things doesn't start breaking when the user currency configuration is missing
1042          if($this->column_fields['currency_grouping_pattern'] == ''
1043                  && $this->column_fields['currency_symbol_placement'] == '') {
1044  
1045              $this->column_fields['currency_grouping_pattern'] = $this->currency_grouping_pattern = '123,456,789';
1046              $this->column_fields['currency_decimal_separator'] = $this->currency_decimal_separator = '.';
1047              $this->column_fields['currency_grouping_separator'] = $this->currency_grouping_separator = ',';
1048              $this->column_fields['currency_symbol_placement'] = $this->currency_symbol_placement = '$1.0';
1049          }
1050  
1051          // TODO - This needs to be cleaned up once default values for fields are picked up in a cleaner way.
1052          // This is just a quick fix to ensure things doesn't start breaking when the user currency configuration is missing
1053          if($this->column_fields['currency_grouping_pattern'] == ''
1054                  && $this->column_fields['currency_symbol_placement'] == '') {
1055  
1056              $this->column_fields['currency_grouping_pattern'] = $this->currency_grouping_pattern = '123,456,789';
1057              $this->column_fields['currency_decimal_separator'] = $this->currency_decimal_separator = '.';
1058              $this->column_fields['currency_grouping_separator'] = $this->currency_grouping_separator = ',';
1059              $this->column_fields['currency_symbol_placement'] = $this->currency_symbol_placement = '$1.0';
1060          }
1061  
1062          $this->id = $record;
1063          $log->debug("Exit from retrieve_entity_info($record, $module) method.");
1064  
1065          return $this;
1066      }
1067  
1068  
1069      /** Function to upload the file to the server and add the file details in the attachments table
1070       * @param $id -- user id:: Type varchar
1071       * @param $module -- module name:: Type varchar
1072       * @param $file_details -- file details array:: Type array
1073       */
1074      function uploadAndSaveFile($id,$module,$file_details) {
1075          global $log;
1076          $log->debug("Entering into uploadAndSaveFile($id,$module,$file_details) method.");
1077  
1078          global $current_user;
1079          global $upload_badext;
1080  
1081          $date_var = date('Y-m-d H:i:s');
1082  
1083          //to get the owner id
1084          $ownerid = $this->column_fields['assigned_user_id'];
1085          if(!isset($ownerid) || $ownerid=='')
1086              $ownerid = $current_user->id;
1087  
1088          $file = $file_details['name'];
1089          $binFile = sanitizeUploadFileName($file, $upload_badext);
1090  
1091          $filename = ltrim(basename(" ".$binFile)); //allowed filename like UTF-8 characters
1092          $filetype= $file_details['type'];
1093          $filesize = $file_details['size'];
1094          $filetmp_name = $file_details['tmp_name'];
1095  
1096          $current_id = $this->db->getUniqueID("vtiger_crmentity");
1097  
1098          //get the file path inwhich folder we want to upload the file
1099          $upload_file_path = decideFilePath();
1100          //upload the file in server
1101          $upload_status = move_uploaded_file($filetmp_name,$upload_file_path.$current_id."_".$binFile);
1102  
1103          $save_file = 'true';
1104          //only images are allowed for these modules
1105          if($module == 'Users') {
1106              $save_file = validateImageFile($file_details);
1107          }
1108          if($save_file == 'true') {
1109  
1110              $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?)";
1111              $params1 = array($current_id, $current_user->id, $ownerid, $module." Attachment", $this->column_fields['description'], $this->db->formatString("vtiger_crmentity","createdtime",$date_var), $this->db->formatDate($date_var, true));
1112              $this->db->pquery($sql1, $params1);
1113  
1114              $sql2="insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?,?,?,?,?)";
1115              $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path);
1116              $result=$this->db->pquery($sql2, $params2);
1117  
1118              if($id != '') {
1119                  $delquery = 'delete from vtiger_salesmanattachmentsrel where smid = ?';
1120                  $this->db->pquery($delquery, array($id));
1121              }
1122  
1123              $sql3='insert into vtiger_salesmanattachmentsrel values(?,?)';
1124              $this->db->pquery($sql3, array($id, $current_id));
1125  
1126              //we should update the imagename in the users table
1127              $this->db->pquery("update vtiger_users set imagename=? where id=?", array($filename, $id));
1128          }
1129          else {
1130              $log->debug("Skip the save attachment process.");
1131          }
1132          $log->debug("Exiting from uploadAndSaveFile($id,$module,$file_details) method.");
1133  
1134          return;
1135      }
1136  
1137  
1138      /** Function to save the user information into the database
1139       * @param $module -- module name:: Type varchar
1140       *
1141       */
1142      function save($module_name) {
1143          global $log, $adb;
1144          //Save entity being called with the modulename as parameter
1145          $this->saveentity($module_name);
1146  
1147          // Added for Reminder Popup support
1148          $query_prev_interval = $adb->pquery("SELECT reminder_interval from vtiger_users where id=?",
1149                  array($this->id));
1150          $prev_reminder_interval = $adb->query_result($query_prev_interval,0,'reminder_interval');
1151  
1152          //$focus->imagename = $image_upload_array['imagename'];
1153          $this->saveHomeStuffOrder($this->id);
1154          SaveTagCloudView($this->id);
1155  
1156          // Added for Reminder Popup support
1157          $this->resetReminderInterval($prev_reminder_interval);
1158          //Creating the Privileges Flat File
1159          if(isset($this->column_fields['roleid'])) {
1160              updateUser2RoleMapping($this->column_fields['roleid'],$this->id);
1161          }
1162  
1163          //After adding new user, set the default activity types for new user
1164          Vtiger_Util_Helper::setCalendarDefaultActivityTypesForUser($this->id);
1165  
1166          require_once ('modules/Users/CreateUserPrivilegeFile.php');
1167          createUserPrivilegesfile($this->id);
1168          createUserSharingPrivilegesfile($this->id);
1169  
1170      }
1171  
1172  
1173      /**
1174       * gives the order in which the modules have to be displayed in the home page for the specified user id
1175       * @param $id -- user id:: Type integer
1176       * @returns the customized home page order in $return_array
1177       */
1178      function getHomeStuffOrder($id) {
1179          global $adb;
1180          if(!is_array($this->homeorder_array)) {
1181              $this->homeorder_array = array('UA', 'PA', 'ALVT','HDB','PLVT','QLTQ','CVLVT','HLT',
1182                      'GRT','OLTSO','ILTI','MNL','OLTPO','LTFAQ');
1183          }
1184          $return_array = Array();
1185          $homeorder=Array();
1186          if($id != '') {
1187              $qry=" select distinct(vtiger_homedefault.hometype) from vtiger_homedefault inner join vtiger_homestuff  on vtiger_homestuff.stuffid=vtiger_homedefault.stuffid where vtiger_homestuff.visible=0 and vtiger_homestuff.userid=?";
1188              $res=$adb->pquery($qry, array($id));
1189              for($q=0;$q<$adb->num_rows($res);$q++) {
1190                  $homeorder[]=$adb->query_result($res,$q,"hometype");
1191              }
1192              for($i = 0;$i < count($this->homeorder_array);$i++) {
1193                  if(in_array($this->homeorder_array[$i],$homeorder)) {
1194                      $return_array[$this->homeorder_array[$i]] = $this->homeorder_array[$i];
1195                  }else {
1196                      $return_array[$this->homeorder_array[$i]] = '';
1197                  }
1198              }
1199          }else {
1200              for($i = 0;$i < count($this->homeorder_array);$i++) {
1201                if(in_array($this->homeorder_array[$i], $this->default_widgets)){
1202                  $return_array[$this->homeorder_array[$i]] = $this->homeorder_array[$i];
1203                }else{
1204                    $return_array[$this->homeorder_array[$i]] = '';
1205                }
1206              }
1207          }
1208          return $return_array;
1209      }
1210  
1211      function getDefaultHomeModuleVisibility($home_string,$inVal) {
1212          $homeModComptVisibility= 1;
1213          if($inVal == 'postinstall') {
1214              if($_REQUEST[$home_string] != '') {
1215                  $homeModComptVisibility = 0;
1216              } else if(in_array($home_string, $this->default_widgets)){
1217                  $homeModComptVisibility = 0;
1218              }
1219          }
1220          return $homeModComptVisibility;
1221  
1222      }
1223  
1224      function insertUserdetails($inVal) {
1225          global $adb;
1226          $uid=$this->id;
1227          $s1=$adb->getUniqueID("vtiger_homestuff");
1228          $visibility=$this->getDefaultHomeModuleVisibility('ALVT',$inVal);
1229          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1230          $res=$adb->pquery($sql, array($s1,1,'Default',$uid,$visibility,'Top Accounts'));
1231  
1232          $s2=$adb->getUniqueID("vtiger_homestuff");
1233          $visibility=$this->getDefaultHomeModuleVisibility('HDB',$inVal);
1234          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1235          $res=$adb->pquery($sql, array($s2,2,'Default',$uid,$visibility,'Home Page Dashboard'));
1236  
1237          $s3=$adb->getUniqueID("vtiger_homestuff");
1238          $visibility=$this->getDefaultHomeModuleVisibility('PLVT',$inVal);
1239          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1240          $res=$adb->pquery($sql, array($s3,3,'Default',$uid,$visibility,'Top Potentials'));
1241  
1242          $s4=$adb->getUniqueID("vtiger_homestuff");
1243          $visibility=$this->getDefaultHomeModuleVisibility('QLTQ',$inVal);
1244          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1245          $res=$adb->pquery($sql, array($s4,4,'Default',$uid,$visibility,'Top Quotes'));
1246  
1247          $s5=$adb->getUniqueID("vtiger_homestuff");
1248          $visibility=$this->getDefaultHomeModuleVisibility('CVLVT',$inVal);
1249          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1250          $res=$adb->pquery($sql, array($s5,5,'Default',$uid,$visibility,'Key Metrics'));
1251  
1252          $s6=$adb->getUniqueID("vtiger_homestuff");
1253          $visibility=$this->getDefaultHomeModuleVisibility('HLT',$inVal);
1254          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1255          $res=$adb->pquery($sql, array($s6,6,'Default',$uid,$visibility,'Top Trouble Tickets'));
1256  
1257          $s7=$adb->getUniqueID("vtiger_homestuff");
1258          $visibility=$this->getDefaultHomeModuleVisibility('UA',$inVal);
1259          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1260          $res=$adb->pquery($sql, array($s7,7,'Default',$uid,$visibility,'Upcoming Activities'));
1261  
1262          $s8=$adb->getUniqueID("vtiger_homestuff");
1263          $visibility=$this->getDefaultHomeModuleVisibility('GRT',$inVal);
1264          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1265          $res=$adb->pquery($sql, array($s8,8,'Default',$uid,$visibility,'My Group Allocation'));
1266  
1267          $s9=$adb->getUniqueID("vtiger_homestuff");
1268          $visibility=$this->getDefaultHomeModuleVisibility('OLTSO',$inVal);
1269          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1270          $res=$adb->pquery($sql, array($s9,9,'Default',$uid,$visibility,'Top Sales Orders'));
1271  
1272          $s10=$adb->getUniqueID("vtiger_homestuff");
1273          $visibility=$this->getDefaultHomeModuleVisibility('ILTI',$inVal);
1274          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1275          $res=$adb->pquery($sql, array($s10,10,'Default',$uid,$visibility,'Top Invoices'));
1276  
1277          $s11=$adb->getUniqueID("vtiger_homestuff");
1278          $visibility=$this->getDefaultHomeModuleVisibility('MNL',$inVal);
1279          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1280          $res=$adb->pquery($sql, array($s11,11,'Default',$uid,$visibility,'My New Leads'));
1281  
1282          $s12=$adb->getUniqueID("vtiger_homestuff");
1283          $visibility=$this->getDefaultHomeModuleVisibility('OLTPO',$inVal);
1284          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1285          $res=$adb->pquery($sql, array($s12,12,'Default',$uid,$visibility,'Top Purchase Orders'));
1286  
1287          $s13=$adb->getUniqueID("vtiger_homestuff");
1288          $visibility=$this->getDefaultHomeModuleVisibility('PA',$inVal);
1289          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1290          $res=$adb->pquery($sql, array($s13,13,'Default',$uid,$visibility,'Pending Activities'));
1291          ;
1292  
1293          $s14=$adb->getUniqueID("vtiger_homestuff");
1294          $visibility=$this->getDefaultHomeModuleVisibility('LTFAQ',$inVal);
1295          $sql="insert into vtiger_homestuff values(?,?,?,?,?,?)";
1296          $res=$adb->pquery($sql, array($s14,14,'Default',$uid,$visibility,'My Recent FAQs'));
1297  
1298          // Non-Default Home Page widget (no entry is requried in vtiger_homedefault below)
1299          $tc = $adb->getUniqueID("vtiger_homestuff");
1300          $visibility=0;
1301          $sql="insert into vtiger_homestuff values($tc, 15, 'Tag Cloud', $uid, $visibility, 'Tag Cloud')";
1302          $adb->pquery($sql, array());
1303  
1304          $sql="insert into vtiger_homedefault values(".$s1.",'ALVT',5,'Accounts')";
1305          $adb->pquery($sql, array());
1306  
1307          $sql="insert into vtiger_homedefault values(".$s2.",'HDB',5,'Dashboard')";
1308          $adb->pquery($sql, array());
1309  
1310          $sql="insert into vtiger_homedefault values(".$s3.",'PLVT',5,'Potentials')";
1311          $adb->pquery($sql, array());
1312  
1313          $sql="insert into vtiger_homedefault values(".$s4.",'QLTQ',5,'Quotes')";
1314          $adb->pquery($sql, array());
1315  
1316          $sql="insert into vtiger_homedefault values(".$s5.",'CVLVT',5,'NULL')";
1317          $adb->pquery($sql, array());
1318  
1319          $sql="insert into vtiger_homedefault values(".$s6.",'HLT',5,'HelpDesk')";
1320          $adb->pquery($sql, array());
1321  
1322          $sql="insert into vtiger_homedefault values(".$s7.",'UA',5,'Calendar')";
1323          $adb->pquery($sql,array());
1324  
1325          $sql="insert into vtiger_homedefault values(".$s8.",'GRT',5,'NULL')";
1326          $adb->pquery($sql, array());
1327  
1328          $sql="insert into vtiger_homedefault values(".$s9.",'OLTSO',5,'SalesOrder')";
1329          $adb->pquery($sql, array());
1330  
1331          $sql="insert into vtiger_homedefault values(".$s10.",'ILTI',5,'Invoice')";
1332          $adb->pquery($sql, array());
1333  
1334          $sql="insert into vtiger_homedefault values(".$s11.",'MNL',5,'Leads')";
1335          $adb->pquery($sql, array());
1336  
1337          $sql="insert into vtiger_homedefault values(".$s12.",'OLTPO',5,'PurchaseOrder')";
1338          $adb->pquery($sql, array());
1339  
1340          $sql="insert into vtiger_homedefault values(".$s13.",'PA',5,'Calendar')";
1341          $adb->pquery($sql,array());
1342  
1343          $sql="insert into vtiger_homedefault values(".$s14.",'LTFAQ',5,'Faq')";
1344          $adb->pquery($sql, array());
1345  
1346      }
1347  
1348      /** function to save the order in which the modules have to be displayed in the home page for the specified user id
1349       * @param $id -- user id:: Type integer
1350       */
1351  	 function saveHomeStuffOrder($id)
1352       {
1353          global $log,$adb;
1354          $log->debug("Entering in function saveHomeOrder($id)");
1355  
1356           if($this->mode == 'edit')
1357           {
1358               for($i = 0;$i < count($this->homeorder_array);$i++)
1359               {
1360                   if($_REQUEST[$this->homeorder_array[$i]] != '')
1361                   {
1362                      $save_array[] = $this->homeorder_array[$i];
1363                      $qry=" update vtiger_homestuff,vtiger_homedefault set vtiger_homestuff.visible=0 where vtiger_homestuff.stuffid=vtiger_homedefault.stuffid and vtiger_homestuff.userid=".$id." and vtiger_homedefault.hometype='".$this->homeorder_array[$i]."'";//To show the default Homestuff on the the Home Page
1364                      $result=$adb->pquery($qry, array());
1365                  }
1366                   else
1367                   {
1368                      $qry="update vtiger_homestuff,vtiger_homedefault set vtiger_homestuff.visible=1 where vtiger_homestuff.stuffid=vtiger_homedefault.stuffid and vtiger_homestuff.userid=".$id." and vtiger_homedefault.hometype='".$this->homeorder_array[$i]."'";//To hide the default Homestuff on the the Home Page
1369                      $result=$adb->pquery($qry, array());
1370                  }
1371              }
1372              if($save_array !="")
1373                  $homeorder = implode(',',$save_array);
1374          }
1375           else
1376           {
1377              $this->insertUserdetails('postinstall');
1378  
1379          }
1380          $log->debug("Exiting from function saveHomeOrder($id)");
1381      }
1382  
1383      /**
1384       * Track the viewing of a detail record.  This leverages get_summary_text() which is object specific
1385       * params $user_id - The user that is viewing the record.
1386       * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
1387       * All Rights Reserved..
1388       * Contributor(s): ______________________________________..
1389       */
1390      function track_view($user_id, $current_module,$id='') {
1391          $this->log->debug("About to call vtiger_tracker (user_id, module_name, item_id)($user_id, $current_module, $this->id)");
1392  
1393          $tracker = new Tracker();
1394          $tracker->track_view($user_id, $current_module, $id, '');
1395      }
1396  
1397      /**
1398       * Function to get the column value of a field
1399       * @param $column_name -- Column name
1400       * @param $input_value -- Input value for the column taken from the User
1401       * @return Column value of the field.
1402       */
1403      function get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype) {
1404          if (is_uitype($uitype, "_date_") && $fldvalue == '') {
1405              return null;
1406          }
1407          if ($datatype == 'I' || $datatype == 'N' || $datatype == 'NN') {
1408              return 0;
1409          }
1410          return $fldvalue;
1411      }
1412  
1413      /**
1414       * Function to reset the Reminder Interval setup and update the time for next reminder interval
1415       * @param $prev_reminder_interval -- Last Reminder Interval on which the reminder popup's were triggered.
1416       */
1417      function resetReminderInterval($prev_reminder_interval) {
1418          global $adb;
1419          if($prev_reminder_interval != $this->column_fields['reminder_interval'] ) {
1420              unset($_SESSION['next_reminder_interval']);
1421              unset($_SESSION['next_reminder_time']);
1422              $set_reminder_next = date('Y-m-d H:i');
1423              // NOTE date_entered has CURRENT_TIMESTAMP constraint, so we need to reset when updating the table
1424              $adb->pquery("UPDATE vtiger_users SET reminder_next_time=?, date_entered=? WHERE id=?",array($set_reminder_next, $this->column_fields['date_entered'], $this->id));
1425          }
1426      }
1427  
1428      function initSortByField($module) {
1429          // Right now, we do not have any fields to be handled for Sorting in Users module. This is just a place holder as it is called from Popup.php
1430      }
1431  
1432      function filterInactiveFields($module) {
1433          // TODO Nothing do right now
1434      }
1435  
1436      function deleteImage() {
1437          $sql1 = 'SELECT attachmentsid FROM vtiger_salesmanattachmentsrel WHERE smid = ?';
1438          $res1 = $this->db->pquery($sql1, array($this->id));
1439          if ($this->db->num_rows($res1) > 0) {
1440              $attachmentId = $this->db->query_result($res1, 0, 'attachmentsid');
1441  
1442              $sql2 = "DELETE FROM vtiger_crmentity WHERE crmid=? AND setype='Users Attachments'";
1443              $this->db->pquery($sql2, array($attachmentId));
1444  
1445              $sql3 = 'DELETE FROM vtiger_salesmanattachmentsrel WHERE smid=? AND attachmentsid=?';
1446              $this->db->pquery($sql3, array($this->id, $attachmentId));
1447  
1448              $sql2 = "UPDATE vtiger_users SET imagename='' WHERE id=?";
1449              $this->db->pquery($sql2, array($this->id));
1450  
1451              $sql4 = 'DELETE FROM vtiger_attachments WHERE attachmentsid=?';
1452              $this->db->pquery($sql4, array($attachmentId));
1453          }
1454      }
1455  
1456      /** Function to delete an entity with given Id */
1457      function trash($module, $id) {
1458          global $log, $current_user;
1459  
1460          $this->mark_deleted($id);
1461      }
1462  
1463  	function transformOwnerShipAndDelete($userId,$transformToUserId){
1464          $adb = PearDatabase::getInstance();
1465  
1466          $em = new VTEventsManager($adb);
1467  
1468          // Initialize Event trigger cache
1469          $em->initTriggerCache();
1470  
1471          $entityData  = VTEntityData::fromUserId($adb, $userId);
1472  
1473          //set transform user id
1474          $entityData->set('transformtouserid',$transformToUserId);
1475  
1476          $em->triggerEvent("vtiger.entity.beforedelete", $entityData);
1477  
1478          vtws_transferOwnership($userId, $transformToUserId);
1479  
1480          //delete from user vtiger_table;
1481          $sql = "delete from vtiger_users where id=?";
1482          $adb->pquery($sql, array($userId));
1483      }
1484  
1485      /**
1486       * This function should be overridden in each module.  It marks an item as deleted.
1487       * @param <type> $id
1488       */
1489      function mark_deleted($id) {
1490          global $log, $current_user, $adb;
1491          $date_var = date('Y-m-d H:i:s');
1492          $query = "UPDATE vtiger_users set status=?,date_modified=?,modified_user_id=? where id=?";
1493          $adb->pquery($query, array('Inactive', $adb->formatDate($date_var, true),
1494                  $current_user->id, $id), true,"Error marking record deleted: ");
1495      }
1496  
1497      /**
1498       * Function to get the user if of the active admin user.
1499       * @return Integer - Active Admin User ID
1500       */
1501      public static function getActiveAdminId() {
1502          global $adb;
1503          $cache = Vtiger_Cache::getInstance();
1504          if($cache->getAdminUserId()){
1505              return $cache->getAdminUserId();
1506          } else {
1507          $sql = "SELECT id FROM vtiger_users WHERE is_admin = 'on' AND status = 'Active' limit 1";
1508          $result = $adb->pquery($sql, array());
1509          $adminId = 1;
1510          $it = new SqlResultIterator($adb, $result);
1511          foreach ($it as $row) {
1512              $adminId = $row->id;
1513          }
1514              $cache->setAdminUserId($adminId);
1515          return $adminId;
1516          }
1517      }
1518  
1519      /**
1520       * Function to get the active admin user object
1521       * @return Users - Active Admin User Instance
1522       */
1523      public static function getActiveAdminUser() {
1524          $adminId = self::getActiveAdminId();
1525          $user = new Users();
1526          $user->retrieveCurrentUserInfoFromFile($adminId);
1527          return $user;
1528      }
1529  
1530      /**
1531      * Function to set the user time zone and language
1532      * @param- $_REQUEST array
1533      */
1534      public function setUserPreferences($requestArray) {
1535          global $adb;
1536          $updateData = array();
1537  
1538          if (isset($requestArray['about']['phone'])) $updateData['phone_mobile'] = vtlib_purify ($requestArray['about']['phone']);
1539          if (isset($requestArray['about']['country'])) $updateData['address_country'] = vtlib_purify ($requestArray['about']['country']);
1540          if (isset($requestArray['about']['company_job'])) $updateData['title'] = vtlib_purify ($requestArray['about']['company_job']);
1541          if (isset($requestArray['about']['department'])) $updateData['department'] = vtlib_purify ($requestArray['about']['department']);
1542  
1543          if (isset($requestArray['lang_name'])) $updateData['language'] = vtlib_purify ($requestArray['lang_name']);
1544          if (isset($requestArray['time_zone'])) $updateData['time_zone']= vtlib_purify ($requestArray['time_zone']);
1545          if (isset($requestArray['date_format'])) $updateData['date_format']= vtlib_purify ($requestArray['date_format']);
1546  
1547          if (!empty($updateData)) {
1548              $updateQuery = 'UPDATE vtiger_users SET '. ( implode('=?,', array_keys($updateData)). '=?') . ' WHERE id = ?';
1549              $updateQueryParams = array_values($updateData);
1550              $updateQueryParams[] = $this->id;
1551              $adb->pquery($updateQuery, $updateQueryParams);
1552          }
1553      }
1554  
1555      /**
1556       * Function to set the Company Logo
1557       * @param- $_REQUEST array
1558       * @param- $_FILE array
1559       */
1560  	public function uploadOrgLogo($requestArray, $fileArray) {
1561          global $adb;
1562          $file = $fileArray['file'];
1563          $logo_name = $file['name'];
1564          $file_size = $file['size'];
1565          $file_type = $file['type'];
1566  
1567          $filetype_array = explode("/",$file_type);
1568          $file_type_val = strtolower($filetype_array[1]);
1569  
1570          $validFileFormats =  array('jpeg', 'png', 'jpg', 'pjpeg', 'x-png', 'gif');
1571  
1572          if ($file_size != 0 && in_array($file_type_val, $validFileFormats)) {
1573              //Uploading the selected Image
1574              move_uploaded_file($file['tmp_name'], 'test/logo/'.$logo_name);
1575  
1576              //Updating Database
1577              $sql = 'UPDATE vtiger_organizationdetails SET logoname = ? WHERE organization_id = ?';
1578              $params = array(decode_html($logo_name), '1');
1579              $adb->pquery($sql, $params);
1580              copy('test/logo/'.$logo_name, 'test/logo/application.ico');
1581          }
1582      }
1583  
1584      /**
1585      * Function to update Base Currency of Product
1586      * @param- $_REQUEST array
1587      */
1588  	public function updateBaseCurrency($requestArray) {
1589          global $adb;
1590          if (isset ($requestArray['currency_name'])) {
1591              $currency_name = vtlib_purify($requestArray['currency_name']);
1592  
1593              $result = $adb->pquery('SELECT currency_code, currency_symbol FROM vtiger_currencies WHERE currency_name = ?', array($currency_name));
1594              $num_rows = $adb->num_rows($result);
1595              if ($num_rows > 0) {
1596                  $currency_code = decode_html($adb->query_result($result, 0, 'currency_code'));
1597                  $currency_symbol = decode_html($adb->query_result($result, 0,'currency_symbol'));
1598              }
1599  
1600              //Updating Database
1601              $query = 'UPDATE vtiger_currency_info SET currency_name = ?, currency_code = ?, currency_symbol = ? WHERE id = ?';
1602              $params = array($currency_name, $currency_code, $currency_symbol, '1');
1603              $adb->pquery($query, $params);
1604  
1605          }
1606      }
1607  
1608      /**
1609      * Function to update Config file
1610      * @param- $_REQUEST array
1611      */
1612  	public function updateConfigFile($requestArray) {
1613         if (isset ($requestArray['currency_name'])) {
1614             $currency_name = vtlib_purify($requestArray['currency_name']);
1615             $currency_name = '$currency_name = \''.$currency_name.'\'';
1616  
1617             //Updating in config inc file
1618             $filename = 'config.inc.php';
1619             if (file_exists($filename)) {
1620                 $contents = file_get_contents($filename);
1621                 $contents = str_replace('$currency_name = \'USA, Dollars\'', $currency_name, $contents);
1622                 file_put_contents($filename, $contents);
1623             }
1624         }
1625     }
1626  
1627     public function triggerAfterSaveEventHandlers() {
1628         global $adb;
1629          require_once ("include/events/include.inc");
1630  
1631          //In Bulk mode stop triggering events
1632          if(!self::isBulkSaveMode()) {
1633              $em = new VTEventsManager($adb);
1634              // Initialize Event trigger cache
1635              $em->initTriggerCache();
1636              $entityData = VTEntityData::fromCRMEntity($this);
1637          }
1638          //Event triggering code ends
1639          if($em) {
1640              //Event triggering code
1641              $em->triggerEvent("vtiger.entity.aftersave", $entityData);
1642              $em->triggerEvent("vtiger.entity.aftersave.final", $entityData);
1643          }
1644     }
1645  }
1646  
1647  class Users_CRMSetup {
1648  
1649      /**
1650       * Function to get user setup status
1651       * @param- User id
1652       * @return-is First User or not
1653       */
1654  	public static function isFirstUser($user) {
1655          global $adb;
1656  
1657          $isFirstUser = false;
1658          if (is_admin($user)) {
1659              $query = 'SELECT COUNT(*) AS count FROM vtiger_crmsetup';
1660              $result = $adb->pquery($query, array());
1661              $count = $adb->query_result($result, 0, 'count');
1662              if (!$count) {
1663                  $isFirstUser = true;
1664              }
1665          }
1666          return $isFirstUser;
1667      }
1668  
1669      /**
1670       * Function to get user setup status
1671       * @return-is First User or not
1672       */
1673  	public static function insertEntryIntoCRMSetup($id) {
1674          global $adb;
1675  
1676          //updating user setup status into database
1677          $insertQuery = 'INSERT INTO vtiger_crmsetup (userid, setup_status) VALUES (?, ?)';
1678          $adb->pquery($insertQuery, array($id, '1'));
1679  
1680      }
1681      /**
1682       * Function to get user setup status
1683       * @param- User id
1684       * @return-Setup Status of user
1685       */
1686  	public static function getUserSetupStatus($id) {
1687          global $adb;
1688  
1689          $userSetupStatus = false;
1690          $query = 'SELECT 1 FROM vtiger_crmsetup WHERE userid = ? AND setup_status = ?';
1691          $result = $adb->pquery($query, array($id, '1'));
1692          $num_rows = $adb->num_rows($result);
1693          if ($num_rows === 0) {
1694              $userSetupStatus = true;
1695          }
1696          return $userSetupStatus;
1697      }
1698  
1699      /**
1700       * Function to get packages list from CRM
1701       * @return <Array> List of packages
1702       */
1703  	public static function getPackagesList() {
1704          $restrictedModulesList = array('Emails', 'ModComments', 'Rss', 'Portal', 'Integration',
1705              'PBXManager', 'Dashboard', 'Home', 'vtmessages', 'vttwitter');
1706  
1707          $packagesList = array(
1708              'Tools' => array(
1709                  'label' => 'Contact Management',
1710                  'imageName' => 'BasicPackage.png',
1711                  'description' => 'Unify and store your contacts alongside detailed notes, documents, emails, calendar events, and more. Additionally, configure what information each CRM user can see and update, and automate business activities such as email responses and contact information updates.',
1712                  'modules' => array(
1713                      'Contacts' => 'Contacts',
1714                      'Accounts' => 'Organizations',
1715                      'MailManager' => 'Mail Manager',
1716                      'Reports' => 'Reports',
1717                      'Access Control' => 'Access Control',
1718                      'Workflows' => 'Workflows',
1719                      'Mail Converter' => 'Mail Converter',
1720                      'Web-to-lead forms' => 'Web-to-lead forms'
1721                  )),
1722              'Sales' => array(
1723                  'label' => 'Sales Automation',
1724                  'imageName' => 'SalesAutomation.png',
1725                  'description' => 'Capture Leads from your website, or import lists of them, then develop a process for qualifying and turning them into potential sales opportunities, and another for winning those potential opportunities. Additionally, track and segment your sales funnel, individual, and team, performance areas.',
1726                  'modules' => array(
1727                      'Potentials' => 'Opportunities'
1728                  )),
1729              'Marketing' => array(
1730                  'label' => 'Marketing',
1731                  'imageName' => 'Marketing.png',
1732                  'description' => 'Send individual, targeted, or bulk emails to your contacts, leads, and customers, and see how they engage with each communication, with tools to analyze and improve campaign performance.',
1733                  'modules' => array()),
1734              
1735              'Support' => array(
1736                  'label' => 'Support',
1737                  'imageName' => 'Support.png',
1738                  'description' => 'Create and track customer requests/tasks via tickets, and even allow your customers to create and monitor their own tickets and details through a professional customer portal.',
1739                  'modules' => array(
1740                      'HelpDesk' => 'Tickets',
1741                      'ServiceContracts' => 'Service Contracts',
1742                      'CustomerPortal' => 'Customer Portal'
1743                  )),
1744              'Inventory' => array(
1745                  'label' => 'Invoicing & Inventory Management',
1746                  'imageName' => 'Inventory.png',
1747                  'description' => 'Build a database of your products and services, maintain inventories, standard prices and prices books, and use these to create quotes, invoices, and sales orders.',
1748                  'modules' => array(
1749                      'Quotes' => 'Quotes',
1750                      'Invoice' => 'Invoice',
1751                      'SalesOrder' => 'Sales Order',
1752                      'PurchaseOrder' => 'Purchase Orders',
1753                      'PriceBooks' => 'Price Books',
1754                  )),
1755              'Project' => array(
1756                  'label' => 'Project Management',
1757                  'imageName' => 'ProjectManagement.png',
1758                  'description' => 'Build and manage customer-associated projects, with detailed tasks that can be assigned to CRM users and placed on their calendars.',
1759                  'modules' => array(
1760                      'Project' => 'Projects',
1761                      'ProjectTask' => 'Tasks',
1762                      'ProjectMilestone' => 'Milestones'
1763                  ))
1764          );
1765  
1766          global $adb;
1767          $result = $adb->pquery('SELECT parent, name, tablabel FROM vtiger_tab', array());
1768          $numOfRows = $adb->num_rows($result);
1769  
1770          for ($i = 0; $i < $numOfRows; $i++) {
1771              $moduleName = $adb->query_result($result, $i, 'name');
1772              $moduleExists = false;
1773  
1774              foreach ($packagesList as $packageName => $packageInfo) {
1775                  if (in_array($moduleName, $restrictedModulesList) || array_key_exists($moduleName, $packageInfo['modules'])) {
1776                      $moduleExists = true;
1777                  }
1778              }
1779  
1780              if (!$moduleExists) {
1781                  $parentName = $adb->query_result($result, $i, 'parent');
1782  
1783                  if ($parentName && ($parentName != 'Settings')) {
1784                      if (array_key_exists($parentName, $packagesList)) {
1785                          $packagesList[$parentName]['modules'][$moduleName] = $adb->query_result($result, $i, 'tablabel');
1786                      } else {
1787                          $packagesList[$parentName] = array('label' => $parentName,
1788                              'modules' => array($moduleName => $adb->query_result($result, $i, 'tablabel')));
1789                      }
1790                  }
1791              }
1792          }
1793          return $packagesList;
1794      }
1795  }
1796  ?>


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1