[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/include/utils/ -> utils.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   * $Header$
  17   * Description:  Includes generic helper functions used throughout the application.
  18   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  19   * All Rights Reserved.
  20   * Contributor(s): ______________________________________..
  21   ********************************************************************************/
  22  require_once ('include/database/PearDatabase.php');
  23  require_once ('include/ComboUtil.php'); //new
  24  require_once ('include/utils/ListViewUtils.php');
  25  require_once ('include/utils/EditViewUtils.php');
  26  require_once ('include/utils/CommonUtils.php');
  27  require_once ('include/utils/InventoryUtils.php');
  28  require_once ('include/utils/SearchUtils.php');
  29  require_once ('include/FormValidationUtil.php');
  30  require_once ('include/events/SqlResultIterator.inc');
  31  require_once ('include/fields/DateTimeField.php');
  32  require_once ('include/fields/CurrencyField.php');
  33  require_once ('data/CRMEntity.php');
  34  require_once  'vtlib/Vtiger/Language.php';
  35  require_once ("include/ListView/ListViewSession.php");
  36  
  37  require_once  'vtlib/Vtiger/Functions.php';
  38  require_once  'vtlib/Vtiger/Deprecated.php';
  39  
  40  require_once  'includes/runtime/Cache.php';
  41  require_once  'modules/Vtiger/helpers/Util.php';
  42  
  43  // Constants to be defined here
  44  
  45  // For Migration status.
  46  define("MIG_CHARSET_PHP_UTF8_DB_UTF8", 1);
  47  define("MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8", 2);
  48  define("MIG_CHARSET_PHP_NONUTF8_DB_UTF8", 3);
  49  define("MIG_CHARSET_PHP_UTF8_DB_NONUTF8", 4);
  50  
  51  // For Customview status.
  52  define("CV_STATUS_DEFAULT", 0);
  53  define("CV_STATUS_PRIVATE", 1);
  54  define("CV_STATUS_PENDING", 2);
  55  define("CV_STATUS_PUBLIC", 3);
  56  
  57  // For Restoration.
  58  define("RB_RECORD_DELETED", 'delete');
  59  define("RB_RECORD_INSERTED", 'insert');
  60  define("RB_RECORD_UPDATED", 'update');
  61  
  62  /** Function to return a full name
  63    * @param $row -- row:: Type integer
  64    * @param $first_column -- first column:: Type string
  65    * @param $last_column -- last column:: Type string
  66    * @returns $fullname -- fullname:: Type string
  67    *
  68  */
  69  function return_name(&$row, $first_column, $last_column)
  70  {
  71      global $log;
  72      $log->debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ...");
  73      $first_name = "";
  74      $last_name = "";
  75      $full_name = "";
  76  
  77      if(isset($row[$first_column]))
  78      {
  79          $first_name = stripslashes($row[$first_column]);
  80      }
  81  
  82      if(isset($row[$last_column]))
  83      {
  84          $last_name = stripslashes($row[$last_column]);
  85      }
  86  
  87      $full_name = $first_name;
  88  
  89      // If we have a first name and we have a last name
  90      if($full_name != "" && $last_name != "")
  91      {
  92          // append a space, then the last name
  93          $full_name .= " ".$last_name;
  94      }
  95      // If we have no first name, but we have a last name
  96      else if($last_name != "")
  97      {
  98          // append the last name without the space.
  99          $full_name .= $last_name;
 100      }
 101  
 102      $log->debug("Exiting return_name method ...");
 103      return $full_name;
 104  }
 105  
 106  /** Function returns the user key in user array
 107    * @param $add_blank -- boolean:: Type boolean
 108    * @param $status -- user status:: Type string
 109    * @param $assigned_user -- user id:: Type string
 110    * @param $private -- sharing type:: Type string
 111    * @returns $user_array -- user array:: Type array
 112    *
 113  */
 114  
 115  //used in module file
 116  function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="",$module=false)
 117  {
 118      global $log;
 119      $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ...");
 120      global $current_user;
 121      if(isset($current_user) && $current_user->id != '')
 122      {
 123          require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
 124          require('user_privileges/user_privileges_'.$current_user->id.'.php');
 125      }
 126      static $user_array = null;
 127      if(!$module){
 128          $module=$_REQUEST['module'];
 129      }
 130  
 131  
 132      if($user_array == null)
 133      {
 134          require_once ('include/database/PearDatabase.php');
 135          $db = PearDatabase::getInstance();
 136          $temp_result = Array();
 137          // Including deleted vtiger_users for now.
 138          if (empty($status)) {
 139                  $query = "SELECT id, user_name from vtiger_users";
 140                  $params = array();
 141          }
 142          else {
 143                  if($private == 'private')
 144                  {
 145                      $log->debug("Sharing is Private. Only the current user should be listed");
 146                      $query = "select id as id,user_name as user_name,first_name,last_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name ,
 147                                vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name
 148                                from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union
 149                                select shareduserid as id,vtiger_users.user_name as user_name ,
 150                                vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name  from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?";
 151                      $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module));
 152                  }
 153                  else
 154                  {
 155                      $log->debug("Sharing is Public. All vtiger_users should be listed");
 156                      $query = "SELECT id, user_name,first_name,last_name from vtiger_users WHERE status=?";
 157                      $params = array($status);
 158                  }
 159          }
 160          if (!empty($assigned_user)) {
 161               $query .= " OR id=?";
 162               array_push($params, $assigned_user);
 163          }
 164  
 165          $query .= " order by user_name ASC";
 166  
 167          $result = $db->pquery($query, $params, true, "Error filling in user array: ");
 168  
 169          if ($add_blank==true){
 170              // Add in a blank row
 171              $temp_result[''] = '';
 172          }
 173  
 174          // Get the id and the name.
 175          while($row = $db->fetchByAssoc($result))
 176          {
 177              $temp_result[$row['id']] = getFullNameFromArray('Users', $row);
 178          }
 179  
 180          $user_array = &$temp_result;
 181      }
 182  
 183      $log->debug("Exiting get_user_array method ...");
 184      return $user_array;
 185  }
 186  
 187  function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="",$module = false)
 188  {
 189      global $log;
 190      $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ...");
 191      global $current_user;
 192      if(isset($current_user) && $current_user->id != '')
 193      {
 194          require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
 195          require('user_privileges/user_privileges_'.$current_user->id.'.php');
 196      }
 197      static $group_array = null;
 198      if(!$module){
 199          $module=$_REQUEST['module'];
 200      }
 201  
 202      if($group_array == null)
 203      {
 204          require_once ('include/database/PearDatabase.php');
 205          $db = PearDatabase::getInstance();
 206          $temp_result = Array();
 207          // Including deleted vtiger_users for now.
 208          $log->debug("Sharing is Public. All vtiger_users should be listed");
 209          $query = "SELECT groupid, groupname from vtiger_groups";
 210          $params = array();
 211  
 212          if($private == 'private'){
 213  
 214              $query .= " WHERE groupid=?";
 215              $params = array( $current_user->id);
 216  
 217              if(count($current_user_groups) != 0) {
 218                  $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")";
 219                  array_push($params, $current_user_groups);
 220              }
 221              $log->debug("Sharing is Private. Only the current user should be listed");
 222              $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?";
 223              array_push($params, $current_user_parent_role_seq."::%");
 224  
 225              if(count($current_user_groups) != 0) {
 226                  $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")";
 227                  array_push($params, $parent_roles);
 228              }
 229  
 230              $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?";
 231              array_push($params, $current_user->id);
 232  
 233              $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?";
 234              array_push($params,  getTabid($module));
 235          }
 236          $query .= " order by groupname ASC";
 237  
 238          $result = $db->pquery($query, $params, true, "Error filling in user array: ");
 239  
 240          if ($add_blank==true){
 241              // Add in a blank row
 242              $temp_result[''] = '';
 243          }
 244  
 245          // Get the id and the name.
 246          while($row = $db->fetchByAssoc($result))
 247          {
 248              $temp_result[$row['groupid']] = $row['groupname'];
 249          }
 250  
 251          $group_array = &$temp_result;
 252      }
 253  
 254      $log->debug("Exiting get_user_array method ...");
 255      return $group_array;
 256  }
 257  
 258  /** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var.
 259   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 260   * All Rights Reserved.
 261   * Contributor(s): ______________________________________..
 262   * If you are using the current language, do not call this function unless you are loading it for the first time */
 263  
 264  function return_app_list_strings_language($language) {
 265      return Vtiger_Deprecated::return_app_list_strings_language($language);
 266  }
 267  
 268  /**
 269   * Retrieve the app_currency_strings for the required language.
 270   */
 271  function return_app_currency_strings_language($language) {
 272      return Vtiger_Deprecated::return_app_list_strings_language($language);
 273  }
 274  
 275  /** This function retrieves an application language file and returns the array of strings included.
 276   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 277   * All Rights Reserved.
 278   * Contributor(s): ______________________________________..
 279   * If you are using the current language, do not call this function unless you are loading it for the first time */
 280  function return_application_language($language) {
 281      return Vtiger_Deprecated::return_app_list_strings_language($language);
 282      }
 283  
 284  /** This function retrieves a module's language file and returns the array of strings included.
 285   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 286   * All Rights Reserved.
 287   * Contributor(s): ______________________________________..
 288   * If you are in the current module, do not call this function unless you are loading it for the first time */
 289  function return_module_language($language, $module) {
 290      return Vtiger_Deprecated::getModuleTranslationStrings($language, $module);
 291  }
 292  
 293  /*This function returns the mod_strings for the current language and the specified module
 294  */
 295  
 296  function return_specified_module_language($language, $module) {
 297      return Vtiger_Deprecated::return_app_list_strings_language($language, $module);
 298  }
 299  
 300  /**
 301   * Return an array of directory names.
 302   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 303   * All Rights Reserved.
 304   * Contributor(s): ______________________________________..
 305   */
 306  function get_themes() {
 307      return Vtiger_Theme::getAllSkins();
 308     }
 309  
 310  
 311  /** Function to set default varibles on to the global variable
 312    * @param $defaults -- default values:: Type array
 313         */
 314  function set_default_config(&$defaults)
 315  {
 316      global $log;
 317      $log->debug("Entering set_default_config(".$defaults.") method ...");
 318  
 319      foreach ($defaults as $name=>$value)
 320      {
 321          if ( ! isset($GLOBALS[$name]) )
 322          {
 323              $GLOBALS[$name] = $value;
 324          }
 325      }
 326      $log->debug("Exiting set_default_config method ...");
 327  }
 328  
 329  $toHtml = array(
 330          '"' => '&quot;',
 331          '<' => '&lt;',
 332          '>' => '&gt;',
 333          '& ' => '&amp; ',
 334          "'" =>  '&#039;',
 335      '' => '\r',
 336          '\r\n'=>'\n',
 337  
 338  );
 339  
 340  /** Function to convert the given string to html
 341    * @param $string -- string:: Type string
 342    * @param $ecnode -- boolean:: Type boolean
 343      * @returns $string -- string:: Type string
 344        *
 345         */
 346  function to_html($string, $encode=true)
 347  {
 348      global $log,$default_charset;
 349      //$log->debug("Entering to_html(".$string.",".$encode.") method ...");
 350      global $toHtml;
 351      $action = $_REQUEST['action'];
 352      $search = $_REQUEST['search'];
 353  
 354      $doconvert = false;
 355  
 356      // For optimization - default_charset can be either upper / lower case.
 357      static $inUTF8 = NULL;
 358      if ($inUTF8 === NULL) {
 359          $inUTF8 = (strtoupper($default_charset) == 'UTF-8');
 360      }
 361  
 362      if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails')
 363          $ajax_action = $_REQUEST['module'].'Ajax';
 364  
 365      if(is_string($string))
 366      {
 367          if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) )
 368          {
 369              $doconvert = true;
 370          }
 371          else if($search == true)
 372          {
 373              // Fix for tickets #4647, #4648. Conversion required in case of search results also.
 374              $doconvert = true;
 375          }
 376  
 377          // In vtiger5 ajax request are treated specially and the data is encoded
 378          if ($doconvert == true)
 379          {
 380              if($inUTF8)
 381                  $string = htmlentities($string, ENT_QUOTES, $default_charset);
 382              else
 383                  $string = preg_replace(array('/</', '/>/', '/"/'), array('&lt;', '&gt;', '&quot;'), $string);
 384          }
 385      }
 386  
 387      //$log->debug("Exiting to_html method ...");
 388      return $string;
 389  }
 390  
 391  /** Function to get the tablabel for a given id
 392    * @param $tabid -- tab id:: Type integer
 393    * @returns $string -- string:: Type string
 394  */
 395  
 396  function getTabname($tabid)
 397  {
 398      global $log;
 399      $log->debug("Entering getTabname(".$tabid.") method ...");
 400          $log->info("tab id is ".$tabid);
 401          global $adb;
 402  
 403      static $cache = array();
 404  
 405      if (!isset($cache[$tabid])) {
 406          $sql = "select tablabel from vtiger_tab where tabid=?";
 407          $result = $adb->pquery($sql, array($tabid));
 408          $tabname=  $adb->query_result($result,0,"tablabel");
 409          $cache[$tabid] = $tabname;
 410      }
 411  
 412      $log->debug("Exiting getTabname method ...");
 413      return $cache[$tabid];
 414  
 415  }
 416  
 417  /** Function to get the tab module name for a given id
 418    * @param $tabid -- tab id:: Type integer
 419      * @returns $string -- string:: Type string
 420        *
 421         */
 422  
 423  function getTabModuleName($tabid)
 424  {
 425      return Vtiger_Functions::getModuleName($tabid);
 426  }
 427  
 428  /** Function to get column fields for a given module
 429    * @param $module -- module:: Type string
 430      * @returns $column_fld -- column field :: Type array
 431        *
 432         */
 433  
 434  function getColumnFields($module)
 435  {
 436      global $log;
 437      $log->debug("Entering getColumnFields(".$module.") method ...");
 438      $log->debug("in getColumnFields ".$module);
 439  
 440      // Lookup in cache for information
 441      $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
 442  
 443      if($cachedModuleFields === false) {
 444          global $adb;
 445          $tabid = getTabid($module);
 446  
 447          if ($module == 'Calendar') {
 448              $tabid = array('9','16');
 449          }
 450  
 451          // To overcome invalid module names.
 452          if (empty($tabid)) {
 453              return array();
 454          }
 455  
 456          // Let us pick up all the fields first so that we can cache information
 457          $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence
 458          FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")";
 459  
 460          $result = $adb->pquery($sql, array($tabid));
 461          $noofrows = $adb->num_rows($result);
 462  
 463          if($noofrows) {
 464              while($resultrow = $adb->fetch_array($result)) {
 465                  // Update information to cache for re-use
 466                  VTCacheUtils::updateFieldInfo(
 467                      $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'],
 468                      $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'],
 469                      $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']
 470                  );
 471              }
 472          }
 473  
 474          // For consistency get information from cache
 475          $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
 476      }
 477  
 478      if($module == 'Calendar') {
 479          $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events');
 480          if ($cachedEventsFields) {
 481              if(empty($cachedModuleFields)) $cachedModuleFields = $cachedEventsFields;
 482              else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields);
 483          }
 484      }
 485  
 486      $column_fld = array();
 487      if($cachedModuleFields) {
 488          foreach($cachedModuleFields as $fieldinfo) {
 489              $column_fld[$fieldinfo['fieldname']] = '';
 490          }
 491      }
 492  
 493      $log->debug("Exiting getColumnFields method ...");
 494      return $column_fld;
 495  }
 496  
 497  /** Function to get a users's mail id
 498    * @param $userid -- userid :: Type integer
 499      * @returns $email -- email :: Type string
 500        *
 501         */
 502  
 503  function getUserEmail($userid)
 504  {
 505      global $log;
 506      $log->debug("Entering getUserEmail(".$userid.") method ...");
 507      $log->info("in getUserEmail ".$userid);
 508  
 509          global $adb;
 510          if($userid != '')
 511          {
 512                  $sql = "select email1 from vtiger_users where id=?";
 513                  $result = $adb->pquery($sql, array($userid));
 514                  $email = $adb->query_result($result,0,"email1");
 515          }
 516      $log->debug("Exiting getUserEmail method ...");
 517          return $email;
 518  }
 519  
 520  /** Function to get a userid for outlook
 521    * @param $username -- username :: Type string
 522      * @returns $user_id -- user id :: Type integer
 523         */
 524  
 525  //outlook security
 526  function getUserId_Ol($username)
 527  {
 528      global $log;
 529      $log->debug("Entering getUserId_Ol(".$username.") method ...");
 530      $log->info("in getUserId_Ol ".$username);
 531      $cache = Vtiger_Cache::getInstance();
 532      if($cache->getUserId($username) || $cache->getUserId($username) === 0){
 533          return $cache->getUserId($username);
 534      } else {
 535      global $adb;
 536      $sql = "select id from vtiger_users where user_name=?";
 537      $result = $adb->pquery($sql, array($username));
 538      $num_rows = $adb->num_rows($result);
 539      if($num_rows > 0)
 540      {
 541          $user_id = $adb->query_result($result,0,"id");
 542          }
 543      else
 544      {
 545          $user_id = 0;
 546      }
 547      $log->debug("Exiting getUserId_Ol method ...");
 548          $cache->setUserId($username,$user_id);
 549      return $user_id;
 550      }
 551  }
 552  
 553  
 554  /** Function to get a action id for a given action name
 555    * @param $action -- action name :: Type string
 556      * @returns $actionid -- action id :: Type integer
 557         */
 558  
 559  //outlook security
 560  
 561  function getActionid($action)
 562  {
 563      global $log;
 564      $log->debug("Entering getActionid(".$action.") method ...");
 565      global $adb;
 566      $log->info("get Actionid ".$action);
 567      $actionid = '';
 568      if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0))
 569      {
 570          include ('tabdata.php');
 571          $actionid= $action_id_array[$action];
 572      }
 573      else
 574      {
 575          $query="select * from vtiger_actionmapping where actionname=?";
 576              $result =$adb->pquery($query, array($action));
 577              $actionid=$adb->query_result($result,0,'actionid');
 578  
 579      }
 580      $log->info("action id selected is ".$actionid );
 581      $log->debug("Exiting getActionid method ...");
 582      return $actionid;
 583  }
 584  
 585  /** Function to get a action for a given action id
 586    * @param $action id -- action id :: Type integer
 587      * @returns $actionname-- action name :: Type string
 588         */
 589  
 590  
 591  function getActionname($actionid)
 592  {
 593      global $log;
 594      $log->debug("Entering getActionname(".$actionid.") method ...");
 595      global $adb;
 596  
 597      $actionname='';
 598  
 599      if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0))
 600      {
 601          include ('tabdata.php');
 602          $actionname= $action_name_array[$actionid];
 603      }
 604      else
 605      {
 606  
 607          $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0";
 608          $result =$adb->pquery($query, array($actionid));
 609          $actionname=$adb->query_result($result,0,"actionname");
 610      }
 611      $log->debug("Exiting getActionname method ...");
 612      return $actionname;
 613  }
 614  
 615  /** Function to get a user id or group id for a given entity
 616    * @param $record -- entity id :: Type integer
 617      * @returns $ownerArr -- owner id :: Type array
 618         */
 619  
 620  function getRecordOwnerId($record)
 621  {
 622      global $log;
 623      $log->debug("Entering getRecordOwnerId(".$record.") method ...");
 624      global $adb;
 625      $ownerArr=Array();
 626  
 627      // Look at cache first for information
 628      $ownerId = VTCacheUtils::lookupRecordOwner($record);
 629  
 630      if($ownerId === false) {
 631          $query="select smownerid from vtiger_crmentity where crmid = ?";
 632          $result=$adb->pquery($query, array($record));
 633          if($adb->num_rows($result) > 0)
 634          {
 635              $ownerId=$adb->query_result($result,0,'smownerid');
 636              // Update cache for re-use
 637              VTCacheUtils::updateRecordOwner($record, $ownerId);
 638          }
 639      }
 640  
 641      if($ownerId)
 642      {
 643          // Look at cache first for information
 644          $count = VTCacheUtils::lookupOwnerType($ownerId);
 645  
 646          if($count === false) {
 647              $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId));
 648              $count = $adb->query_result($sql_result,0,'count');
 649              // Update cache for re-use
 650              VTCacheUtils::updateOwnerType($ownerId, $count);
 651          }
 652          if($count > 0)
 653              $ownerArr['Users'] = $ownerId;
 654          else
 655              $ownerArr['Groups'] = $ownerId;
 656      }
 657      $log->debug("Exiting getRecordOwnerId method ...");
 658      return $ownerArr;
 659  
 660  }
 661  
 662  /** Function to insert value to profile2field table
 663    * @param $profileid -- profileid :: Type integer
 664         */
 665  
 666  
 667  function insertProfile2field($profileid)
 668  {
 669      global $log;
 670      $log->debug("Entering insertProfile2field(".$profileid.") method ...");
 671          $log->info("in insertProfile2field ".$profileid);
 672  
 673      global $adb;
 674      $adb->database->SetFetchMode(ADODB_FETCH_ASSOC);
 675      $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array());
 676      $num_rows = $adb->num_rows($fld_result);
 677      for($i=0; $i<$num_rows; $i++) {
 678           $tab_id = $adb->query_result($fld_result,$i,'tabid');
 679           $field_id = $adb->query_result($fld_result,$i,'fieldid');
 680           $params = array($profileid, $tab_id, $field_id, 0, 0);
 681           $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params);
 682      }
 683      $log->debug("Exiting insertProfile2field method ...");
 684  }
 685  
 686  /** Function to insert into default org field
 687         */
 688  
 689  function insert_def_org_field()
 690  {
 691      global $log;
 692      $log->debug("Entering insert_def_org_field() method ...");
 693      global $adb;
 694      $adb->database->SetFetchMode(ADODB_FETCH_ASSOC);
 695      $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array());
 696          $num_rows = $adb->num_rows($fld_result);
 697          for($i=0; $i<$num_rows; $i++)
 698          {
 699                   $tab_id = $adb->query_result($fld_result,$i,'tabid');
 700                   $field_id = $adb->query_result($fld_result,$i,'fieldid');
 701                   $params = array($tab_id, $field_id, 0, 0);
 702                   $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params);
 703      }
 704      $log->debug("Exiting insert_def_org_field() method ...");
 705  }
 706  
 707  /** Function to update product quantity
 708    * @param $product_id -- product id :: Type integer
 709    * @param $upd_qty -- quantity :: Type integer
 710    */
 711  
 712  function updateProductQty($product_id, $upd_qty)
 713  {
 714      global $log;
 715      $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ...");
 716      global $adb;
 717      $query= "update vtiger_products set qtyinstock=? where productid=?";
 718      $adb->pquery($query, array($upd_qty, $product_id));
 719      $log->debug("Exiting updateProductQty method ...");
 720  
 721  }
 722  
 723  /** This Function adds the specified product quantity to the Product Quantity in Stock in the Warehouse
 724    * The following is the input parameter for the function:
 725    *  $productId --> ProductId, Type:Integer
 726    *  $qty --> Quantity to be added, Type:Integer
 727    */
 728  function addToProductStock($productId,$qty)
 729  {
 730      global $log;
 731      $log->debug("Entering addToProductStock(".$productId.",".$qty.") method ...");
 732      global $adb;
 733      $qtyInStck=getProductQtyInStock($productId);
 734      $updQty=$qtyInStck + $qty;
 735      $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?";
 736      $adb->pquery($sql, array($updQty, $productId));
 737      $log->debug("Exiting addToProductStock method ...");
 738  
 739      }
 740  
 741  /**    This Function adds the specified product quantity to the Product Quantity in Demand in the Warehouse
 742    *    @param int $productId - ProductId
 743    *    @param int $qty - Quantity to be added
 744    */
 745  function addToProductDemand($productId,$qty)
 746  {
 747      global $log;
 748      $log->debug("Entering addToProductDemand(".$productId.",".$qty.") method ...");
 749          global $adb;
 750      $qtyInStck=getProductQtyInDemand($productId);
 751      $updQty=$qtyInStck + $qty;
 752      $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?";
 753      $adb->pquery($sql, array($updQty, $productId));
 754      $log->debug("Exiting addToProductDemand method ...");
 755  
 756          }
 757  
 758  /**    This Function subtract the specified product quantity to the Product Quantity in Stock in the Warehouse
 759    *    @param int $productId - ProductId
 760    *    @param int $qty - Quantity to be subtracted
 761    */
 762  function deductFromProductStock($productId,$qty)
 763  {
 764      global $log;
 765      $log->debug("Entering deductFromProductStock(".$productId.",".$qty.") method ...");
 766      global $adb;
 767      $qtyInStck=getProductQtyInStock($productId);
 768      $updQty=$qtyInStck - $qty;
 769      $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?";
 770      $adb->pquery($sql, array($updQty, $productId));
 771      $log->debug("Exiting deductFromProductStock method ...");
 772  
 773  }
 774  
 775  /**    This Function subtract the specified product quantity to the Product Quantity in Demand in the Warehouse
 776    *    @param int $productId - ProductId
 777    *    @param int $qty - Quantity to be subtract
 778    */
 779  function deductFromProductDemand($productId,$qty)
 780  {
 781      global $log;
 782      $log->debug("Entering deductFromProductDemand(".$productId.",".$qty.") method ...");
 783      global $adb;
 784      $qtyInStck=getProductQtyInDemand($productId);
 785      $updQty=$qtyInStck - $qty;
 786      $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?";
 787      $adb->pquery($sql, array($updQty, $productId));
 788      $log->debug("Exiting deductFromProductDemand method ...");
 789  
 790      }
 791  
 792  
 793  /** This Function returns the current product quantity in stock.
 794    * The following is the input parameter for the function:
 795    *  $product_id --> ProductId, Type:Integer
 796    */
 797  function getProductQtyInStock($product_id)
 798  {
 799      global $log;
 800      $log->debug("Entering getProductQtyInStock(".$product_id.") method ...");
 801      global $adb;
 802          $query1 = "select qtyinstock from vtiger_products where productid=?";
 803          $result=$adb->pquery($query1, array($product_id));
 804          $qtyinstck= $adb->query_result($result,0,"qtyinstock");
 805      $log->debug("Exiting getProductQtyInStock method ...");
 806          return $qtyinstck;
 807  
 808  
 809  }
 810  
 811  /**    This Function returns the current product quantity in demand.
 812    *    @param int $product_id - ProductId
 813    *    @return int $qtyInDemand - Quantity in Demand of a product
 814    */
 815  function getProductQtyInDemand($product_id)
 816  {
 817      global $log;
 818      $log->debug("Entering getProductQtyInDemand(".$product_id.") method ...");
 819      global $adb;
 820          $query1 = "select qtyindemand from vtiger_products where productid=?";
 821          $result = $adb->pquery($query1, array($product_id));
 822          $qtyInDemand = $adb->query_result($result,0,"qtyindemand");
 823      $log->debug("Exiting getProductQtyInDemand method ...");
 824          return $qtyInDemand;
 825  }
 826  
 827  /**     Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module
 828   *      @param  : string $module - current module value
 829   *      @param  : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename
 830   *      @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis
 831    */
 832  function getTableNameForField($module,$fieldname)
 833  {
 834      global $log;
 835      $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ...");
 836      global $adb;
 837      $tabid = getTabid($module);
 838      //Asha
 839      if($module == 'Calendar') {
 840          $tabid = array('9','16');
 841  }
 842      $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.presence in (0,2) and columnname like ?";
 843      $res = $adb->pquery($sql, array($tabid, '%'.$fieldname.'%'));
 844  
 845      $tablename = '';
 846      if($adb->num_rows($res) > 0)
 847  {
 848          $tablename = $adb->query_result($res,0,'tablename');
 849      }
 850  
 851      $log->debug("Exiting getTableNameForField method ...");
 852      return $tablename;
 853  }
 854  
 855  /** Function to get parent record owner
 856    * @param $tabid -- tabid :: Type integer
 857    * @param $parModId -- parent module id :: Type integer
 858    * @param $record_id -- record id :: Type integer
 859    * @returns $parentRecOwner -- parentRecOwner:: Type integer
 860    */
 861  
 862  function getParentRecordOwner($tabid,$parModId,$record_id)
 863   {
 864      global $log;
 865      $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ...");
 866      $parentRecOwner=Array();
 867      $parentTabName=getTabname($parModId);
 868      $relTabName=getTabname($tabid);
 869      $fn_name="get".$relTabName."Related".$parentTabName;
 870      $ent_id=$fn_name($record_id);
 871      if($ent_id != '')
 872          {
 873          $parentRecOwner=getRecordOwnerId($ent_id);
 874          }
 875      $log->debug("Exiting getParentRecordOwner method ...");
 876      return $parentRecOwner;
 877          }
 878  
 879  /** Function to get potential related accounts
 880    * @param $record_id -- record id :: Type integer
 881    * @returns $accountid -- accountid:: Type integer
 882    */
 883  
 884  function getPotentialsRelatedAccounts($record_id)
 885  {
 886      global $log;
 887      $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ...");
 888      global $adb;
 889      $query="select related_to from vtiger_potential where potentialid=?";
 890      $result=$adb->pquery($query, array($record_id));
 891      $accountid=$adb->query_result($result,0,'related_to');
 892      $log->debug("Exiting getPotentialsRelatedAccounts method ...");
 893      return $accountid;
 894  }
 895  
 896  /** Function to get email related accounts
 897    * @param $record_id -- record id :: Type integer
 898    * @returns $accountid -- accountid:: Type integer
 899    */
 900  function getEmailsRelatedAccounts($record_id)
 901  {
 902      global $log;
 903      $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ...");
 904      global $adb;
 905      $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?";
 906      $result = $adb->pquery($query, array($record_id));
 907      $accountid=$adb->query_result($result,0,'crmid');
 908      $log->debug("Exiting getEmailsRelatedAccounts method ...");
 909      return $accountid;
 910  }
 911  /** Function to get email related Leads
 912    * @param $record_id -- record id :: Type integer
 913    * @returns $leadid -- leadid:: Type integer
 914    */
 915  
 916  function getEmailsRelatedLeads($record_id)
 917  {
 918      global $log;
 919      $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ...");
 920      global $adb;
 921      $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?";
 922      $result = $adb->pquery($query, array($record_id));
 923      $leadid=$adb->query_result($result,0,'crmid');
 924      $log->debug("Exiting getEmailsRelatedLeads method ...");
 925      return $leadid;
 926  }
 927  
 928  /** Function to get HelpDesk related Accounts
 929    * @param $record_id -- record id :: Type integer
 930    * @returns $accountid -- accountid:: Type integer
 931    */
 932  
 933  function getHelpDeskRelatedAccounts($record_id)
 934  {
 935      global $log;
 936      $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ...");
 937      global $adb;
 938          $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'";
 939          $result=$adb->pquery($query, array($record_id));
 940          $accountid=$adb->query_result($result,0,'parent_id');
 941      $log->debug("Exiting getHelpDeskRelatedAccounts method ...");
 942          return $accountid;
 943  }
 944  
 945  /** Function to get Quotes related Accounts
 946    * @param $record_id -- record id :: Type integer
 947    * @returns $accountid -- accountid:: Type integer
 948    */
 949  
 950  function getQuotesRelatedAccounts($record_id)
 951  {
 952      global $log;
 953      $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ...");
 954      global $adb;
 955          $query="select accountid from vtiger_quotes where quoteid=?";
 956          $result=$adb->pquery($query, array($record_id));
 957          $accountid=$adb->query_result($result,0,'accountid');
 958      $log->debug("Exiting getQuotesRelatedAccounts method ...");
 959          return $accountid;
 960  }
 961  
 962  /** Function to get Quotes related Potentials
 963    * @param $record_id -- record id :: Type integer
 964    * @returns $potid -- potid:: Type integer
 965    */
 966  
 967  function getQuotesRelatedPotentials($record_id)
 968  {
 969      global $log;
 970      $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ...");
 971      global $adb;
 972          $query="select potentialid from vtiger_quotes where quoteid=?";
 973          $result=$adb->pquery($query, array($record_id));
 974          $potid=$adb->query_result($result,0,'potentialid');
 975      $log->debug("Exiting getQuotesRelatedPotentials method ...");
 976          return $potid;
 977  }
 978  
 979  /** Function to get Quotes related Potentials
 980    * @param $record_id -- record id :: Type integer
 981    * @returns $accountid -- accountid:: Type integer
 982    */
 983  
 984  function getSalesOrderRelatedAccounts($record_id)
 985  {
 986      global $log;
 987      $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ...");
 988      global $adb;
 989          $query="select accountid from vtiger_salesorder where salesorderid=?";
 990          $result=$adb->pquery($query, array($record_id));
 991          $accountid=$adb->query_result($result,0,'accountid');
 992      $log->debug("Exiting getSalesOrderRelatedAccounts method ...");
 993          return $accountid;
 994  }
 995  
 996  /** Function to get SalesOrder related Potentials
 997    * @param $record_id -- record id :: Type integer
 998    * @returns $potid -- potid:: Type integer
 999    */
1000  
1001  function getSalesOrderRelatedPotentials($record_id)
1002  {
1003      global $log;
1004      $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ...");
1005      global $adb;
1006          $query="select potentialid from vtiger_salesorder where salesorderid=?";
1007          $result=$adb->pquery($query, array($record_id));
1008          $potid=$adb->query_result($result,0,'potentialid');
1009      $log->debug("Exiting getSalesOrderRelatedPotentials method ...");
1010          return $potid;
1011  }
1012  /** Function to get SalesOrder related Quotes
1013    * @param $record_id -- record id :: Type integer
1014    * @returns $qtid -- qtid:: Type integer
1015    */
1016  
1017  function getSalesOrderRelatedQuotes($record_id)
1018  {
1019      global $log;
1020      $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ...");
1021      global $adb;
1022          $query="select quoteid from vtiger_salesorder where salesorderid=?";
1023          $result=$adb->pquery($query, array($record_id));
1024          $qtid=$adb->query_result($result,0,'quoteid');
1025      $log->debug("Exiting getSalesOrderRelatedQuotes method ...");
1026          return $qtid;
1027  }
1028  
1029  /** Function to get Invoice related Accounts
1030    * @param $record_id -- record id :: Type integer
1031    * @returns $accountid -- accountid:: Type integer
1032    */
1033  
1034  function getInvoiceRelatedAccounts($record_id)
1035  {
1036      global $log;
1037      $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ...");
1038      global $adb;
1039          $query="select accountid from vtiger_invoice where invoiceid=?";
1040          $result=$adb->pquery($query, array($record_id));
1041          $accountid=$adb->query_result($result,0,'accountid');
1042      $log->debug("Exiting getInvoiceRelatedAccounts method ...");
1043          return $accountid;
1044  }
1045  /** Function to get Invoice related SalesOrder
1046    * @param $record_id -- record id :: Type integer
1047    * @returns $soid -- soid:: Type integer
1048    */
1049  
1050  function getInvoiceRelatedSalesOrder($record_id)
1051  {
1052      global $log;
1053      $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ...");
1054      global $adb;
1055          $query="select salesorderid from vtiger_invoice where invoiceid=?";
1056          $result=$adb->pquery($query, array($record_id));
1057          $soid=$adb->query_result($result,0,'salesorderid');
1058      $log->debug("Exiting getInvoiceRelatedSalesOrder method ...");
1059          return $soid;
1060  }
1061  
1062  /**
1063  * the function is like unescape in javascript
1064  * added by dingjianting on 2006-10-1 for picklist editor
1065  */
1066  function utf8RawUrlDecode ($source) {
1067      global $default_charset;
1068      $decodedStr = "";
1069      $pos = 0;
1070      $len = strlen ($source);
1071      while ($pos < $len) {
1072          $charAt = substr ($source, $pos, 1);
1073          if ($charAt == '%') {
1074              $pos++;
1075              $charAt = substr ($source, $pos, 1);
1076              if ($charAt == 'u') {
1077                  // we got a unicode character
1078                  $pos++;
1079                  $unicodeHexVal = substr ($source, $pos, 4);
1080                  $unicode = hexdec ($unicodeHexVal);
1081                  $entity = "&#". $unicode . ';';
1082                  $decodedStr .= utf8_encode ($entity);
1083                  $pos += 4;
1084          }
1085              else {
1086                  // we have an escaped ascii character
1087                  $hexVal = substr ($source, $pos, 2);
1088                  $decodedStr .= chr (hexdec ($hexVal));
1089                  $pos += 2;
1090   }
1091      } else {
1092              $decodedStr .= $charAt;
1093              $pos++;
1094          }
1095      }
1096      if(strtolower($default_charset) == 'utf-8')
1097          return html_to_utf8($decodedStr);
1098      else
1099          return $decodedStr;
1100      //return html_to_utf8($decodedStr);
1101  }
1102  
1103  /**
1104  *simple HTML to UTF-8 conversion:
1105    */
1106  function html_to_utf8 ($data)
1107  {
1108      return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data);
1109      }
1110  
1111  function _html_to_utf8 ($data)
1112      {
1113      if ($data > 127)
1114          {
1115          $i = 5;
1116          while (($i--) > 0)
1117          {
1118              if ($data != ($a = $data % ($p = pow(64, $i))))
1119      {
1120                  $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
1121                  for ($i; $i > 0; $i--)
1122                      $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
1123                  break;
1124      }
1125  }
1126      }
1127      else
1128          $ret = "&#$data;";
1129      return $ret;
1130      }
1131  
1132  // Return Question mark
1133  function _questionify($v){
1134      return "?";
1135  }
1136  
1137  /**
1138  * Function to generate question marks for a given list of items
1139    */
1140  function generateQuestionMarks($items_list) {
1141      // array_map will call the function specified in the first parameter for every element of the list in second parameter
1142      if (is_array($items_list)) {
1143          return implode(",", array_map("_questionify", $items_list));
1144      } else {
1145          return implode(",", array_map("_questionify", explode(",", $items_list)));
1146  }
1147  }
1148  
1149  /**
1150  * Function to find the UI type of a field based on the uitype id
1151    */
1152  function is_uitype($uitype, $reqtype) {
1153      $ui_type_arr = array(
1154          '_date_' => array(5, 6, 23, 70),
1155          '_picklist_' => array(15, 16, 52, 53, 54, 55, 59, 62, 63, 66, 68, 76, 77, 78, 80, 98, 101, 115, 357),
1156          '_users_list_' => array(52),
1157      );
1158  
1159      if ($ui_type_arr[$reqtype] != null) {
1160          if (in_array($uitype, $ui_type_arr[$reqtype])) {
1161              return true;
1162      }
1163      }
1164      return false;
1165      }
1166  /**
1167   * Function to escape quotes
1168   * @param $value - String in which single quotes have to be replaced.
1169   * @return Input string with single quotes escaped.
1170    */
1171  function escape_single_quotes($value) {
1172      if (isset($value)) $value = str_replace("'", "\'", $value);
1173      return $value;
1174  }
1175  
1176  /**
1177   * Function to format the input value for SQL like clause.
1178   * @param $str - Input string value to be formatted.
1179   * @param $flag - By default set to 0 (Will look for cases %string%).
1180   *                If set to 1 - Will look for cases %string.
1181   *                If set to 2 - Will look for cases string%.
1182   * @return String formatted as per the SQL like clause requirement
1183    */
1184  function formatForSqlLike($str, $flag=0,$is_field=false) {
1185      global $adb;
1186      if (isset($str)) {
1187          if($is_field==false){
1188              $str = str_replace('%', '\%', $str);
1189              $str = str_replace('_', '\_', $str);
1190              if ($flag == 0) {
1191                  // If value what to search is null then we should not add % which will fail
1192                  if(empty($str))
1193                      $str = ''.$str.'';
1194                  else
1195                      $str = '%'. $str .'%';
1196              } elseif ($flag == 1) {
1197                  $str = '%'. $str;
1198              } elseif ($flag == 2) {
1199                  $str = $str .'%';
1200              }
1201          } else {
1202              if ($flag == 0) {
1203                  $str = 'concat("%",'. $str .',"%")';
1204              } elseif ($flag == 1) {
1205                  $str = 'concat("%",'. $str .')';
1206              } elseif ($flag == 2) {
1207                  $str = 'concat('. $str .',"%")';
1208              }
1209          }
1210      }
1211      return $adb->sql_escape_string($str);
1212  }
1213  
1214  /**    Function used to get all the picklists and their values for a module
1215      @param string $module - Module name to which the list of picklists and their values needed
1216      @return array $fieldlists - Array of picklists and their values
1217  **/
1218  function getAccessPickListValues($module)
1219  {
1220      global $adb, $log;
1221      global $current_user;
1222      $log->debug("Entering into function getAccessPickListValues($module)");
1223  
1224      $id = getTabid($module);
1225      $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_field.presence in (0,2)";
1226      $result = $adb->pquery($query, array($id));
1227  
1228      $roleid = $current_user->roleid;
1229      $subrole = getRoleSubordinates($roleid);
1230  
1231      if(count($subrole)> 0)
1232  {
1233          $roleids = $subrole;
1234          array_push($roleids, $roleid);
1235      }
1236      else
1237      {
1238          $roleids = $roleid;
1239      }
1240  
1241      $temp_status = Array();
1242      for($i=0;$i < $adb->num_rows($result);$i++)
1243  {
1244          $fieldname = $adb->query_result($result,$i,"fieldname");
1245          $fieldlabel = $adb->query_result($result,$i,"fieldlabel");
1246          $columnname = $adb->query_result($result,$i,"columnname");
1247          $tabid = $adb->query_result($result,$i,"tabid");
1248          $uitype = $adb->query_result($result,$i,"uitype");
1249  
1250          $keyvalue = $columnname;
1251          $fieldvalues = Array();
1252          if (count($roleids) > 1)
1253      {
1254              $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc";
1255      }
1256      else
1257      {
1258              $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc";
1259      }
1260          if($fieldname != 'firstname')
1261              $mulselresult = $adb->query($mulsel);
1262          for($j=0;$j < $adb->num_rows($mulselresult);$j++)
1263          {
1264              $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname);
1265  }
1266          $field_count = count($fieldvalues);
1267          if($uitype == 15 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus'))
1268          {
1269              $temp_count =count($temp_status[$keyvalue]);
1270              if($temp_count > 0)
1271  {
1272                  for($t=0;$t < $field_count;$t++)
1273      {
1274                      $temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t];
1275                  }
1276                  $fieldvalues = $temp_status[$keyvalue];
1277      }
1278              else
1279                  $temp_status[$keyvalue] = $fieldvalues;
1280      }
1281          if($uitype == 33)
1282              $fieldlists[1][$keyvalue] = $fieldvalues;
1283          else if($uitype == 55 && $fieldname == 'salutationtype')
1284              $fieldlists[$keyvalue] = $fieldvalues;
1285          else if($uitype == 15)
1286              $fieldlists[$keyvalue] = $fieldvalues;
1287      }
1288      $log->debug("Exit from function getAccessPickListValues($module)");
1289  
1290      return $fieldlists;
1291      }
1292  
1293  function get_config_status() {
1294      global $default_charset;
1295      if(strtolower($default_charset) == 'utf-8')
1296          $config_status=1;
1297      else
1298          $config_status=0;
1299      return $config_status;
1300          }
1301  
1302  function getMigrationCharsetFlag() {
1303      global $adb;
1304  
1305      if(!$adb->isPostgres())
1306          $db_status=$adb->check_db_utf8_support();
1307      $config_status=get_config_status();
1308  
1309      if ($db_status == $config_status) {
1310          if ($db_status == 1) { // Both are UTF-8
1311              $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8;
1312          } else { // Both are Non UTF-8
1313              $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8;
1314  }
1315          } else {
1316              if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8
1317                  $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8;
1318          } else { // Database charset is Non UTF-8 and CRM charset is UTF-8
1319              $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8;
1320      }
1321      }
1322      return $db_migration_status;
1323  }
1324  
1325  /** Function to get on clause criteria for duplicate check queries */
1326  function get_on_clause($field_list,$uitype_arr,$module)
1327  {
1328      $field_array = explode(",",$field_list);
1329      $ret_str = '';
1330      $i=1;
1331      foreach($field_array as $fld)
1332      {
1333          $sub_arr = explode(".",$fld);
1334          $tbl_name = $sub_arr[0];
1335          $col_name = $sub_arr[1];
1336          $fld_name = $sub_arr[2];
1337  
1338          $ret_str .= " ifnull($tbl_name.$col_name,'null') = ifnull(temp.$col_name,'null')";
1339  
1340          if (count($field_array) != $i) $ret_str .= " and ";
1341          $i++;
1342      }
1343      return $ret_str;
1344  }
1345  
1346  // Update all the data refering to currency $old_cur to $new_cur
1347  function transferCurrency($old_cur, $new_cur) {
1348  
1349      // Transfer User currency to new currency
1350      transferUserCurrency($old_cur, $new_cur);
1351  
1352      // Transfer Product Currency to new currency
1353      transferProductCurrency($old_cur, $new_cur);
1354  
1355      // Transfer PriceBook Currency to new currency
1356      transferPriceBookCurrency($old_cur, $new_cur);
1357      }
1358  
1359  // Function to transfer the users with currency $old_cur to $new_cur as currency
1360  function transferUserCurrency($old_cur, $new_cur) {
1361      global $log, $adb, $current_user;
1362      $log->debug("Entering function transferUserCurrency...");
1363  
1364      $sql = "update vtiger_users set currency_id=? where currency_id=?";
1365      $adb->pquery($sql, array($new_cur, $old_cur));
1366  
1367      $current_user->retrieve_entity_info($current_user->id,"Users");
1368      $log->debug("Exiting function transferUserCurrency...");
1369  }
1370  
1371  // Function to transfer the products with currency $old_cur to $new_cur as currency
1372  function transferProductCurrency($old_cur, $new_cur) {
1373      global $log, $adb;
1374      $log->debug("Entering function updateProductCurrency...");
1375      $prod_res = $adb->pquery("select productid from vtiger_products where currency_id = ?", array($old_cur));
1376      $numRows = $adb->num_rows($prod_res);
1377      $prod_ids = array();
1378      for($i=0;$i<$numRows;$i++) {
1379          $prod_ids[] = $adb->query_result($prod_res,$i,'productid');
1380      }
1381      if(count($prod_ids) > 0) {
1382          $prod_price_list = getPricesForProducts($new_cur,$prod_ids);
1383  
1384          for($i=0;$i<count($prod_ids);$i++) {
1385              $product_id = $prod_ids[$i];
1386              $unit_price = $prod_price_list[$product_id];
1387              $query = "update vtiger_products set currency_id=?, unit_price=? where productid=?";
1388              $params = array($new_cur, $unit_price, $product_id);
1389              $adb->pquery($query, $params);
1390          }
1391  }
1392      $log->debug("Exiting function updateProductCurrency...");
1393  }
1394  
1395  // Function to transfer the pricebooks with currency $old_cur to $new_cur as currency
1396  // and to update the associated products with list price in $new_cur currency
1397  function transferPriceBookCurrency($old_cur, $new_cur) {
1398      global $log, $adb;
1399      $log->debug("Entering function updatePriceBookCurrency...");
1400      $pb_res = $adb->pquery("select pricebookid from vtiger_pricebook where currency_id = ?", array($old_cur));
1401      $numRows = $adb->num_rows($pb_res);
1402      $pb_ids = array();
1403      for($i=0;$i<$numRows;$i++) {
1404          $pb_ids[] = $adb->query_result($pb_res,$i,'pricebookid');
1405  }
1406  
1407      if(count($pb_ids) > 0) {
1408          require_once ('modules/PriceBooks/PriceBooks.php');
1409  
1410          for($i=0;$i<count($pb_ids);$i++) {
1411              $pb_id = $pb_ids[$i];
1412              $focus = new PriceBooks();
1413              $focus->id = $pb_id;
1414              $focus->mode = 'edit';
1415              $focus->retrieve_entity_info($pb_id, "PriceBooks");
1416              $focus->column_fields['currency_id'] = $new_cur;
1417              $focus->save("PriceBooks");
1418  }
1419  }
1420  
1421      $log->debug("Exiting function updatePriceBookCurrency...");
1422  }
1423  
1424  /**
1425   * this function searches for a given number in vtiger and returns the callerInfo in an array format
1426   * currently the search is made across only leads, accounts and contacts modules
1427   *
1428   * @param $number - the number whose information you want
1429   * @return array in format array(name=>callername, module=>module, id=>id);
1430    */
1431  function getCallerInfo($number){
1432      global $adb, $log;
1433      if(empty($number)){
1434          return false;
1435  }
1436      $caller = "Unknown Number (Unknown)"; //declare caller as unknown in beginning
1437  
1438      $params = array();
1439      $name = array('Contacts', 'Accounts', 'Leads');
1440      foreach ($name as $module) {
1441          $focus = CRMEntity::getInstance($module);
1442          $query = $focus->buildSearchQueryForFieldTypes(11, $number);
1443          if(empty($query)) return;
1444  
1445          $result = $adb->pquery($query, array());
1446          if($adb->num_rows($result) > 0 ){
1447              $callerName = $adb->query_result($result, 0, "name");
1448              $callerID = $adb->query_result($result,0,'id');
1449              $data = array("name"=>$callerName, "module"=>$module, "id"=>$callerID);
1450              return $data;
1451          }
1452      }
1453      return false;
1454  }
1455  
1456  /**
1457   * this function returns the value of use_asterisk from the database for the current user
1458   * @param string $id - the id of the current user
1459   */
1460  function get_use_asterisk($id){
1461      global $adb;
1462      if(!vtlib_isModuleActive('PBXManager') || isPermitted('PBXManager', 'index') == 'no'){
1463          return false;
1464      }
1465      $sql = "select * from vtiger_asteriskextensions where userid = ?";
1466      $result = $adb->pquery($sql, array($id));
1467      if($adb->num_rows($result)>0){
1468          $use_asterisk = $adb->query_result($result, 0, "use_asterisk");
1469          $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension");
1470          if($use_asterisk == 0 || empty($asterisk_extension)){
1471              return 'false';
1472          }else{
1473              return 'true';
1474      }
1475      }else{
1476          return 'false';
1477      }
1478  }
1479  
1480  /**
1481   * this function adds a record to the callhistory module
1482   *
1483   * @param string $userExtension - the extension of the current user
1484   * @param string $callfrom - the caller number
1485   * @param string $callto - the called number
1486   * @param string $status - the status of the call (outgoing/incoming/missed)
1487   * @param object $adb - the peardatabase object
1488    */
1489  function addToCallHistory($userExtension, $callfrom, $callto, $status, $adb, $useCallerInfo){
1490      $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
1491      $result = $adb->pquery($sql,array($userExtension));
1492      $userID = $adb->query_result($result, 0, "userid");
1493      if(empty($userID)) {
1494          // we have observed call to extension not configured in Vtiger will returns NULL
1495          return;
1496      }
1497      if(empty($callfrom)){
1498          $callfrom = "Unknown";
1499      }
1500      if(empty($callto)){
1501          $callto = "Unknown";
1502  }
1503  
1504      if($status == 'outgoing'){
1505          //call is from user to record
1506          $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
1507          $result = $adb->pquery($sql, array($callfrom));
1508          if($adb->num_rows($result)>0){
1509              $userid = $adb->query_result($result, 0, "userid");
1510              $callerName = getUserFullName($userid);
1511          }
1512  
1513          $receiver = $useCallerInfo;
1514          if(empty($receiver)){
1515              $receiver = "Unknown";
1516          }else{
1517              $receiver = "<a href='index.php?module=".$receiver['module']."&action=DetailView&record=".$receiver['id']."'>".$receiver['name']."</a>";
1518          }
1519      }else{
1520          //call is from record to user
1521          $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?";
1522          $result = $adb->pquery($sql,array($callto));
1523          if($adb->num_rows($result)>0){
1524              $userid = $adb->query_result($result, 0, "userid");
1525              $receiver = getUserFullName($userid);
1526          }
1527          $callerName = $useCallerInfo;
1528          if(empty($callerName)){
1529              $callerName = "Unknown $callfrom";
1530          }else{
1531              $callerName = "<a href='index.php?module=".$callerName['module']."&action=DetailView&record=".$callerName['id']."'>".decode_html($callerName['name'])."</a>";
1532  }
1533  }
1534  
1535      $crmID = $adb->getUniqueID('vtiger_crmentity');
1536      $timeOfCall = date('Y-m-d H:i:s');
1537  
1538      $query = "INSERT INTO vtiger_crmentity (crmid,smcreatorid,smownerid,modifiedby,setype,description,createdtime,
1539              modifiedtime,viewedtime,status,version,presence,deleted,label) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
1540      $adb->pquery($query, array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0, $callerName));
1541  
1542      $sql = "insert into vtiger_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)";
1543      $params = array($crmID, $callerName, $receiver, $timeOfCall, $status);
1544      $adb->pquery($sql, $params);
1545      return $crmID;
1546  }
1547  //functions for asterisk integration end
1548  
1549  /* Function to get the related tables data
1550   * @param - $module - Primary module name
1551   * @param - $secmodule - Secondary module name
1552   * return Array $rel_array tables and fields to be compared are sent
1553   * */
1554  function getRelationTables($module,$secmodule){
1555      global $adb;
1556      $primary_obj = CRMEntity::getInstance($module);
1557      $secondary_obj = CRMEntity::getInstance($secmodule);
1558  
1559      $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?)",array($module,$secmodule,$secmodule,$module));
1560      if($adb->num_rows($ui10_query)>0){
1561          $ui10_tablename = $adb->query_result($ui10_query,0,'tablename');
1562          $ui10_columnname = $adb->query_result($ui10_query,0,'columnname');
1563          $ui10_tabid = $adb->query_result($ui10_query,0,'tabid');
1564  
1565          if($primary_obj->table_name == $ui10_tablename){
1566              $reltables = array($ui10_tablename=>array("".$primary_obj->table_index."","$ui10_columnname"));
1567          } else if($secondary_obj->table_name == $ui10_tablename){
1568              $reltables = array($ui10_tablename=>array("$ui10_columnname","".$secondary_obj->table_index.""),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
1569          } else {
1570              if(isset($secondary_obj->tab_name_index[$ui10_tablename])){
1571                  $rel_field = $secondary_obj->tab_name_index[$ui10_tablename];
1572                  $reltables = array($ui10_tablename=>array("$ui10_columnname","$rel_field"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
1573              } else {
1574                  $rel_field = $primary_obj->tab_name_index[$ui10_tablename];
1575                  $reltables = array($ui10_tablename=>array("$rel_field","$ui10_columnname"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
1576              }
1577          }
1578      }else {
1579          if(method_exists($primary_obj,setRelationTables)){
1580              $reltables = $primary_obj->setRelationTables($secmodule);
1581          } else {
1582              $reltables = '';
1583          }
1584      }
1585      if(is_array($reltables) && !empty($reltables)){
1586          $rel_array = $reltables;
1587      } else {
1588          $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
1589      }
1590      return $rel_array;
1591  }
1592  
1593  /**
1594   * This function returns no value but handles the delete functionality of each entity.
1595   * Input Parameter are $module - module name, $return_module - return module name, $focus - module object, $record - entity id, $return_id - return entity id.
1596    */
1597  function DeleteEntity($module,$return_module,$focus,$record,$return_id) {
1598      global $log;
1599      $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)");
1600  
1601      if ($module != $return_module && !empty($return_module) && !empty($return_id)) {
1602          $focus->unlinkRelationship($record, $return_module, $return_id);
1603          $focus->trackUnLinkedInfo($return_module, $return_id, $module, $record);
1604      } else {
1605          $focus->trash($module, $record);
1606      }
1607      $log->debug("Exiting DeleteEntity method ...");
1608  }
1609  
1610  /**
1611   * Function to related two records of different entity types
1612    */
1613  function relateEntities($focus, $sourceModule, $sourceRecordId, $destinationModule, $destinationRecordIds) {
1614      if(!is_array($destinationRecordIds)) $destinationRecordIds = Array($destinationRecordIds);
1615      foreach($destinationRecordIds as $destinationRecordId) {
1616          $focus->save_related_module($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId);
1617          $focus->trackLinkedInfo($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId);
1618      }
1619  }
1620  
1621  /**
1622   * Track install/update vtlib module in current run.
1623   */
1624  $_installOrUpdateVtlibModule = array();
1625  
1626  /* Function to install Vtlib Compliant modules
1627   * @param - $packagename - Name of the module
1628   * @param - $packagepath - Complete path to the zip file of the Module
1629    */
1630  function installVtlibModule($packagename, $packagepath, $customized=false) {
1631      global $log, $Vtiger_Utils_Log, $_installOrUpdateVtlibModule;
1632      if(!file_exists($packagepath)) return;
1633  
1634      if (isset($_installOrUpdateVtlibModule[$packagename.$packagepath])) return;
1635      $_installOrUpdateVtlibModule[$packagename.$packagepath] = 'install';
1636  
1637      require_once ('vtlib/Vtiger/Package.php');
1638      require_once ('vtlib/Vtiger/Module.php');
1639      $Vtiger_Utils_Log = defined('INSTALLATION_MODE_DEBUG')? INSTALLATION_MODE_DEBUG : true;
1640      $package = new Vtiger_Package();
1641  
1642      if($package->isLanguageType($packagepath)) {
1643          $package = new Vtiger_Language();
1644          $package->import($packagepath, true);
1645          return;
1646  }
1647      $module = $package->getModuleNameFromZip($packagepath);
1648  
1649      // Customization
1650      if($package->isLanguageType()) {
1651          require_once ('vtlib/Vtiger/Language.php');
1652          $languagePack = new Vtiger_Language();
1653          @$languagePack->import($packagepath, true);
1654          return;
1655  }
1656      // END
1657  
1658      $module_exists = false;
1659      $module_dir_exists = false;
1660      if($module == null) {
1661          $log->fatal("$packagename Module zipfile is not valid!");
1662      } else if(Vtiger_Module::getInstance($module)) {
1663          $log->fatal("$module already exists!");
1664          $module_exists = true;
1665      }
1666      if($module_exists == false) {
1667          $log->debug("$module - Installation starts here");
1668          $package->import($packagepath, true);
1669          $moduleInstance = Vtiger_Module::getInstance($module);
1670          if (empty($moduleInstance)) {
1671              $log->fatal("$module module installation failed!");
1672          }
1673      }
1674  }
1675  
1676  /* Function to update Vtlib Compliant modules
1677   * @param - $module - Name of the module
1678   * @param - $packagepath - Complete path to the zip file of the Module
1679   */
1680  function updateVtlibModule($module, $packagepath) {
1681      global $log, $_installOrUpdateVtlibModule;
1682      if(!file_exists($packagepath)) return;
1683  
1684      if (isset($_installOrUpdateVtlibModule[$module.$packagepath])) return;
1685      $_installOrUpdateVtlibModule[$module.$packagepath] = 'update';
1686  
1687      require_once ('vtlib/Vtiger/Package.php');
1688      require_once ('vtlib/Vtiger/Module.php');
1689      $Vtiger_Utils_Log = defined('INSTALLATION_MODE_DEBUG')? INSTALLATION_MODE_DEBUG : true;
1690      $package = new Vtiger_Package();
1691  
1692      if($package->isLanguageType($packagepath)) {
1693          require_once ('vtlib/Vtiger/Language.php');
1694          $languagePack = new Vtiger_Language();
1695          $languagePack->update(null, $packagepath, true);
1696          return;
1697      }
1698  
1699      if($module == null) {
1700          $log->fatal("Module name is invalid");
1701      } else {
1702          $moduleInstance = Vtiger_Module::getInstance($module);
1703          if($moduleInstance || $package->isModuleBundle($packagepath)) {
1704              $log->debug("$module - Module instance found - Update starts here");
1705              $package->update($moduleInstance, $packagepath);
1706          } else {
1707              $log->fatal("$module doesn't exists!");
1708          }
1709      }
1710  }
1711  
1712  /**
1713   * this function checks if a given column exists in a given table or not
1714   * @param string $columnName - the columnname
1715   * @param string $tableName - the tablename
1716   * @return boolean $status - true if column exists; false otherwise
1717   */
1718  function columnExists($columnName, $tableName){
1719      global $adb;
1720      $columnNames = array();
1721      $columnNames = $adb->getColumnNames($tableName);
1722  
1723      if(in_array($columnName, $columnNames)){
1724          return true;
1725      }else{
1726          return false;
1727      }
1728  }
1729  
1730  /* To get modules list for which work flow and field formulas is permitted*/
1731  function com_vtGetModules($adb) {
1732      $sql="select distinct vtiger_field.tabid, name
1733          from vtiger_field
1734          inner join vtiger_tab
1735              on vtiger_field.tabid=vtiger_tab.tabid
1736          where vtiger_field.tabid not in(9,10,16,15,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1";
1737      $it = new SqlResultIterator($adb, $adb->query($sql));
1738      $modules = array();
1739      foreach($it as $row) {
1740          if(isPermitted($row->name,'index') == "yes") {
1741              $modules[$row->name] = getTranslatedString($row->name);
1742          }
1743      }
1744      return $modules;
1745          }
1746  
1747  /**
1748   * Function to check if a given record exists (not deleted)
1749   * @param integer $recordId - record id
1750   */
1751  function isRecordExists($recordId) {
1752      global $adb;
1753      $query = "SELECT crmid FROM vtiger_crmentity where crmid=? AND deleted=0";
1754      $result = $adb->pquery($query, array($recordId));
1755      if ($adb->num_rows($result)) {
1756          return true;
1757      }
1758      return false;
1759  }
1760  
1761  /** Function to set date values compatible to database (YY_MM_DD)
1762    * @param $value -- value :: Type string
1763    * @returns $insert_date -- insert_date :: Type string
1764    */
1765  function getValidDBInsertDateValue($value) {
1766      global $log;
1767      $log->debug("Entering getValidDBInsertDateValue(".$value.") method ...");
1768      $value = trim($value);
1769      $delim = array('/','.');
1770      foreach ($delim as $delimiter){
1771          $x = strpos($value, $delimiter);
1772          if($x === false) continue;
1773          else{
1774              $value=str_replace($delimiter, '-', $value);
1775              break;
1776          }
1777      }
1778      list($y,$m,$d) = explode('-',$value);
1779      if(strlen($y) == 1) $y = '0'.$y;
1780      if(strlen($m) == 1) $m = '0'.$m;
1781      if(strlen($d) == 1) $d = '0'.$d;
1782      $value = implode('-', array($y,$m,$d));
1783  
1784      if(strlen($y)<4){
1785          $insert_date = DateTimeField::convertToDBFormat($value);
1786      } else {
1787          $insert_date = $value;
1788      }
1789  
1790      if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2}$/", $insert_date) == 0) {
1791          return '';
1792      }
1793  
1794      $log->debug("Exiting getValidDBInsertDateValue method ...");
1795      return $insert_date;
1796          }
1797  
1798  function getValidDBInsertDateTimeValue($value) {
1799      $value = trim($value);
1800      $valueList = explode(' ',$value);
1801      if(count($valueList) == 2) {
1802          $dbDateValue = getValidDBInsertDateValue($valueList[0]);
1803          $dbTimeValue = $valueList[1];
1804          if(!empty($dbTimeValue) && strpos($dbTimeValue, ':') === false) {
1805              $dbTimeValue = $dbTimeValue.':';
1806          }
1807          $timeValueLength = strlen($dbTimeValue);
1808          if(!empty($dbTimeValue) &&  strrpos($dbTimeValue, ':') == ($timeValueLength-1)) {
1809              $dbTimeValue = $dbTimeValue.'00';
1810          }
1811          try {
1812              $dateTime = new DateTimeField($dbDateValue.' '.$dbTimeValue);
1813              return $dateTime->getDBInsertDateTimeValue();
1814          } catch (Exception $ex) {
1815              return '';
1816          }
1817      } elseif(count($valueList == 1)) {
1818          return getValidDBInsertDateValue($value);
1819      }
1820  }
1821  
1822  /** Function to set the PHP memory limit to the specified value, if the memory limit set in the php.ini is less than the specified value
1823   * @param $newvalue -- Required Memory Limit
1824   */
1825  function _phpset_memorylimit_MB($newvalue) {
1826      $current = @ini_get('memory_limit');
1827      if(preg_match("/(.*)M/", $current, $matches)) {
1828          // Check if current value is less then new value
1829          if($matches[1] < $newvalue) {
1830              @ini_set('memory_limit', "{$newvalue}M");
1831      }
1832      }
1833      }
1834  
1835  /** Function to sanitize the upload file name when the file name is detected to have bad extensions
1836   * @param String -- $fileName - File name to be sanitized
1837   * @return String - Sanitized file name
1838   */
1839  function sanitizeUploadFileName($fileName, $badFileExtensions) {
1840  
1841      $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename
1842      $fileName = rtrim($fileName, '\\/<>?*:"<>|');
1843  
1844      $fileNameParts = explode(".", $fileName);
1845      $countOfFileNameParts = count($fileNameParts);
1846      $badExtensionFound = false;
1847  
1848      for ($i=0;$i<$countOfFileNameParts;++$i) {
1849          $partOfFileName = $fileNameParts[$i];
1850          if(in_array(strtolower($partOfFileName), $badFileExtensions)) {
1851              $badExtensionFound = true;
1852              $fileNameParts[$i] = $partOfFileName . 'file';
1853      }
1854      }
1855  
1856      $newFileName = implode(".", $fileNameParts);
1857  
1858      if ($badExtensionFound) {
1859          $newFileName .= ".txt";
1860          }
1861      return $newFileName;
1862          }
1863  
1864  /** Function to get the tab meta information for a given id
1865    * @param $tabId -- tab id :: Type integer
1866    * @returns $tabInfo -- array of preference name to preference value :: Type array
1867    */
1868  function getTabInfo($tabId) {
1869      global $adb;
1870  
1871      $tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM vtiger_tab_info WHERE tabid=?', array($tabId));
1872      $tabInfo = array();
1873      for($i=0; $i<$adb->num_rows($tabInfoResult); ++$i) {
1874          $prefName = $adb->query_result($tabInfoResult, $i, 'prefname');
1875          $prefValue = $adb->query_result($tabInfoResult, $i, 'prefvalue');
1876          $tabInfo[$prefName] = $prefValue;
1877  }
1878  }
1879  
1880  /** Function to return block name
1881   * @param Integer -- $blockid
1882   * @return String - Block Name
1883   */
1884  function getBlockName($blockid) {
1885      global $adb;
1886  
1887      $blockname = VTCacheUtils::lookupBlockLabelWithId($blockid);
1888  
1889      if(!empty($blockid) && $blockname === false){
1890          $block_res = $adb->pquery('SELECT blocklabel FROM vtiger_blocks WHERE blockid = ?',array($blockid));
1891          if($adb->num_rows($block_res)){
1892              $blockname = $adb->query_result($block_res,0,'blocklabel');
1893          } else {
1894              $blockname = '';
1895          }
1896          VTCacheUtils::updateBlockLabelWithId($blockname, $blockid);
1897      }
1898      return $blockname;
1899  }
1900  
1901  function validateAlphaNumericInput($string){
1902      preg_match('/^[\w _\-]+$/', $string, $matches);
1903      if(count($matches) == 0) {
1904          return false;
1905      }
1906      return true;
1907  }
1908  
1909  function validateServerName($string){
1910      preg_match('/^[\w\-\.\\/:]+$/', $string, $matches);
1911      if(count($matches) == 0) {
1912          return false;
1913          }
1914      return true;
1915      }
1916  
1917  function validateEmailId($string){
1918      preg_match('/^[a-zA-Z0-9]+([\_\-\.]*[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-]?[a-zA-Z0-9]+)*\.+([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)*$/', $string, $matches);
1919      if(count($matches) == 0) {
1920          return false;
1921      }
1922      return true;
1923  }
1924  
1925  /**
1926  * Function to get the approximate difference between two date time values as string
1927  */
1928  function dateDiffAsString($d1, $d2) {
1929      global $currentModule;
1930  
1931      $dateDiff = dateDiff($d1, $d2);
1932  
1933      $years = $dateDiff['years'];
1934      $months = $dateDiff['months'];
1935      $days = $dateDiff['days'];
1936      $hours = $dateDiff['hours'];
1937      $minutes = $dateDiff['minutes'];
1938      $seconds = $dateDiff['seconds'];
1939  
1940      if($years > 0) {
1941          $diffString = "$years ".getTranslatedString('LBL_YEARS',$currentModule);
1942      } elseif($months > 0) {
1943          $diffString = "$months ".getTranslatedString('LBL_MONTHS',$currentModule);
1944      } elseif($days > 0) {
1945          $diffString = "$days ".getTranslatedString('LBL_DAYS',$currentModule);
1946      } elseif($hours > 0) {
1947          $diffString = "$hours ".getTranslatedString('LBL_HOURS',$currentModule);
1948      } elseif($minutes > 0) {
1949          $diffString = "$minutes ".getTranslatedString('LBL_MINUTES',$currentModule);
1950                  } else {
1951          $diffString = "$seconds ".getTranslatedString('LBL_SECONDS',$currentModule);
1952                  }
1953      return $diffString;
1954              }
1955  
1956  function getMinimumCronFrequency() {
1957      global $MINIMUM_CRON_FREQUENCY;
1958  
1959      if(!empty($MINIMUM_CRON_FREQUENCY)) {
1960          return $MINIMUM_CRON_FREQUENCY;
1961          }
1962      return 15;
1963  }
1964  
1965  //Function returns Email related Modules
1966  function getEmailRelatedModules() {
1967      global $current_user;
1968      $handler = vtws_getModuleHandlerFromName('Emails',$current_user);
1969      $meta = $handler->getMeta();
1970      $moduleFields = $meta->getModuleFields();
1971      $fieldModel = $moduleFields['parent_id'];
1972      $relatedModules = $fieldModel->getReferenceList();
1973      foreach($relatedModules as $key=>$value) {
1974          if($value == 'Users') {
1975              unset($relatedModules[$key]);
1976      }
1977  }
1978      return $relatedModules;
1979  }
1980  
1981  //Get the User selected NumberOfCurrencyDecimals
1982  function getCurrencyDecimalPlaces() {
1983      global $current_user;
1984      $currency_decimal_places = $current_user->no_of_currency_decimals;
1985      if(isset($currency_decimal_places)) {
1986          return $currency_decimal_places;
1987          } else {
1988          return 2;
1989              }
1990          }
1991  
1992  function getInventoryModules() {
1993      $inventoryModules = array('Invoice','Quotes','PurchaseOrder','SalesOrder');
1994      return $inventoryModules;
1995  }
1996  
1997  /* Function to only initialize the update of Vtlib Compliant modules
1998   * @param - $module - Name of the module
1999   * @param - $packagepath - Complete path to the zip file of the Module
2000   */
2001  function initUpdateVtlibModule($module, $packagepath) {
2002      global $log;
2003      require_once ('vtlib/Vtiger/Package.php');
2004      require_once ('vtlib/Vtiger/Module.php');
2005      $Vtiger_Utils_Log = true;
2006      $package = new Vtiger_Package();
2007  
2008      if($module == null) {
2009          $log->fatal("Module name is invalid");
2010      } else {
2011          $moduleInstance = Vtiger_Module::getInstance($module);
2012          if($moduleInstance) {
2013              $log->debug("$module - Module instance found - Init Update starts here");
2014              $package->initUpdate($moduleInstance, $packagepath, true);
2015          } else {
2016              $log->fatal("$module doesn't exists!");
2017          }
2018      }
2019  }
2020  
2021  
2022  /**
2023   * Function to get the list of Contacts related to an activity
2024   * @param Integer $activityId
2025   * @return Array $contactsList - List of Contact ids, mapped to Contact Names
2026   */
2027  function getActivityRelatedContacts($activityId) {
2028      $adb = PearDatabase::getInstance();
2029  
2030      $query = 'SELECT * FROM vtiger_cntactivityrel WHERE activityid=?';
2031      $result = $adb->pquery($query, array($activityId));
2032  
2033      $noOfContacts = $adb->num_rows($result);
2034      $contactsList = array();
2035      for ($i = 0; $i < $noOfContacts; ++$i) {
2036          $contactId = $adb->query_result($result, $i, 'contactid');
2037          $displayValueArray = getEntityName('Contacts', $contactId);
2038          if (!empty($displayValueArray)) {
2039              foreach ($displayValueArray as $key => $field_value) {
2040                  $contact_name = $field_value;
2041              }
2042          } else {
2043              $contact_name='';
2044          }
2045          $contactsList[$contactId] = $contact_name;
2046      }
2047      return $contactsList;
2048  }
2049  
2050  function isLeadConverted($leadId) {
2051      $adb = PearDatabase::getInstance();
2052  
2053      $query = 'SELECT converted FROM vtiger_leaddetails WHERE converted = 1 AND leadid=?';
2054      $params = array($leadId);
2055  
2056      $result = $adb->pquery($query, $params);
2057  
2058      if($result && $adb->num_rows($result) > 0) {
2059          return true;
2060      }
2061      return false;
2062  }
2063  
2064  function getSelectedRecords($input,$module,$idstring,$excludedRecords) {
2065      global $current_user, $adb;
2066  
2067      if($idstring == 'relatedListSelectAll') {
2068  
2069          $recordid = vtlib_purify($input['recordid']);
2070          if($module == 'Accounts') {
2071              $result = getCampaignAccountIds($recordid);
2072          }
2073          if($module == 'Contacts') {
2074              $result = getCampaignContactIds($recordid);
2075          }
2076          if($module == 'Leads') {
2077              $result = getCampaignLeadIds($recordid);
2078          }
2079          $storearray = array();
2080          for ($i = 0; $i < $adb->num_rows($result); $i++) {
2081              $storearray[] = $adb->query_result($result, $i, 'id');
2082          }
2083  
2084          $excludedRecords=explode(';',$excludedRecords);
2085          $storearray=array_diff($storearray,$excludedRecords);
2086  
2087      } else if($module == 'Documents') {
2088  
2089          if($input['selectallmode']=='true') {
2090              $result = getSelectAllQuery($input,$module);
2091              $storearray = array();
2092              $focus = CRMEntity::getInstance($module);
2093  
2094              for ($i = 0; $i < $adb->num_rows($result); $i++) {
2095                  $storearray[] = $adb->query_result($result, $i, $focus->table_index);
2096              }
2097  
2098              $excludedRecords = explode(';',$excludedRecords);
2099              $storearray = array_diff($storearray,$excludedRecords);
2100              if($idstring != 'all') {
2101                  $storearray = array_merge($storearray,explode(';',$idstring));
2102              }
2103              $storearray = array_unique($storearray);
2104  
2105          } else {
2106              $storearray = explode(";",$idstring);
2107          }
2108  
2109      } elseif($idstring == 'all') {
2110  
2111          $result = getSelectAllQuery($input,$module);
2112          $storearray = array();
2113          $focus = CRMEntity::getInstance($module);
2114  
2115          for ($i = 0; $i < $adb->num_rows($result); $i++) {
2116              $storearray[] = $adb->query_result($result, $i, $focus->table_index);
2117          }
2118  
2119          $excludedRecords = explode(';',$excludedRecords);
2120          $storearray = array_diff($storearray,$excludedRecords);
2121  
2122      } else {
2123          $storearray = explode(";",$idstring);
2124      }
2125  
2126      return $storearray;
2127  }
2128  
2129  function getSelectAllQuery($input,$module) {
2130      global $adb,$current_user;
2131  
2132      $viewid = vtlib_purify($input['viewname']);
2133  
2134      if($module == "Calendar") {
2135          $listquery = getListQuery($module);
2136          $oCustomView = new CustomView($module);
2137          $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,$module);
2138          $where = '';
2139          if($input['query'] == 'true') {
2140              list($where, $ustring) = split("#@@#",getWhereCondition($module, $input));
2141              if(isset($where) && $where != '') {
2142                  $query .= " AND " .$where;
2143              }
2144          }
2145      } else {
2146          $queryGenerator = new QueryGenerator($module, $current_user);
2147          $queryGenerator->initForCustomViewById($viewid);
2148  
2149          if($input['query'] == 'true') {
2150              $queryGenerator->addUserSearchConditions($input);
2151          }
2152  
2153          $queryGenerator->setFields(array('id'));
2154          $query = $queryGenerator->getQuery();
2155  
2156          if($module == 'Documents') {
2157              $folderid = vtlib_purify($input['folderidstring']);
2158              $folderid = str_replace(';', ',', $folderid);
2159              $query .= " AND vtiger_notes.folderid in (".$folderid.")";
2160          }
2161      }
2162  
2163      $result = $adb->pquery($query, array());
2164      return $result;
2165  }
2166  
2167  function getCampaignAccountIds($id) {
2168      global $adb;
2169      $sql="SELECT vtiger_account.accountid as id FROM vtiger_account
2170          INNER JOIN vtiger_campaignaccountrel ON vtiger_campaignaccountrel.accountid = vtiger_account.accountid
2171          LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid
2172          WHERE vtiger_campaignaccountrel.campaignid = ? AND vtiger_crmentity.deleted=0";
2173      $result = $adb->pquery($sql, array($id));
2174      return $result;
2175  }
2176  
2177  function getCampaignContactIds($id) {
2178      global $adb;
2179      $sql="SELECT vtiger_contactdetails.contactid as id FROM vtiger_contactdetails
2180          INNER JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid
2181          LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid
2182          WHERE vtiger_campaigncontrel.campaignid = ? AND vtiger_crmentity.deleted=0";
2183      $result = $adb->pquery($sql, array($id));
2184      return $result;
2185  }
2186  
2187  function getCampaignLeadIds($id) {
2188      global $adb;
2189      $sql="SELECT vtiger_leaddetails.leadid as id FROM vtiger_leaddetails
2190          INNER JOIN vtiger_campaignleadrel ON vtiger_campaignleadrel.leadid = vtiger_leaddetails.leadid
2191          LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid
2192          WHERE vtiger_campaignleadrel.campaignid = ? AND vtiger_crmentity.deleted=0";
2193      $result = $adb->pquery($sql, array($id));
2194      return $result;
2195  }
2196  
2197  /** Function to get the difference between 2 datetime strings or millisecond values */
2198  function dateDiff($d1, $d2){
2199      $d1 = (is_string($d1) ? strtotime($d1) : $d1);
2200      $d2 = (is_string($d2) ? strtotime($d2) : $d2);
2201  
2202      $diffSecs = abs($d1 - $d2);
2203      $baseYear = min(date("Y", $d1), date("Y", $d2));
2204      $diff = mktime(0, 0, $diffSecs, 1, 1, $baseYear);
2205      return array(
2206          "years" => date("Y", $diff) - $baseYear,
2207          "months_total" => (date("Y", $diff) - $baseYear) * 12 + date("n", $diff) - 1,
2208          "months" => date("n", $diff) - 1,
2209          "days_total" => floor($diffSecs / (3600 * 24)),
2210          "days" => date("j", $diff) - 1,
2211          "hours_total" => floor($diffSecs / 3600),
2212          "hours" => date("G", $diff),
2213          "minutes_total" => floor($diffSecs / 60),
2214          "minutes" => (int) date("i", $diff),
2215          "seconds_total" => $diffSecs,
2216          "seconds" => (int) date("s", $diff)
2217      );
2218  }
2219  
2220  function getExportRecordIds($moduleName, $viewid, $input) {
2221      global $adb, $current_user, $list_max_entries_per_page;
2222  
2223      $idstring = vtlib_purify($input['idstring']);
2224      $export_data = vtlib_purify($input['export_data']);
2225  
2226      if (in_array($moduleName, getInventoryModules()) && $export_data == 'currentpage') {
2227          $queryGenerator = new QueryGenerator($moduleName, $current_user);
2228          $queryGenerator->initForCustomViewById($viewid);
2229  
2230          if($input['query'] == 'true') {
2231              $queryGenerator->addUserSearchConditions($input);
2232          }
2233  
2234          $queryGenerator->setFields(array('id'));
2235          $query = $queryGenerator->getQuery();
2236          $current_page = ListViewSession::getCurrentPage($moduleName,$viewid);
2237          $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page;
2238          if ($limit_start_rec < 0) $limit_start_rec = 0;
2239          $query .= ' LIMIT '.$limit_start_rec.','.$list_max_entries_per_page;
2240  
2241          $result = $adb->pquery($query, array());
2242          $idstring = array();
2243          $focus = CRMEntity::getInstance($moduleName);
2244          for ($i = 0; $i < $adb->num_rows($result); $i++) {
2245              $idstring[] = $adb->query_result($result, $i, $focus->table_index);
2246          }
2247          $idstring = implode(';',$idstring);
2248          $export_data = 'selecteddata';
2249      }
2250      return $idstring. '#@@#' .$export_data;
2251  }
2252  
2253  /**
2254   * Function to get combinations of string from Array
2255   * @param <Array> $array
2256   * @param <String> $tempString
2257   * @return <Array>
2258   */
2259  function getCombinations($array, $tempString = '') {
2260      for ($i=0; $i<count($array); $i++) {
2261          $splicedArray = $array;
2262          $element = array_splice($splicedArray, $i, 1);// removes and returns the i'th element
2263          if (count($splicedArray) > 0) {
2264               if(!is_array($result)) {
2265                   $result = array();
2266               }
2267               $result = array_merge($result, getCombinations($splicedArray, $tempString. ' |##| ' .$element[0]));
2268          } else {
2269              return array($tempString. ' |##| ' . $element[0]);
2270          }
2271      }
2272      return $result;
2273  }
2274  
2275  function getCompanyDetails() {
2276      global $adb;
2277      
2278      $sql="select * from vtiger_organizationdetails";
2279      $result = $adb->pquery($sql, array());
2280      
2281      $companyDetails = array();
2282      $companyDetails['companyname'] = $adb->query_result($result,0,'organizationname');
2283      $companyDetails['website'] = $adb->query_result($result,0,'website');
2284      $companyDetails['address'] = $adb->query_result($result,0,'address');
2285      $companyDetails['city'] = $adb->query_result($result,0,'city');
2286      $companyDetails['state'] = $adb->query_result($result,0,'state');
2287      $companyDetails['country'] = $adb->query_result($result,0,'country');
2288      $companyDetails['phone'] = $adb->query_result($result,0,'phone');
2289      $companyDetails['fax'] = $adb->query_result($result,0,'fax');
2290      $companyDetails['logoname'] = $adb->query_result($result,0,'logoname');
2291      
2292      return $companyDetails;
2293  }
2294  
2295  /** call back function to change the array values in to lower case */
2296  function lower_array(&$string){
2297          $string = strtolower(trim($string));
2298  }
2299  ?>


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