[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/include/Webservices/ -> Utils.php (source)

   1  <?php
   2  /*+***********************************************************************************
   3   * The contents of this file are subject to the vtiger CRM Public License Version 1.0
   4   * ("License"); You may not use this file except in compliance with the License
   5   * The Original Code is:  vtiger CRM Open Source
   6   * The Initial Developer of the Original Code is vtiger.
   7   * Portions created by vtiger are Copyright (C) vtiger.
   8   * All Rights Reserved.
   9   *************************************************************************************/
  10  
  11  require_once ('include/database/PearDatabase.php');
  12  require_once ("modules/Users/Users.php");
  13  require_once  'include/Webservices/WebserviceField.php';
  14  require_once  'include/Webservices/EntityMeta.php';
  15  require_once  'include/Webservices/VtigerWebserviceObject.php';
  16  require_once ("include/Webservices/VtigerCRMObject.php");
  17  require_once ("include/Webservices/VtigerCRMObjectMeta.php");
  18  require_once ("include/Webservices/DataTransform.php");
  19  require_once ("include/Webservices/WebServiceError.php");
  20  require_once  'include/utils/utils.php';
  21  require_once  'include/utils/UserInfoUtil.php';
  22  require_once  'include/Webservices/ModuleTypes.php';
  23  require_once  'include/utils/VtlibUtils.php';
  24  require_once  'include/Webservices/WebserviceEntityOperation.php';
  25  require_once  'include/Webservices/PreserveGlobal.php';
  26  
  27  /* Function to return all the users in the groups that this user is part of.
  28   * @param $id - id of the user
  29   * returns Array:UserIds userid of all the users in the groups that this user is part of.
  30   */
  31  function vtws_getUsersInTheSameGroup($id){
  32      require_once ('include/utils/GetGroupUsers.php');
  33      require_once ('include/utils/GetUserGroups.php');
  34  
  35      $groupUsers = new GetGroupUsers();
  36      $userGroups = new GetUserGroups();
  37      $allUsers = Array();
  38      $userGroups->getAllUserGroups($id);
  39      $groups = $userGroups->user_groups;
  40  
  41      foreach ($groups as $group) {
  42          $groupUsers->getAllUsersInGroup($group);
  43          $usersInGroup = $groupUsers->group_users;
  44          foreach ($usersInGroup as $user) {
  45          if($user != $id){
  46                  $allUsers[$user] = getUserFullName($user);
  47              }
  48          }
  49      }
  50      return $allUsers;
  51  }
  52  
  53  function vtws_generateRandomAccessKey($length=10){
  54      $source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  55      $accesskey = "";
  56      $maxIndex = strlen($source);
  57      for($i=0;$i<$length;++$i){
  58          $accesskey = $accesskey.substr($source,rand(null,$maxIndex),1);
  59      }
  60      return $accesskey;
  61  }
  62  
  63  /**
  64   * get current vtiger version from the database.
  65   */
  66  function vtws_getVtigerVersion(){
  67      global $adb;
  68      $query = 'select * from vtiger_version';
  69      $result = $adb->pquery($query, array());
  70      $version = '';
  71      while($row = $adb->fetch_array($result))
  72      {
  73          $version = $row['current_version'];
  74      }
  75      return $version;
  76  }
  77  
  78  function vtws_getUserAccessibleGroups($moduleId, $user){
  79      global $adb;
  80      require('user_privileges/user_privileges_'.$user->id.'.php');
  81      require('user_privileges/sharing_privileges_'.$user->id.'.php');
  82      $tabName = getTabname($moduleId);
  83      if($is_admin==false && $profileGlobalPermission[2] == 1 &&
  84              ($defaultOrgSharingPermission[$moduleId] == 3 or $defaultOrgSharingPermission[$moduleId] == 0)){
  85          $result=get_current_user_access_groups($tabName);
  86      }else{
  87          $result = get_group_options();
  88      }
  89  
  90      $groups = array();
  91      if($result != null && $result != '' && is_object($result)){
  92          $rowCount = $adb->num_rows($result);
  93          for ($i = 0; $i < $rowCount; $i++) {
  94              $nameArray = $adb->query_result_rowdata($result,$i);
  95              $groupId=$nameArray["groupid"];
  96              $groupName=$nameArray["groupname"];
  97              $groups[] = array('id'=>$groupId,'name'=>$groupName);
  98          }
  99      }
 100      return $groups;
 101  }
 102  
 103  function vtws_getWebserviceGroupFromGroups($groups){
 104      global $adb;
 105      $webserviceObject = VtigerWebserviceObject::fromName($adb,'Groups');
 106      foreach($groups as $index=>$group){
 107          $groups[$index]['id'] = vtws_getId($webserviceObject->getEntityId(),$group['id']);
 108      }
 109      return $groups;
 110  }
 111  
 112  function vtws_getUserWebservicesGroups($tabId,$user){
 113      $groups = vtws_getUserAccessibleGroups($tabId,$user);
 114      return vtws_getWebserviceGroupFromGroups($groups);
 115  }
 116  
 117  function vtws_getIdComponents($elementid){
 118      return explode("x",$elementid);
 119  }
 120  
 121  function vtws_getId($objId, $elemId){
 122      return $objId."x".$elemId;
 123  }
 124  
 125  function getEmailFieldId($meta, $entityId){
 126      global $adb;
 127      //no email field accessible in the module. since its only association pick up the field any way.
 128      $query="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=?
 129          and uitype=13 and presence in (0,2)";
 130      $result = $adb->pquery($query, array($meta->getTabId()));
 131  
 132      //pick up the first field.
 133      $fieldId = $adb->query_result($result,0,'fieldid');
 134      return $fieldId;
 135  }
 136  
 137  function vtws_getParameter($parameterArray, $paramName,$default=null){
 138  
 139      if (!get_magic_quotes_gpc()) {
 140          if(is_array($parameterArray[$paramName])) {
 141              $param = array_map('addslashes', $parameterArray[$paramName]);
 142          } else {
 143              $param = addslashes($parameterArray[$paramName]);
 144          }
 145      } else {
 146          $param = $parameterArray[$paramName];
 147      }
 148      if(!$param){
 149          $param = $default;
 150      }
 151      return $param;
 152  }
 153  
 154  function vtws_getEntityNameFields($moduleName){
 155  
 156      global $adb;
 157      $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?";
 158      $result = $adb->pquery($query, array($moduleName));
 159      $rowCount = $adb->num_rows($result);
 160      $nameFields = array();
 161      if($rowCount > 0){
 162          $fieldsname = $adb->query_result($result,0,'fieldname');
 163          if(!(strpos($fieldsname,',') === false)){
 164               $nameFields = explode(',',$fieldsname);
 165          }else{
 166              array_push($nameFields,$fieldsname);
 167          }
 168      }
 169      return $nameFields;
 170  }
 171  
 172  /** function to get the module List to which are crm entities.
 173   *  @return Array modules list as array
 174   */
 175  function vtws_getModuleNameList(){
 176      global $adb;
 177  
 178      $sql = "select name from vtiger_tab where isentitytype=1 and name not in ('Rss','Webmails',".
 179      "'Recyclebin','Events') order by tabsequence";
 180      $res = $adb->pquery($sql, array());
 181      $mod_array = Array();
 182      while($row = $adb->fetchByAssoc($res)){
 183          array_push($mod_array,$row['name']);
 184      }
 185      return $mod_array;
 186  }
 187  
 188  function vtws_getWebserviceEntities(){
 189      global $adb;
 190  
 191      $sql = "select name,id,ismodule from vtiger_ws_entity";
 192      $res = $adb->pquery($sql, array());
 193      $moduleArray = Array();
 194      $entityArray = Array();
 195      while($row = $adb->fetchByAssoc($res)){
 196          if($row['ismodule'] == '1'){
 197              array_push($moduleArray,$row['name']);
 198          }else{
 199              array_push($entityArray,$row['name']);
 200          }
 201      }
 202      return array('module'=>$moduleArray,'entity'=>$entityArray);
 203  }
 204  
 205  /**
 206   *
 207   * @param VtigerWebserviceObject $webserviceObject
 208   * @return CRMEntity
 209   */
 210  function vtws_getModuleInstance($webserviceObject){
 211      $moduleName = $webserviceObject->getEntityName();
 212      return CRMEntity::getInstance($moduleName);
 213  }
 214  
 215  function vtws_isRecordOwnerUser($ownerId){
 216      global $adb;
 217      
 218      static $cache = array();
 219      if (!array_key_exists($ownerId, $cache)) {
 220          $result = $adb->pquery("select first_name from vtiger_users where id = ?",array($ownerId));
 221          $rowCount = $adb->num_rows($result);
 222          $ownedByUser = ($rowCount > 0);
 223          $cache[$ownerId] = $ownedByUser;
 224      } else {
 225          $ownedByUser = $cache[$ownerId];
 226      }
 227      
 228      return $ownedByUser;
 229  }
 230  
 231  function vtws_isRecordOwnerGroup($ownerId){
 232      global $adb;
 233  
 234      static $cache = array();
 235      if (!array_key_exists($ownerId, $cache)) {
 236          $result = $adb->pquery("select groupname from vtiger_groups where groupid = ?",array($ownerId));
 237          $rowCount = $adb->num_rows($result);
 238          $ownedByGroup = ($rowCount > 0);
 239          $cache[$ownerId] = $ownedByGroup;
 240      } else {
 241          $ownedByGroup = $cache[$ownerId];
 242      }
 243      
 244      return $ownedByGroup;
 245  }
 246  
 247  function vtws_getOwnerType($ownerId){
 248      if(vtws_isRecordOwnerGroup($ownerId) == true){
 249          return 'Groups';
 250      }
 251      if(vtws_isRecordOwnerUser($ownerId) == true){
 252          return 'Users';
 253      }
 254      throw new WebServiceException(WebServiceErrorCode::$INVALIDID,"Invalid owner of the record");
 255  }
 256  
 257  function vtws_runQueryAsTransaction($query,$params,&$result){
 258      global $adb;
 259  
 260      $adb->startTransaction();
 261      $result = $adb->pquery($query,$params);
 262      $error = $adb->hasFailedTransaction();
 263      $adb->completeTransaction();
 264      return !$error;
 265  }
 266  
 267  function vtws_getCalendarEntityType($id){
 268      global $adb;
 269  
 270      $sql = "select activitytype from vtiger_activity where activityid=?";
 271      $result = $adb->pquery($sql,array($id));
 272      $seType = 'Calendar';
 273      if($result != null && isset($result)){
 274          if($adb->num_rows($result)>0){
 275              $activityType = $adb->query_result($result,0,"activitytype");
 276              if($activityType !== "Task"){
 277                  $seType = "Events";
 278              }
 279          }
 280      }
 281      return $seType;
 282  }
 283  
 284  /***
 285   * Get the webservice reference Id given the entity's id and it's type name
 286   */
 287  function vtws_getWebserviceEntityId($entityName, $id){
 288      global $adb;
 289      $webserviceObject = VtigerWebserviceObject::fromName($adb,$entityName);
 290      return $webserviceObject->getEntityId().'x'.$id;
 291  }
 292  
 293  function vtws_addDefaultModuleTypeEntity($moduleName){
 294      global $adb;
 295      $isModule = 1;
 296      $moduleHandler = array('file'=>'include/Webservices/VtigerModuleOperation.php',
 297          'class'=>'VtigerModuleOperation');
 298      return vtws_addModuleTypeWebserviceEntity($moduleName,$moduleHandler['file'],$moduleHandler['class'],$isModule);
 299  }
 300  
 301  function vtws_addModuleTypeWebserviceEntity($moduleName,$filePath,$className){
 302      global $adb;
 303      $checkres = $adb->pquery('SELECT id FROM vtiger_ws_entity WHERE name=? AND handler_path=? AND handler_class=?',
 304          array($moduleName, $filePath, $className));
 305      if($checkres && $adb->num_rows($checkres) == 0) {
 306          $isModule=1;
 307          $entityId = $adb->getUniqueID("vtiger_ws_entity");
 308          $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)',
 309              array($entityId,$moduleName,$filePath,$className,$isModule));
 310      }
 311  }
 312  
 313  function vtws_deleteWebserviceEntity($moduleName) {
 314      global $adb;
 315      $adb->pquery('DELETE FROM vtiger_ws_entity WHERE name=?',array($moduleName));
 316  }
 317  
 318  function vtws_addDefaultActorTypeEntity($actorName,$actorNameDetails,$withName = true){
 319      $actorHandler = array('file'=>'include/Webservices/VtigerActorOperation.php',
 320          'class'=>'VtigerActorOperation');
 321      if($withName == true){
 322          vtws_addActorTypeWebserviceEntityWithName($actorName,$actorHandler['file'],$actorHandler['class'],
 323              $actorNameDetails);
 324      }else{
 325          vtws_addActorTypeWebserviceEntityWithoutName($actorName,$actorHandler['file'],$actorHandler['class'],
 326              $actorNameDetails);
 327      }
 328  }
 329  
 330  function vtws_addActorTypeWebserviceEntityWithName($moduleName,$filePath,$className,$actorNameDetails){
 331      global $adb;
 332      $isModule=0;
 333      $entityId = $adb->getUniqueID("vtiger_ws_entity");
 334      $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)',
 335          array($entityId,$moduleName,$filePath,$className,$isModule));
 336      vtws_addActorTypeName($entityId,$actorNameDetails['fieldNames'],$actorNameDetails['indexField'],
 337          $actorNameDetails['tableName']);
 338  }
 339  
 340  function vtws_addActorTypeWebserviceEntityWithoutName($moduleName,$filePath,$className,$actorNameDetails){
 341      global $adb;
 342      $isModule=0;
 343      $entityId = $adb->getUniqueID("vtiger_ws_entity");
 344      $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)',
 345          array($entityId,$moduleName,$filePath,$className,$isModule));
 346  }
 347  
 348  function vtws_addActorTypeName($entityId,$fieldNames,$indexColumn,$tableName){
 349      global $adb;
 350      $adb->pquery('insert into vtiger_ws_entity_name(entity_id,name_fields,index_field,table_name) values (?,?,?,?)',
 351          array($entityId,$fieldNames,$indexColumn,$tableName));
 352  }
 353  
 354  function vtws_getName($id,$user){
 355      global $log,$adb;
 356  
 357      $webserviceObject = VtigerWebserviceObject::fromId($adb,$id);
 358      $handlerPath = $webserviceObject->getHandlerPath();
 359      $handlerClass = $webserviceObject->getHandlerClass();
 360  
 361      require_once $handlerPath;
 362  
 363      $handler = new $handlerClass($webserviceObject,$user,$adb,$log);
 364      $meta = $handler->getMeta();
 365      return $meta->getName($id);
 366  }
 367  
 368  function vtws_preserveGlobal($name,$value){
 369      return VTWS_PreserveGlobal::preserveGlobal($name,$value);
 370  }
 371  
 372  /**
 373   * Takes the details of a webservices and exposes it over http.
 374   * @param $name name of the webservice to be added with namespace.
 375   * @param $handlerFilePath file to be include which provides the handler method for the given webservice.
 376   * @param $handlerMethodName name of the function to the called when this webservice is invoked.
 377   * @param $requestType type of request that this operation should be, if in doubt give it as GET,
 378   *     general rule of thumb is that, if the operation is adding/updating data on server then it must be POST
 379   *     otherwise it should be GET.
 380   * @param $preLogin 0 if the operation need the user to authorised to access the webservice and
 381   *     1 if the operation is called before login operation hence the there will be no user authorisation happening
 382   *     for the operation.
 383   * @return Integer operationId of successful or null upon failure.
 384   */
 385  function vtws_addWebserviceOperation($name,$handlerFilePath,$handlerMethodName,$requestType,$preLogin = 0){
 386      global $adb;
 387      $createOperationQuery = "insert into vtiger_ws_operation(operationid,name,handler_path,handler_method,type,prelogin)
 388          values (?,?,?,?,?,?);";
 389      if(strtolower($requestType) != 'get' && strtolower($requestType) != 'post'){
 390          return null;
 391      }
 392      $requestType = strtoupper($requestType);
 393      if(empty($preLogin)){
 394          $preLogin = 0;
 395      }else{
 396          $preLogin = 1;
 397      }
 398      $operationId = $adb->getUniqueID("vtiger_ws_operation");
 399      $result = $adb->pquery($createOperationQuery,array($operationId,$name,$handlerFilePath,$handlerMethodName,
 400          $requestType,$preLogin));
 401      if($result !== false){
 402          return $operationId;
 403      }
 404      return null;
 405  }
 406  
 407  /**
 408   * Add a parameter to a webservice.
 409   * @param $operationId Id of the operation for which a webservice needs to be added.
 410   * @param $paramName name of the parameter used to pickup value from request(POST/GET) object.
 411   * @param $paramType type of the parameter, it can either 'string','datetime' or 'encoded'
 412   *     encoded type is used for input which will be encoded in JSON or XML(NOT SUPPORTED).
 413   * @param $sequence sequence of the parameter in the definition in the handler method.
 414   * @return Boolean true if the parameter was added successfully, false otherwise
 415   */
 416  function vtws_addWebserviceOperationParam($operationId,$paramName,$paramType,$sequence){
 417      global $adb;
 418      $supportedTypes = array('string','encoded','datetime','double','boolean');
 419      if(!is_numeric($sequence)){
 420          $sequence = 1;
 421      }if($sequence <=1){
 422          $sequence = 1;
 423      }
 424      if(!in_array(strtolower($paramType),$supportedTypes)){
 425          return false;
 426      }
 427      $createOperationParamsQuery = "insert into vtiger_ws_operation_parameters(operationid,name,type,sequence)
 428          values (?,?,?,?);";
 429      $result = $adb->pquery($createOperationParamsQuery,array($operationId,$paramName,$paramType,$sequence));
 430      return ($result !== false);
 431  }
 432  
 433  /**
 434   *
 435   * @global PearDatabase $adb
 436   * @global <type> $log
 437   * @param <type> $name
 438   * @param <type> $user
 439   * @return WebserviceEntityOperation
 440   */
 441  function vtws_getModuleHandlerFromName($name,$user){
 442      global $adb, $log;
 443      $webserviceObject = VtigerWebserviceObject::fromName($adb,$name);
 444      $handlerPath = $webserviceObject->getHandlerPath();
 445      $handlerClass = $webserviceObject->getHandlerClass();
 446  
 447      require_once $handlerPath;
 448  
 449      $handler = new $handlerClass($webserviceObject,$user,$adb,$log);
 450      return $handler;
 451  }
 452  
 453  function vtws_getModuleHandlerFromId($id,$user){
 454      global $adb, $log;
 455      $webserviceObject = VtigerWebserviceObject::fromId($adb,$id);
 456      $handlerPath = $webserviceObject->getHandlerPath();
 457      $handlerClass = $webserviceObject->getHandlerClass();
 458  
 459      require_once $handlerPath;
 460  
 461      $handler = new $handlerClass($webserviceObject,$user,$adb,$log);
 462      return $handler;
 463  }
 464  
 465  function vtws_CreateCompanyLogoFile($fieldname) {
 466      global $root_directory;
 467      $uploaddir = $root_directory ."/test/logo/";
 468      $allowedFileTypes = array("jpeg", "png", "jpg", "pjpeg" ,"x-png");
 469      $binFile = $_FILES[$fieldname]['name'];
 470      $fileType = $_FILES[$fieldname]['type'];
 471      $fileSize = $_FILES[$fieldname]['size'];
 472      $fileTypeArray = explode("/",$fileType);
 473      $fileTypeValue = strtolower($fileTypeArray[1]);
 474      if($fileTypeValue == '') {
 475          $fileTypeValue = substr($binFile,strrpos($binFile, '.')+1);
 476      }
 477      if($fileSize != 0) {
 478          if(in_array($fileTypeValue, $allowedFileTypes)) {
 479              move_uploaded_file($_FILES[$fieldname]["tmp_name"],
 480                      $uploaddir.$_FILES[$fieldname]["name"]);
 481              copy($uploaddir.$_FILES[$fieldname]["name"], $uploaddir.'application.ico');
 482              return $binFile;
 483          }
 484          throw new WebServiceException(WebServiceErrorCode::$INVALIDTOKEN,
 485              "$fieldname wrong file type given for upload");
 486      }
 487      throw new WebServiceException(WebServiceErrorCode::$INVALIDTOKEN,
 488              "$fieldname file upload failed");
 489  }
 490  
 491  function vtws_getActorEntityName ($name, $idList) {
 492      $db = PearDatabase::getInstance();
 493      if (!is_array($idList) && count($idList) == 0) {
 494          return array();
 495      }
 496      $entity = VtigerWebserviceObject::fromName($db, $name);
 497      return vtws_getActorEntityNameById($entity->getEntityId(), $idList);
 498  }
 499  
 500  function vtws_getActorEntityNameById ($entityId, $idList) {
 501      $db = PearDatabase::getInstance();
 502      if (!is_array($idList) && count($idList) == 0) {
 503          return array();
 504      }
 505      $nameList = array();
 506      $webserviceObject = VtigerWebserviceObject::fromId($db, $entityId);
 507      $query = "select * from vtiger_ws_entity_name where entity_id = ?";
 508      $result = $db->pquery($query, array($entityId));
 509      if (is_object($result)) {
 510          $rowCount = $db->num_rows($result);
 511          if ($rowCount > 0) {
 512              $nameFields = $db->query_result($result,0,'name_fields');
 513              $tableName = $db->query_result($result,0,'table_name');
 514              $indexField = $db->query_result($result,0,'index_field');
 515              if (!(strpos($nameFields,',') === false)) {
 516                  $fieldList = explode(',',$nameFields);
 517                  $nameFields = "concat(";
 518                  $nameFields = $nameFields.implode(",' ',",$fieldList);
 519                  $nameFields = $nameFields.")";
 520              }
 521  
 522              $query1 = "select $nameFields as entityname, $indexField from $tableName where ".
 523                  "$indexField in (".generateQuestionMarks($idList).")";
 524              $params1 = array($idList);
 525              $result = $db->pquery($query1, $params1);
 526              if (is_object($result)) {
 527                  $rowCount = $db->num_rows($result);
 528                  for ($i = 0; $i < $rowCount; $i++) {
 529                      $id = $db->query_result($result,$i, $indexField);
 530                      $nameList[$id] = $db->query_result($result,$i,'entityname');
 531                  }
 532                  return $nameList;
 533              }
 534          }
 535      }
 536      return array();
 537  }
 538  
 539  function vtws_isRoleBasedPicklist($name) {
 540      $db = PearDatabase::getInstance();
 541      $sql = "select picklistid from vtiger_picklist where name = ?";
 542      $result = $db->pquery($sql, array($name));
 543      return ($db->num_rows($result) > 0);
 544  }
 545  
 546  function vtws_getConvertLeadFieldMapping(){
 547      global $adb;
 548      $sql = "select * from vtiger_convertleadmapping";
 549      $result = $adb->pquery($sql,array());
 550      if($result === false){
 551          return null;
 552      }
 553      $mapping = array();
 554      $rowCount = $adb->num_rows($result);
 555      for($i=0;$i<$rowCount;++$i){
 556          $row = $adb->query_result_rowdata($result,$i);
 557          $mapping[$row['leadfid']] = array('Accounts'=>$row['accountfid'],
 558              'Potentials'=>$row['potentialfid'],'Contacts'=>$row['contactfid']);
 559      }
 560      return $mapping;
 561  }
 562  
 563  /**    Function used to get the lead related Notes and Attachments with other entities Account, Contact and Potential
 564   *    @param integer $id - leadid
 565   *    @param integer $relatedId -  related entity id (accountid / contactid)
 566   */
 567  function vtws_getRelatedNotesAttachments($id,$relatedId) {
 568      global $adb,$log;
 569  
 570      $sql = "select * from vtiger_senotesrel where crmid=?";
 571      $result = $adb->pquery($sql, array($id));
 572      if($result === false){
 573          return false;
 574      }
 575      $rowCount = $adb->num_rows($result);
 576  
 577      $sql="insert into vtiger_senotesrel(crmid,notesid) values (?,?)";
 578      for($i=0; $i<$rowCount;++$i ) {
 579          $noteId=$adb->query_result($result,$i,"notesid");
 580          $resultNew = $adb->pquery($sql, array($relatedId, $noteId));
 581          if($resultNew === false){
 582              return false;
 583          }
 584      }
 585  
 586      $sql = "select * from vtiger_seattachmentsrel where crmid=?";
 587      $result = $adb->pquery($sql, array($id));
 588      if($result === false){
 589          return false;
 590      }
 591      $rowCount = $adb->num_rows($result);
 592  
 593      $sql = "insert into vtiger_seattachmentsrel(crmid,attachmentsid) values (?,?)";
 594      for($i=0;$i<$rowCount;++$i) {
 595          $attachmentId=$adb->query_result($result,$i,"attachmentsid");
 596          $resultNew = $adb->pquery($sql, array($relatedId, $attachmentId));
 597          if($resultNew === false){
 598              return false;
 599          }
 600      }
 601      return true;
 602  }
 603  
 604  /**    Function used to save the lead related products with other entities Account, Contact and Potential
 605   *    $leadid - leadid
 606   *    $relatedid - related entity id (accountid/contactid/potentialid)
 607   *    $setype - related module(Accounts/Contacts/Potentials)
 608   */
 609  function vtws_saveLeadRelatedProducts($leadId, $relatedId, $setype) {
 610      global $adb;
 611  
 612      $result = $adb->pquery("select * from vtiger_seproductsrel where crmid=?", array($leadId));
 613      if($result === false){
 614          return false;
 615      }
 616      $rowCount = $adb->num_rows($result);
 617      for($i = 0; $i < $rowCount; ++$i) {
 618          $productId = $adb->query_result($result,$i,'productid');
 619          $resultNew = $adb->pquery("insert into vtiger_seproductsrel values(?,?,?)", array($relatedId, $productId, $setype));
 620          if($resultNew === false){
 621              return false;
 622          }
 623      }
 624      return true;
 625  }
 626  
 627  /**    Function used to save the lead related services with other entities Account, Contact and Potential
 628   *    $leadid - leadid
 629   *    $relatedid - related entity id (accountid/contactid/potentialid)
 630   *    $setype - related module(Accounts/Contacts/Potentials)
 631   */
 632  function vtws_saveLeadRelations($leadId, $relatedId, $setype) {
 633      global $adb;
 634  
 635      $result = $adb->pquery("select * from vtiger_crmentityrel where crmid=?", array($leadId));
 636      if($result === false){
 637          return false;
 638      }
 639      $rowCount = $adb->num_rows($result);
 640      for($i = 0; $i < $rowCount; ++$i) {
 641          $recordId = $adb->query_result($result,$i,'relcrmid');
 642          $recordModule = $adb->query_result($result,$i,'relmodule');
 643          $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)",
 644          array($relatedId, $setype, $recordId, $recordModule));
 645          if($resultNew === false){
 646              return false;
 647          }
 648      }
 649      $result = $adb->pquery("select * from vtiger_crmentityrel where relcrmid=?", array($leadId));
 650      if($result === false){
 651          return false;
 652      }
 653      $rowCount = $adb->num_rows($result);
 654      for($i = 0; $i < $rowCount; ++$i) {
 655          $recordId = $adb->query_result($result,$i,'crmid');
 656          $recordModule = $adb->query_result($result,$i,'module');
 657          $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)",
 658          array($relatedId, $setype, $recordId, $recordModule));
 659          if($resultNew === false){
 660              return false;
 661          }
 662      }
 663  
 664      return true;
 665  }
 666  
 667  function vtws_getFieldfromFieldId($fieldId, $fieldObjectList){
 668      foreach ($fieldObjectList as $field) {
 669          if($fieldId == $field->getFieldId()){
 670              return $field;
 671          }
 672      }
 673      return null;
 674  }
 675  
 676  /**    Function used to get the lead related activities with other entities Account and Contact
 677   *    @param integer $leadId - lead entity id
 678   *    @param integer $accountId - related account id
 679   *    @param integer $contactId -  related contact id
 680   *    @param integer $relatedId - related entity id to which the records need to be transferred
 681   */
 682  function vtws_getRelatedActivities($leadId,$accountId,$contactId,$relatedId) {
 683  
 684      if(empty($leadId) || empty($relatedId) || (empty($accountId) && empty($contactId))){
 685          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 686              "Failed to move related Activities/Emails");
 687      }
 688      global $adb;
 689      $sql = "select * from vtiger_seactivityrel where crmid=?";
 690      $result = $adb->pquery($sql, array($leadId));
 691      if($result === false){
 692          return false;
 693      }
 694      $rowCount = $adb->num_rows($result);
 695      for($i=0;$i<$rowCount;++$i) {
 696          $activityId=$adb->query_result($result,$i,"activityid");
 697  
 698          $sql ="select setype from vtiger_crmentity where crmid=?";
 699          $resultNew = $adb->pquery($sql, array($activityId));
 700          if($resultNew === false){
 701              return false;
 702          }
 703          $type=$adb->query_result($resultNew,0,"setype");
 704  
 705          $sql="delete from vtiger_seactivityrel where crmid=?";
 706          $resultNew = $adb->pquery($sql, array($leadId));
 707          if($resultNew === false){
 708              return false;
 709          }
 710          if($type != "Emails") {
 711                  if(!empty($accountId)){
 712                      $sql = "insert into vtiger_seactivityrel(crmid,activityid) values (?,?)";
 713                      $resultNew = $adb->pquery($sql, array($accountId, $activityId));
 714                      if($resultNew === false){
 715                          return false;
 716                  }
 717              }
 718                  if(!empty($contactId)){
 719                      $sql="insert into vtiger_cntactivityrel(contactid,activityid) values (?,?)";
 720                      $resultNew = $adb->pquery($sql, array($contactId, $activityId));
 721                      if($resultNew === false){
 722                          return false;
 723                  }
 724              }
 725          } else {
 726              $sql = "insert into vtiger_seactivityrel(crmid,activityid) values (?,?)";
 727              $resultNew = $adb->pquery($sql, array($relatedId, $activityId));
 728              if($resultNew === false){
 729                  return false;
 730              }
 731          }
 732      }
 733      return true;
 734  }
 735  
 736  /**
 737   * Function used to save the lead related Campaigns with Contact
 738   * @param $leadid - leadid
 739   * @param $relatedid - related entity id (contactid/accountid)
 740   * @param $setype - related module(Accounts/Contacts)
 741   * @return Boolean true on success, false otherwise.
 742   */
 743  function vtws_saveLeadRelatedCampaigns($leadId, $relatedId, $seType) {
 744      global $adb;
 745  
 746      $result = $adb->pquery("select * from vtiger_campaignleadrel where leadid=?", array($leadId));
 747      if($result === false){
 748          return false;
 749      }
 750      $rowCount = $adb->num_rows($result);
 751      for($i = 0; $i < $rowCount; ++$i) {
 752          $campaignId = $adb->query_result($result,$i,'campaignid');
 753          if($seType == 'Accounts') {
 754              $resultNew = $adb->pquery("insert into vtiger_campaignaccountrel (campaignid, accountid) values(?,?)",
 755                  array($campaignId, $relatedId));
 756          } elseif ($seType == 'Contacts') {
 757              $resultNew = $adb->pquery("insert into vtiger_campaigncontrel (campaignid, contactid) values(?,?)",
 758                  array($campaignId, $relatedId));
 759          }
 760          if($resultNew === false){
 761              return false;
 762          }
 763      }
 764      return true;
 765  }
 766  
 767  /**
 768   * Function used to transfer all the lead related records to given Entity(Contact/Account) record
 769   * @param $leadid - leadid
 770   * @param $relatedid - related entity id (contactid/accountid)
 771   * @param $setype - related module(Accounts/Contacts)
 772   */
 773  function vtws_transferLeadRelatedRecords($leadId, $relatedId, $seType) {
 774  
 775      if(empty($leadId) || empty($relatedId) || empty($seType)){
 776          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 777              "Failed to move related Records");
 778      }
 779      $status = vtws_getRelatedNotesAttachments($leadId, $relatedId);
 780      if($status === false){
 781          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 782              "Failed to move related Documents to the ".$seType);
 783      }
 784      //Retrieve the lead related products and relate them with this new account
 785      $status = vtws_saveLeadRelatedProducts($leadId, $relatedId, $seType);
 786      if($status === false){
 787          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 788              "Failed to move related Products to the ".$seType);
 789      }
 790      $status = vtws_saveLeadRelations($leadId, $relatedId, $seType);
 791      if($status === false){
 792          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 793              "Failed to move Records to the ".$seType);
 794      }
 795      $status = vtws_saveLeadRelatedCampaigns($leadId, $relatedId, $seType);
 796      if($status === false){
 797          throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED,
 798              "Failed to move Records to the ".$seType);
 799      }
 800      vtws_transferComments($leadId, $relatedId);
 801  }
 802  
 803  function vtws_transferComments($sourceRecordId, $destinationRecordId) {
 804      if(vtlib_isModuleActive('ModComments')) {
 805          CRMEntity::getInstance('ModComments'); ModComments::transferRecords($sourceRecordId, $destinationRecordId);
 806      }
 807  }
 808  
 809  function vtws_transferOwnership($ownerId, $newOwnerId, $delete=true) {
 810      $db = PearDatabase::getInstance();
 811      //Updating the smcreatorid,smownerid, modifiedby in vtiger_crmentity
 812      $sql = "UPDATE vtiger_crmentity SET smcreatorid=? WHERE smcreatorid=? AND setype<>?";
 813      $db->pquery($sql, array($newOwnerId, $ownerId,'ModComments'));
 814  
 815      $sql = "UPDATE vtiger_crmentity SET smownerid=? WHERE smownerid=? AND setype<>?";
 816      $db->pquery($sql, array($newOwnerId, $ownerId, 'ModComments'));
 817  
 818      $sql = "update vtiger_crmentity set modifiedby=? where modifiedby=?";
 819      $db->pquery($sql, array($newOwnerId, $ownerId));
 820  
 821      //deleting from vtiger_tracker
 822      if ($delete) {
 823          $sql = "delete from vtiger_tracker where user_id=?";
 824          $db->pquery($sql, array($ownerId));
 825      }
 826  
 827      //updating the vtiger_import_maps
 828      $sql ="update vtiger_import_maps set assigned_user_id=? where assigned_user_id=?";
 829      $db->pquery($sql, array($newOwnerId, $ownerId));
 830  
 831      if(Vtiger_Utils::CheckTable('vtiger_customerportal_prefs')) {
 832          $query = 'UPDATE vtiger_customerportal_prefs SET prefvalue = ? WHERE prefkey = ? AND prefvalue = ?';
 833          $params = array($newOwnerId, 'defaultassignee', $ownerId);
 834          $db->pquery($query, $params);
 835  
 836          $query = 'UPDATE vtiger_customerportal_prefs SET prefvalue = ? WHERE prefkey = ? AND prefvalue = ?';
 837          $params = array($newOwnerId, 'userid', $ownerId);
 838          $db->pquery($query, $params);
 839      }
 840  
 841      //delete from vtiger_homestuff
 842      if ($delete) {
 843          $sql = "delete from vtiger_homestuff where userid=?";
 844          $db->pquery($sql, array($ownerId));
 845      }
 846  
 847      //delete from vtiger_users to vtiger_role vtiger_table
 848      if ($delete) {
 849          $sql = "delete from vtiger_users2group where userid=?";
 850          $db->pquery($sql, array($ownerId));
 851      }
 852  
 853      $sql = "select tabid,fieldname,tablename,columnname from vtiger_field left join ".
 854      "vtiger_fieldmodulerel on vtiger_field.fieldid=vtiger_fieldmodulerel.fieldid where uitype ".
 855      "in (52,53,77,101) or (uitype=10 and relmodule='Users')";
 856      $result = $db->pquery($sql, array());
 857      $it = new SqlResultIterator($db, $result);
 858      $columnList = array();
 859      foreach ($it as $row) {
 860          $column = $row->tablename.'.'.$row->columnname;
 861          if(!in_array($column, $columnList)) {
 862              $columnList[] = $column;
 863              if($row->columnname == 'smcreatorid' || $row->columnname == 'smownerid') {
 864                  $sql = "update $row->tablename set $row->columnname=? where $row->columnname=? and setype<>?";
 865                  $db->pquery($sql, array($newOwnerId, $ownerId, 'ModComments'));
 866              } else {
 867                  $sql = "update $row->tablename set $row->columnname=? where $row->columnname=?";
 868                  $db->pquery($sql, array($newOwnerId, $ownerId));
 869              }
 870          }
 871      }
 872      
 873      //update workflow tasks Assigned User from Deleted User to Transfer User
 874      $newOwnerModel = Users_Record_Model::getInstanceById($newOwnerId, 'Users');
 875      $ownerModel = Users_Record_Model::getInstanceById($ownerId, 'Users');
 876      
 877      vtws_transferOwnershipForWorkflowTasks($ownerModel, $newOwnerModel);
 878      vtws_updateWebformsRoundrobinUsersLists($ownerId, $newOwnerId);
 879  }
 880  
 881  function vtws_updateWebformsRoundrobinUsersLists($ownerId, $newOwnerId){
 882      $db = PearDatabase::getInstance();
 883      $sql = 'SELECT id,roundrobin_userid FROM vtiger_webforms;';
 884      $result = $db->pquery($sql, array());
 885      $numOfRows = $db->num_rows($result);
 886      for($i=0;$i<$numOfRows;$i++){
 887          $rowdata = $db->query_result_rowdata($result, $i);
 888          $webformId = $rowdata['id'];
 889          $encodedUsersList = $rowdata['roundrobin_userid'];
 890          $encodedUsersList = str_replace("&quot;","\"",$encodedUsersList);
 891          $usersList = json_decode($encodedUsersList,true);
 892          if(is_array($usersList)){
 893              if(($key = array_search($ownerId, $usersList)) !== false){
 894                  if(!in_array($newOwnerId,$usersList)){
 895                        $usersList[$key] = $newOwnerId;
 896                  }
 897                  else{
 898                      unset($usersList[$key]);
 899                      $revisedUsersList = array();
 900                      $j=0;
 901                      foreach($usersList as $uid){
 902                          $revisedUsersList[$j++] = $uid;
 903                      }
 904                      $usersList = $revisedUsersList;
 905                  }
 906                  if(count($usersList) == 0){
 907                      $db->pquery('UPDATE vtiger_webforms SET roundrobin_userid = ?,roundrobin = ? where id =?',array("--None--",0,$webformId));
 908                  }
 909                  else{
 910                      $usersList = json_encode($usersList);
 911                      $db->pquery('UPDATE vtiger_webforms SET roundrobin_userid = ? where id =?',array($usersList,$webformId));
 912                  }
 913              }
 914          }
 915      }
 916  }
 917  
 918  function vtws_transferOwnershipForWorkflowTasks($ownerModel, $newOwnerModel) {
 919      $db = PearDatabase::getInstance();
 920      
 921      //update workflow tasks Assigned User from Deleted User to Transfer User
 922      $newOwnerName = $newOwnerModel->get('user_name');
 923      if(!$newOwnerName) {
 924          $newOwnerName = $newOwnerModel->getName();
 925      }
 926      $newOwnerId = $newOwnerModel->getId();
 927      
 928      $ownerName = $ownerModel->get('user_name');
 929      if(!$ownerName) {
 930          $ownerName = $ownerModel->getName();
 931      }
 932      $ownerId = $ownerModel->getId();
 933      
 934      $nameSearchValue = '"fieldname":"assigned_user_id","value":"'.$ownerName.'"';
 935      $idSearchValue = '"fieldname":"assigned_user_id","value":"'.$ownerId.'"';
 936      $fieldSearchValue = 's:16:"assigned_user_id"';
 937      $query = "SELECT task,task_id,workflow_id FROM com_vtiger_workflowtasks where task LIKE '%".$nameSearchValue."%' OR task LIKE '%".$idSearchValue.
 938              "%' OR task LIKE '%".$fieldSearchValue."%'";
 939      $result = $db->pquery($query, array());
 940      
 941      $num_rows = $db->num_rows($result);
 942      for ($i = 0; $i < $num_rows; $i++) {
 943          $row = $db->raw_query_result_rowdata($result, $i);
 944          $task = $row['task'];
 945          $taskComponents = explode(':', $task);
 946          $classNameWithDoubleQuotes = $taskComponents[2];
 947          $className = str_replace('"', '', $classNameWithDoubleQuotes);
 948          require_once ("modules/com_vtiger_workflow/VTTaskManager.inc");
 949          require_once 'modules/com_vtiger_workflow/tasks/'.$className.'.inc';
 950          $unserializeTask = unserialize($task);
 951          if(array_key_exists("field_value_mapping",$unserializeTask)) {
 952              $fieldMapping = Zend_Json::decode($unserializeTask->field_value_mapping);
 953              if (!empty($fieldMapping)) {
 954                  foreach ($fieldMapping as $key => $condition) {
 955                      if ($condition['fieldname'] == 'assigned_user_id') {
 956                          $value = $condition['value'];
 957                          if(is_numeric($value) && $value == $ownerId) {
 958                              $condition['value'] = $newOwnerId;
 959                          } else if($value == $ownerName) {
 960                              $condition['value'] = $newOwnerName;
 961                          }
 962                      }
 963                      $fieldMapping[$key] = $condition;
 964                  }
 965                  $updatedTask = Zend_Json::encode($fieldMapping);
 966                  $unserializeTask->field_value_mapping = $updatedTask;
 967                  $serializeTask = serialize($unserializeTask);
 968                  
 969                  $query = 'UPDATE com_vtiger_workflowtasks SET task=? where workflow_id=? AND task_id=?';
 970                  $db->pquery($query, array($serializeTask, $row['workflow_id'], $row['task_id']));
 971              }
 972          } else {
 973              //For VTCreateTodoTask and VTCreateEventTask
 974              if(array_key_exists('assigned_user_id', $unserializeTask)){
 975                  $value = $unserializeTask->assigned_user_id;
 976                  if($value == $ownerId) {
 977                      $unserializeTask->assigned_user_id = $newOwnerId;
 978                  }
 979                  $serializeTask = serialize($unserializeTask);
 980                  $query = 'UPDATE com_vtiger_workflowtasks SET task=? where workflow_id=? AND task_id=?';
 981                  $db->pquery($query, array($serializeTask, $row['workflow_id'], $row['task_id']));
 982              }
 983          }
 984      }
 985  }
 986  
 987  function vtws_getWebserviceTranslatedStringForLanguage($label, $currentLanguage) {
 988      static $translations = array();
 989      $currentLanguage = vtws_getWebserviceCurrentLanguage();
 990      if(empty($translations[$currentLanguage])) {
 991              if(file_exists('include/Webservices/language/'.$currentLanguage.'.lang.php')){
 992          include 'include/Webservices/language/'.$currentLanguage.'.lang.php';
 993              }
 994          $translations[$currentLanguage] = $webservice_strings;
 995      }
 996      if(isset($translations[$currentLanguage][$label])) {
 997          return $translations[$currentLanguage][$label];
 998      }
 999      return null;
1000  }
1001  
1002  function vtws_getWebserviceTranslatedString($label) {
1003      $currentLanguage = vtws_getWebserviceCurrentLanguage();
1004      $translation = vtws_getWebserviceTranslatedStringForLanguage($label, $currentLanguage);
1005      if(!empty($translation)) {
1006          return $translation;
1007      }
1008  
1009      //current language doesn't have translation, return translation in default language
1010      //if default language is english then LBL_ will not shown to the user.
1011      $defaultLanguage = vtws_getWebserviceDefaultLanguage();
1012      $translation = vtws_getWebserviceTranslatedStringForLanguage($label, $defaultLanguage);
1013      if(!empty($translation)) {
1014          return $translation;
1015      }
1016  
1017      //if default language is not en_us then do the translation in en_us to eliminate the LBL_ bit
1018      //of label.
1019      if('en_us' != $defaultLanguage) {
1020          $translation = vtws_getWebserviceTranslatedStringForLanguage($label, 'en_us');
1021          if(!empty($translation)) {
1022              return $translation;
1023          }
1024      }
1025      return $label;
1026  }
1027  
1028  function vtws_getWebserviceCurrentLanguage() {
1029      global $default_language, $current_language;
1030      if(empty($current_language)) {
1031          return $default_language;
1032      }
1033      return $current_language;
1034  }
1035  
1036  function vtws_getWebserviceDefaultLanguage() {
1037      global $default_language;
1038      return $default_language;
1039  }
1040  
1041  ?>


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