public function create($elementType, $element)
 {
     $db = PearDatabase::getInstance();
     $sql = 'select * from vtiger_organizationdetails';
     $result = $db->pquery($sql, $params);
     $rowCount = $db->num_rows($result);
     if ($rowCount > 0) {
         $id = $db->query_result($result, 0, 'organization_id');
         $meta = $this->getMeta();
         $element['id'] = vtws_getId($meta->getEntityId(), $id);
         return $this->revise($element);
     } else {
         $element = $this->handleFileUpload($element);
         return parent::create($elementType, $element);
     }
 }
Example #2
0
function vtws_extendSession()
{
    global $adb, $API_VERSION, $application_unique_key;
    if (isset($_SESSION["authenticated_user_id"]) && $_SESSION["app_unique_key"] == $application_unique_key) {
        $userId = $_SESSION["authenticated_user_id"];
        $sessionManager = new SessionManager();
        $sessionManager->set("authenticatedUserId", $userId);
        $crmObject = VtigerWebserviceObject::fromName($adb, "Users");
        $userId = vtws_getId($crmObject->getEntityId(), $userId);
        $vtigerVersion = vtws_getVtigerVersion();
        $resp = array("sessionName" => $sessionManager->getSessionId(), "userId" => $userId, "version" => $API_VERSION, "vtigerVersion" => $vtigerVersion);
        return $resp;
    } else {
        throw new WebServiceException(WebServiceErrorCode::$AUTHFAILURE, "Authencation Failed");
    }
}
 public function create($elementType, $element)
 {
     $db = PearDatabase::getInstance();
     $sql = 'SELECT * FROM vtiger_producttaxrel WHERE productid =? AND taxid=?';
     list($typeId, $productId) = vtws_getIdComponents($element['productid']);
     list($typeId, $taxId) = vtws_getIdComponents($element['taxid']);
     $params = array($productId, $taxId);
     $result = $db->pquery($sql, $params);
     $rowCount = $db->num_rows($result);
     if ($rowCount > 0) {
         $id = $db->query_result($result, 0, $this->meta->getObectIndexColumn());
         $meta = $this->getMeta();
         $element['id'] = vtws_getId($meta->getEntityId(), $id);
         return $this->update($element);
     } else {
         unset($element['id']);
         return parent::create($elementType, $element);
     }
 }
 public function create($elementType, $element)
 {
     $crmObject = new VtigerCRMObject($elementType, false);
     $element = DataTransform::sanitizeForInsert($element, $this->meta);
     $error = $crmObject->create($element);
     if (!$error) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
     }
     $id = $crmObject->getObjectId();
     // Bulk Save Mode
     if (CRMEntity::isBulkSaveMode()) {
         // Avoiding complete read, as during bulk save mode, $result['id'] is enough
         return array('id' => vtws_getId($this->meta->getEntityId(), $id));
     }
     $error = $crmObject->read($id);
     if (!$error) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
     }
     return DataTransform::filterAndSanitize($crmObject->getFields(), $this->meta);
 }
 function runOperation($params, $user)
 {
     global $API_VERSION;
     try {
         $operation = strtolower($this->operationName);
         if (!$this->preLogin) {
             $params[] = $user;
             return call_user_func_array($this->handlerMethod, $params);
         } else {
             $userDetails = call_user_func_array($this->handlerMethod, $params);
             if (is_array($userDetails)) {
                 return $userDetails;
             } else {
                 $this->sessionManager->set("authenticatedUserId", $userDetails->id);
                 global $adb;
                 $webserviceObject = VtigerWebserviceObject::fromName($adb, "Users");
                 $userId = vtws_getId($webserviceObject->getEntityId(), $userDetails->id);
                 $vtigerVersion = vtws_getVtigerVersion();
                 $resp = array("sessionName" => $this->sessionManager->getSessionId(), "userId" => $userId, "version" => $API_VERSION, "vtigerVersion" => $vtigerVersion);
                 return $resp;
             }
         }
     } catch (WebServiceException $e) {
         throw $e;
     } catch (Exception $e) {
         throw new WebServiceException(WebServiceErrorCode::$INTERNALERROR, "Unknown Error while processing request");
     }
 }
Example #6
0
function webforms_init()
{
    global $defaultUserName, $defaultUserAccessKey, $defaultOwner, $adb, $enableAppKeyValidation, $application_unique_key;
    try {
        $active = vtlib_isModuleActive('Webforms');
        if ($active === false) {
            webforms_returnError(array('code' => "WEBFORMS_DISABLED", 'message' => 'Webforms module is disabled'), 'Webforms');
        }
        if ($enableAppKeyValidation == true) {
            if ($application_unique_key !== $_REQUEST['appKey']) {
                webforms_returnError(array('code' => "WEBFORMS_INVALID_APPKEY", 'message' => 'AppKey provided is invalid'), null);
                return;
            }
        }
        $module = $_REQUEST['moduleName'];
        $challengeResult = vtws_getchallenge($defaultUserName);
        $challengeToken = $challengeResult['token'];
        $user = vtws_login($defaultUserName, md5($challengeToken . $defaultUserAccessKey));
        $describeResult = vtws_describe($module, $user);
        $fields = $describeResult['fields'];
        $assignedUser = new Users();
        $ownerId = $assignedUser->retrieve_user_id($defaultOwner);
        $userData = webforms_getUserData(vtws_getId(VtigerWebserviceObject::fromName($adb, "Users")->getEntityId(), $ownerId), $fields, $_REQUEST);
        if ($userData === null) {
            webforms_returnError(array('code' => "WEBFORMS_INVALID_DATA", 'message' => 'data provided is invalid'), $module);
            return;
        }
        if (sizeof($userData) < 1) {
            webforms_returnError(array('code' => "WEBFORMS_INVALID_DATA", 'message' => 'data provided is invalid'), $module);
            return;
        }
        $createResult = vtws_create($module, $userData, $user);
        webforms_returnSuccess($createResult, $module);
    } catch (WebServiceException $e) {
        webforms_returnError($e, $module);
    }
}
Example #7
0
 public function createRecords()
 {
     $adb = PearDatabase::getInstance();
     $moduleName = $this->module;
     $focus = CRMEntity::getInstance($moduleName);
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleObjectId = $moduleMeta->getEntityId();
     $moduleFields = $moduleMeta->getModuleFields();
     $entityData = array();
     $tableName = Import_Utils_Helper::getDbTableName($this->user);
     $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Action::$IMPORT_RECORD_NONE;
     if ($this->batchImport) {
         $configReader = new Import_Config_Model();
         $importBatchLimit = $configReader->get('importBatchLimit');
         $sql .= ' LIMIT ' . $importBatchLimit;
     }
     $result = $adb->query($sql);
     $numberOfRecords = $adb->num_rows($result);
     if ($numberOfRecords <= 0) {
         return;
     }
     $fieldMapping = $this->fieldMapping;
     $fieldColumnMapping = $moduleMeta->getFieldColumnMapping();
     for ($i = 0; $i < $numberOfRecords; ++$i) {
         $row = $adb->raw_query_result_rowdata($result, $i);
         $rowId = $row['id'];
         $entityInfo = null;
         $fieldData = array();
         foreach ($fieldMapping as $fieldName => $index) {
             $fieldData[$fieldName] = $row[$fieldName];
         }
         $mergeType = $this->mergeType;
         $createRecord = false;
         if (method_exists($focus, 'importRecord')) {
             $entityInfo = $focus->importRecord($this, $fieldData);
         } else {
             if (!empty($mergeType) && $mergeType != Import_Utils_Helper::$AUTO_MERGE_NONE) {
                 $queryGenerator = new QueryGenerator($moduleName, $this->user);
                 $customView = new CustomView($moduleName);
                 $viewId = $customView->getViewIdByName('All', $moduleName);
                 if (!empty($viewId)) {
                     $queryGenerator->initForCustomViewById($viewId);
                 } else {
                     $queryGenerator->initForDefaultCustomView();
                 }
                 $fieldsList = array('id');
                 $queryGenerator->setFields($fieldsList);
                 $mergeFields = $this->mergeFields;
                 if ($queryGenerator->getWhereFields() && $mergeFields) {
                     $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                 }
                 foreach ($mergeFields as $index => $mergeField) {
                     if ($index != 0) {
                         $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                     }
                     $comparisonValue = $fieldData[$mergeField];
                     $fieldInstance = $moduleFields[$mergeField];
                     if ($fieldInstance->getFieldDataType() == 'owner') {
                         $userId = getUserId_Ol($comparisonValue);
                         $comparisonValue = getUserFullName($userId);
                     }
                     if ($fieldInstance->getFieldDataType() == 'reference') {
                         if (strpos($comparisonValue, '::::') > 0) {
                             $referenceFileValueComponents = explode('::::', $comparisonValue);
                         } else {
                             $referenceFileValueComponents = explode(':::', $comparisonValue);
                         }
                         if (count($referenceFileValueComponents) > 1) {
                             $comparisonValue = trim($referenceFileValueComponents[1]);
                         }
                     }
                     $queryGenerator->addCondition($mergeField, $comparisonValue, 'e', '', '', '', true);
                 }
                 $query = $queryGenerator->getQuery();
                 $duplicatesResult = $adb->query($query);
                 $noOfDuplicates = $adb->num_rows($duplicatesResult);
                 if ($noOfDuplicates > 0) {
                     if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_IGNORE) {
                         $entityInfo['status'] = self::$IMPORT_RECORD_SKIPPED;
                     } elseif ($mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE || $mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS) {
                         for ($index = 0; $index < $noOfDuplicates - 1; ++$index) {
                             $duplicateRecordId = $adb->query_result($duplicatesResult, $index, $fieldColumnMapping['id']);
                             $entityId = vtws_getId($moduleObjectId, $duplicateRecordId);
                             vtws_delete($entityId, $this->user);
                         }
                         $baseRecordId = $adb->query_result($duplicatesResult, $noOfDuplicates - 1, $fieldColumnMapping['id']);
                         $baseEntityId = vtws_getId($moduleObjectId, $baseRecordId);
                         if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE) {
                             $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                             $fieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_update($fieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_UPDATED;
                         }
                         if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS) {
                             $filteredFieldData = array();
                             foreach ($fieldData as $fieldName => $fieldValue) {
                                 // empty will give false for value = 0
                                 if (!empty($fieldValue) || $fieldValue != "") {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             // Custom handling for default values & mandatory fields
                             // need to be taken care than normal import as we merge
                             // existing record values with newer values.
                             $fillDefault = false;
                             $mandatoryValueChecks = false;
                             $existingFieldValues = vtws_retrieve($baseEntityId, $this->user);
                             $defaultFieldValues = $this->getDefaultFieldValues($moduleMeta);
                             foreach ($existingFieldValues as $fieldName => $fieldValue) {
                                 if (empty($fieldValue) && empty($filteredFieldData[$fieldName]) && !empty($defaultFieldValues[$fieldName])) {
                                     $filteredFieldData[$fieldName] = $defaultFieldValues[$fieldName];
                                 }
                             }
                             $filteredFieldData = $this->transformForImport($filteredFieldData, $moduleMeta, $fillDefault, $mandatoryValueChecks);
                             $filteredFieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_revise($filteredFieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_MERGED;
                             $fieldData = $filteredFieldData;
                         }
                     } else {
                         $createRecord = true;
                     }
                 } else {
                     $createRecord = true;
                 }
             } else {
                 $createRecord = true;
             }
             if ($createRecord) {
                 $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                 if ($fieldData == null) {
                     $entityInfo = null;
                 } else {
                     try {
                         $entityInfo = vtws_create($moduleName, $fieldData, $this->user);
                     } catch (Exception $e) {
                     }
                 }
             }
         }
         if ($entityInfo == null) {
             $entityInfo = array('id' => null, 'status' => self::$IMPORT_RECORD_FAILED);
         } else {
             if ($createRecord) {
                 $entityInfo['status'] = self::$IMPORT_RECORD_CREATED;
             }
         }
         if ($createRecord || $mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS || $mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE) {
             $entityIdComponents = vtws_getIdComponents($entityInfo['id']);
             $recordId = $entityIdComponents[1];
             $entityfields = getEntityFieldNames($this->module);
             switch ($this->module) {
                 case 'HelpDesk':
                     $entityfields['fieldname'] = array('ticket_title');
                     break;
                 case 'Documents':
                     $entityfields['fieldname'] = array('notes_title');
                     break;
                 case 'Documents':
                     $entityfields['fieldname'] = array('notes_title');
                     break;
             }
             $label = '';
             if (is_array($entityfields['fieldname'])) {
                 foreach ($entityfields['fieldname'] as $field) {
                     $label .= $fieldData[$field] . " ";
                 }
             } else {
                 $label = $fieldData[$entityfields['fieldname']];
             }
             $label = trim($label);
             $adb->pquery('UPDATE vtiger_crmentity SET label=? WHERE crmid=?', array($label, $recordId));
         }
         $this->importedRecordInfo[$rowId] = $entityInfo;
         $this->updateImportStatus($rowId, $entityInfo);
     }
     if ($this->entityData) {
         $entity = new VTEventsManager($adb);
         $entity->triggerEvent('vtiger.batchevent.save', $this->entityData);
     }
     $this->entityData = null;
     $result = null;
     return true;
 }
Example #8
0
 function sanitizeOwnerFields($row, $meta, $t = null)
 {
     global $adb;
     $ownerFields = $meta->getOwnerFields();
     foreach ($ownerFields as $index => $field) {
         if (isset($row[$field]) && $row[$field] != null) {
             $ownerType = vtws_getOwnerType($row[$field]);
             $webserviceObject = VtigerWebserviceObject::fromName($adb, $ownerType);
             $row[$field] = vtws_getId($webserviceObject->getEntityId(), $row[$field]);
         }
     }
     return $row;
 }
Example #9
0
 public function process($params)
 {
     $module = $this->module;
     $recordId = $this->recordId;
     $variableList = $this->getTemplateVariableListForModule($module);
     $handler = vtws_getModuleHandlerFromName($module, $this->user);
     $meta = $handler->getMeta();
     $referenceFields = $meta->getReferenceFieldDetails();
     $fieldColumnMapping = $meta->getFieldColumnMapping();
     $columnTableMapping = $meta->getColumnTableMapping();
     if ($this->isProcessingReferenceField($params)) {
         $parentFieldColumnMapping = $meta->getFieldColumnMapping();
         $module = $params['referencedMeta']->getEntityName();
         if ($this->processedmodules[$module] || !$this->isModuleActive($module)) {
             return;
         }
         $recordId = $params['id'];
         $meta = $params['referencedMeta'];
         $referenceFields = $meta->getReferenceFieldDetails();
         $fieldColumnMapping = $meta->getFieldColumnMapping();
         $columnTableMapping = $meta->getColumnTableMapping();
         $referenceColumn = $parentFieldColumnMapping[$params['field']];
         $variableList = $this->referencedFields[$referenceColumn];
     }
     $tableList = array();
     $columnList = array();
     $allColumnList = $meta->getUserAccessibleColumns();
     $fieldList = array();
     if (count($variableList) > 0) {
         foreach ($variableList as $column) {
             if (in_array($column, $allColumnList)) {
                 $fieldList[] = array_search($column, $fieldColumnMapping);
                 $columnList[] = $column;
             }
         }
         foreach ($fieldList as $field) {
             if (!empty($columnTableMapping[$fieldColumnMapping[$field]])) {
                 $tableList[$columnTableMapping[$fieldColumnMapping[$field]]] = '';
             }
         }
         $tableList = array_keys($tableList);
         $defaultTableList = $meta->getEntityDefaultTableList();
         foreach ($defaultTableList as $defaultTable) {
             if (!in_array($defaultTable, $tableList)) {
                 $tableList[] = $defaultTable;
             }
         }
         if (count($tableList) > 0 && count($columnList) > 0) {
             $sql = 'select ' . implode(', ', $columnList) . ' from ' . $tableList[0];
             $moduleTableIndexList = $meta->getEntityTableIndexList();
             foreach ($tableList as $index => $tableName) {
                 if ($tableName != $tableList[0]) {
                     $sql .= ' INNER JOIN ' . $tableName . ' ON ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=' . $tableName . '.' . $moduleTableIndexList[$tableName];
                 }
             }
             //If module is Leads and if you are not selected any leads fields then query failure is happening.
             //By default we are checking where condition on base table.
             if ($module == 'Leads' && !in_array('vtiger_leaddetails', $tableList)) {
                 $sql .= ' INNER JOIN vtiger_leaddetails ON vtiger_leaddetails.leadid = vtiger_crmentity.crmid';
             }
             $sql .= ' WHERE';
             $deleteQuery = $meta->getEntityDeletedQuery();
             if (!empty($deleteQuery)) {
                 $sql .= ' ' . $meta->getEntityDeletedQuery() . ' AND';
             }
             $sql .= ' ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=?';
             $sqlparams = array($recordId);
             $db = PearDatabase::getInstance();
             $result = $db->pquery($sql, $sqlparams);
             $it = new SqlResultIterator($db, $result);
             //assuming there can only be one row.
             $values = array();
             foreach ($it as $row) {
                 foreach ($fieldList as $field) {
                     $values[$field] = $row->get($fieldColumnMapping[$field]);
                 }
             }
             $moduleFields = $meta->getModuleFields();
             foreach ($moduleFields as $fieldName => $webserviceField) {
                 $presence = $webserviceField->getPresence();
                 if (!in_array($presence, array(0, 2))) {
                     continue;
                 }
                 if (isset($values[$fieldName]) && $values[$fieldName] !== null) {
                     if (strcasecmp($webserviceField->getFieldDataType(), 'reference') === 0) {
                         $details = $webserviceField->getReferenceList();
                         if (count($details) == 1) {
                             $referencedObjectHandler = vtws_getModuleHandlerFromName($details[0], $this->user);
                         } else {
                             $type = getSalesEntityType($values[$fieldName]);
                             $referencedObjectHandler = vtws_getModuleHandlerFromName($type, $this->user);
                         }
                         $referencedObjectMeta = $referencedObjectHandler->getMeta();
                         if (!$this->isProcessingReferenceField($params) && !empty($values[$fieldName])) {
                             $this->process(array('parentMeta' => $meta, 'referencedMeta' => $referencedObjectMeta, 'field' => $fieldName, 'id' => $values[$fieldName]));
                         }
                         $values[$fieldName] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldName]));
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'owner') === 0) {
                         $referencedObjectHandler = vtws_getModuleHandlerFromName(vtws_getOwnerType($values[$fieldName]), $this->user);
                         $referencedObjectMeta = $referencedObjectHandler->getMeta();
                         /*
                          * operation supported for format $module-parentcolumn:childcolumn$
                          */
                         if (in_array($fieldColumnMapping[$fieldName], array_keys($this->referencedFields))) {
                             $this->process(array('parentMeta' => $meta, 'referencedMeta' => $referencedObjectMeta, 'field' => $fieldName, 'id' => $values[$fieldName], 'owner' => true));
                         }
                         $values[$fieldName] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldName]));
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'picklist') === 0) {
                         $values[$fieldName] = getTranslatedString($values[$fieldName], $module);
                     } elseif (strcasecmp($fieldName, 'salutationtype') === 0 && $webserviceField->getUIType() == '55') {
                         $values[$fieldName] = getTranslatedString($values[$fieldName], $module);
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'datetime') === 0) {
                         $values[$fieldName] = $values[$fieldName] . ' ' . DateTimeField::getDBTimeZone();
                     }
                 }
             }
             if (!$this->isProcessingReferenceField($params)) {
                 foreach ($columnList as $column) {
                     $needle = '$' . strtolower($this->module) . "-{$column}\$";
                     $this->processedDescription = str_replace($needle, $values[array_search($column, $fieldColumnMapping)], $this->processedDescription);
                 }
                 // Is process Description will send false even that module don't have reference record set
                 $this->processedDescription = preg_replace("/\\\$(?:[a-zA-Z0-9]+)-(?:[a-zA-Z0-9]+)(?:_[a-zA-Z0-9]+)?(?::[a-zA-Z0-9]+)(?:[a-zA-Z0-9]+)?(?:_[a-zA-Z0-9]+)?\\\$/", '', $this->processedDescription);
             } else {
                 foreach ($columnList as $column) {
                     $needle = '$' . strtolower($this->module) . '-' . $parentFieldColumnMapping[$params['field']] . ':' . $column . '$';
                     $this->processedDescription = str_replace($needle, $values[array_search($column, $fieldColumnMapping)], $this->processedDescription);
                 }
                 if (!$params['owner']) {
                     $this->processedmodules[$module] = true;
                 }
             }
         }
     }
     $this->processed = true;
 }
Example #10
0
    public function process()
    {
        global $site_URL;
        $imagefound = false;
        $variableList = $this->getTemplateVariableListForModule($this->module);
        $handler = vtws_getModuleHandlerFromName($this->module, $this->user);
        $meta = $handler->getMeta();
        $referenceFields = $meta->getReferenceFieldDetails();
        $fieldColumnMapping = $meta->getFieldColumnMapping();
        $columnTableMapping = $meta->getColumnTableMapping();
        $tableList = array();
        $columnList = array();
        $columnList_full = array();
        $allColumnList = $meta->getUserAccessibleColumns();
        if (count($variableList) > 0) {
            foreach ($variableList as $column) {
                if (in_array($column, $allColumnList)) {
                    $columnList[] = $column;
                    $columnList_full[] = $columnTableMapping[$column] . '.' . $column;
                }
            }
            foreach ($columnList as $column) {
                if (!empty($columnTableMapping[$column])) {
                    $tableList[$columnTableMapping[$column]] = '';
                }
            }
            $tableList = array_keys($tableList);
            $defaultTableList = $meta->getEntityDefaultTableList();
            $tableList = array_merge($tableList, $defaultTableList);
            $leadtables = array('vtiger_leadsubdetails', 'vtiger_leadaddress', 'vtiger_leadscf');
            $leadmerge = array_intersect($tableList, $leadtables);
            if (count($leadmerge) > 0 and !in_array('vtiger_leaddetails', $tableList)) {
                // we need this one because the where condition for Leads uses the converted column from the main table
                $tableList[] = 'vtiger_leaddetails';
            }
            // right now this is will be limited to module type, entities.
            // need to extend it to non-module entities when we have a reliable way of getting
            // record type from the given record id. non webservice id.
            // can extend to non-module entity without many changes as long as the reference field
            // refers to one type of entity, either module entities or non-module entities.
            if (count($tableList) > 0) {
                $sql = 'select ' . implode(', ', $columnList_full) . ' from ' . $tableList[0];
                $moduleTableIndexList = $meta->getEntityTableIndexList();
                foreach ($tableList as $index => $tableName) {
                    if ($tableName != $tableList[0]) {
                        $sql .= ' INNER JOIN ' . $tableName . ' ON ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=' . $tableName . '.' . $moduleTableIndexList[$tableName];
                    }
                }
                $sql .= ' WHERE';
                $deleteQuery = $meta->getEntityDeletedQuery();
                if (!empty($deleteQuery)) {
                    $sql .= " {$deleteQuery} AND";
                }
                $sql .= ' ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=?';
                $params = array($this->recordId);
                $db = PearDatabase::getInstance();
                $result = $db->pquery($sql, $params);
                $it = new SqlResultIterator($db, $result);
                //assuming there can only be one row.
                $values = array();
                foreach ($it as $row) {
                    foreach ($columnList as $column) {
                        $values[$column] = $row->get($column);
                    }
                }
                $moduleFields = $meta->getModuleFields();
                foreach ($moduleFields as $fieldName => $webserviceField) {
                    if (isset($values[$fieldColumnMapping[$fieldName]]) && $values[$fieldColumnMapping[$fieldName]] !== null) {
                        $fieldtype = $webserviceField->getFieldDataType();
                        if (strcasecmp($fieldtype, 'reference') === 0) {
                            $details = $webserviceField->getReferenceList();
                            if (count($details) == 1) {
                                $referencedObjectHandler = vtws_getModuleHandlerFromName($details[0], $this->user);
                            } else {
                                $type = getSalesEntityType($values[$fieldColumnMapping[$fieldName]]);
                                $referencedObjectHandler = vtws_getModuleHandlerFromName($type, $this->user);
                            }
                            $referencedObjectMeta = $referencedObjectHandler->getMeta();
                            $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                        } elseif (strcasecmp($fieldtype, 'owner') === 0) {
                            $referencedObjectHandler = vtws_getModuleHandlerFromName(vtws_getOwnerType($values[$fieldColumnMapping[$fieldName]]), $this->user);
                            $referencedObjectMeta = $referencedObjectHandler->getMeta();
                            $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                        } elseif (strcasecmp($fieldtype, 'picklist') === 0 or $fieldName == 'salutationtype') {
                            $values[$fieldColumnMapping[$fieldName]] = getTranslatedString($values[$fieldColumnMapping[$fieldName]], $this->module);
                        } elseif (strcasecmp($fieldtype, 'datetime') === 0) {
                            $values[$fieldColumnMapping[$fieldName]] = $values[$fieldColumnMapping[$fieldName]] . ' ' . DateTimeField::getDBTimeZone();
                        } elseif (strcasecmp($fieldtype, 'currency') === 0 or strcasecmp($fieldtype, 'double') === 0) {
                            $currencyField = new CurrencyField($values[$fieldColumnMapping[$fieldName]]);
                            $values[$fieldColumnMapping[$fieldName]] = $currencyField->getDisplayValue(null, true);
                        } elseif ($webserviceField->getUIType() == 69) {
                            $query = 'select vtiger_attachments.name, vtiger_attachments.type, vtiger_attachments.attachmentsid, vtiger_attachments.path
									from vtiger_attachments
									inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid
									inner join vtiger_seattachmentsrel on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid
									where (vtiger_crmentity.setype LIKE "%Image" or vtiger_crmentity.setype LIKE "%Attachment")
									  and deleted=0 and vtiger_seattachmentsrel.crmid=?';
                            $params = array($this->recordId);
                            if (!empty($values[$fieldColumnMapping[$fieldName]])) {
                                $query .= ' and vtiger_attachments.name = ?';
                                $params[] = $values[$fieldColumnMapping[$fieldName]];
                            }
                            $result_image = $db->pquery($query, $params);
                            if ($db->num_rows($result_image) > 0) {
                                $img = $db->fetch_array($result_image);
                                $fullpath = $site_URL . '/' . $img['path'] . $img['attachmentsid'] . '_' . $img['name'];
                                $values[$fieldColumnMapping[$fieldName] . '_fullpath'] = $fullpath;
                                $values[$fieldColumnMapping[$fieldName]] = $img['name'];
                                $imagefound = true;
                            }
                        }
                    }
                }
                foreach ($columnList as $column) {
                    if ($imagefound) {
                        $needle = '$' . strtolower($this->module) . "-{$column}" . '_fullpath$';
                        $this->processedDescription = str_replace($needle, $values[$column . '_fullpath'], $this->processedDescription);
                    }
                    $needle = '$' . strtolower($this->module) . "-{$column}\$";
                    $this->processedDescription = str_replace($needle, $values[$column], $this->processedDescription);
                }
            }
        }
        $this->processed = true;
    }
 public function update($element)
 {
     $ids = vtws_getIdComponents($element["id"]);
     $element = DataTransform::sanitizeForInsert($element, $this->meta);
     $element = $this->restrictFields($element);
     $columnStr = 'set ' . implode('=?,', array_keys($element)) . ' =? ';
     $query = 'update ' . $this->entityTableName . ' ' . $columnStr . 'where ' . $this->meta->getObectIndexColumn() . '=?';
     $params = array_values($element);
     array_push($params, $ids[1]);
     $result = null;
     $transactionSuccessful = vtws_runQueryAsTransaction($query, $params, $result);
     if (!$transactionSuccessful) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
     }
     return $this->retrieve(vtws_getId($ids[0], $ids[1]));
 }
Example #12
0
function vtws_sync($mtime, $elementType, $syncType, $user)
{
    global $adb, $recordString, $modifiedTimeString;
    $numRecordsLimit = 100;
    $ignoreModules = array("Users");
    $typed = true;
    $dformat = "Y-m-d H:i:s";
    $datetime = date($dformat, $mtime);
    $setypeArray = array();
    $setypeData = array();
    $setypeHandler = array();
    $setypeNoAccessArray = array();
    $output = array();
    $output["updated"] = array();
    $output["deleted"] = array();
    $applicationSync = false;
    if (is_object($syncType) && $syncType instanceof Users) {
        $user = $syncType;
    } else {
        if ($syncType == 'application') {
            $applicationSync = true;
        } else {
            if ($syncType == 'userandgroup') {
                $userAndGroupSync = true;
            }
        }
    }
    if ($applicationSync && !is_admin($user)) {
        throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Only admin users can perform application sync");
    }
    $ownerIds = array($user->id);
    // To get groupids in which this user exist
    if ($userAndGroupSync) {
        $groupresult = $adb->pquery("select groupid from vtiger_users2group where userid=?", array($user->id));
        $numOfRows = $adb->num_rows($groupresult);
        if ($numOfRows > 0) {
            for ($i = 0; $i < $numOfRows; $i++) {
                $ownerIds[count($ownerIds)] = $adb->query_result($groupresult, $i, "groupid");
            }
        }
    }
    // End
    if (!isset($elementType) || $elementType == '' || $elementType == null) {
        $typed = false;
    }
    $adb->startTransaction();
    $accessableModules = array();
    $entityModules = array();
    $modulesDetails = vtws_listtypes(null, $user);
    $moduleTypes = $modulesDetails['types'];
    $modulesInformation = $modulesDetails["information"];
    foreach ($modulesInformation as $moduleName => $entityInformation) {
        if ($entityInformation["isEntity"]) {
            $entityModules[] = $moduleName;
        }
    }
    if (!$typed) {
        $accessableModules = $entityModules;
    } else {
        if (!in_array($elementType, $entityModules)) {
            throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied");
        }
        $accessableModules[] = $elementType;
    }
    $accessableModules = array_diff($accessableModules, $ignoreModules);
    if (count($accessableModules) <= 0) {
        $output['lastModifiedTime'] = $mtime;
        $output['more'] = false;
        return $output;
    }
    if ($typed) {
        $handler = vtws_getModuleHandlerFromName($elementType, $user);
        $moduleMeta = $handler->getMeta();
        $entityDefaultBaseTables = $moduleMeta->getEntityDefaultTableList();
        //since there will be only one base table for all entities
        $baseCRMTable = $entityDefaultBaseTables[0];
        if ($elementType == "Calendar" || $elementType == "Events") {
            $baseCRMTable = getSyncQueryBaseTable($elementType);
        }
    } else {
        $baseCRMTable = " vtiger_crmentity ";
    }
    //modifiedtime - next token
    $q = "SELECT modifiedtime FROM {$baseCRMTable} WHERE  modifiedtime>? and setype IN(" . generateQuestionMarks($accessableModules) . ") ";
    $params = array($datetime);
    foreach ($accessableModules as $entityModule) {
        if ($entityModule == "Events") {
            $entityModule = "Calendar";
        }
        $params[] = $entityModule;
    }
    if (!$applicationSync) {
        $q .= ' and smownerid IN(' . generateQuestionMarks($ownerIds) . ')';
        $params = array_merge($params, $ownerIds);
    }
    $q .= " order by modifiedtime limit {$numRecordsLimit}";
    $result = $adb->pquery($q, $params);
    $modTime = array();
    for ($i = 0; $i < $adb->num_rows($result); $i++) {
        $modTime[] = $adb->query_result($result, $i, 'modifiedtime');
    }
    if (!empty($modTime)) {
        $maxModifiedTime = max($modTime);
    }
    if (!$maxModifiedTime) {
        $maxModifiedTime = $datetime;
    }
    foreach ($accessableModules as $elementType) {
        $handler = vtws_getModuleHandlerFromName($elementType, $user);
        $moduleMeta = $handler->getMeta();
        $deletedQueryCondition = $moduleMeta->getEntityDeletedQuery();
        preg_match_all("/(?:\\s+\\w+[ \t\n\r]+)?([^=]+)\\s*=([^\\s]+|'[^']+')/", $deletedQueryCondition, $deletedFieldDetails);
        $fieldNameDetails = $deletedFieldDetails[1];
        $deleteFieldValues = $deletedFieldDetails[2];
        $deleteColumnNames = array();
        foreach ($fieldNameDetails as $tableName_fieldName) {
            $fieldComp = explode(".", $tableName_fieldName);
            $deleteColumnNames[$tableName_fieldName] = $fieldComp[1];
        }
        $params = array($moduleMeta->getTabName(), $datetime, $maxModifiedTime);
        $queryGenerator = new QueryGenerator($elementType, $user);
        $fields = array();
        $moduleFields = $moduleMeta->getModuleFields();
        $moduleFieldNames = getSelectClauseFields($elementType, $moduleMeta, $user);
        $moduleFieldNames[] = 'id';
        $queryGenerator->setFields($moduleFieldNames);
        $selectClause = "SELECT " . $queryGenerator->getSelectClauseColumnSQL();
        // adding the fieldnames that are present in the delete condition to the select clause
        // since not all fields present in delete condition will be present in the fieldnames of the module
        foreach ($deleteColumnNames as $table_fieldName => $columnName) {
            if (!in_array($columnName, $moduleFieldNames)) {
                $selectClause .= ", " . $table_fieldName;
            }
        }
        if ($elementType == "Emails") {
            $fromClause = vtws_getEmailFromClause();
        } else {
            $fromClause = $queryGenerator->getFromClause();
        }
        $fromClause .= " INNER JOIN (select modifiedtime, crmid,deleted,setype FROM {$baseCRMTable} WHERE setype=? and modifiedtime >? and modifiedtime<=?";
        if (!$applicationSync) {
            $fromClause .= 'and smownerid IN(' . generateQuestionMarks($ownerIds) . ')';
            $params = array_merge($params, $ownerIds);
        }
        $fromClause .= ' ) vtiger_ws_sync ON (vtiger_crmentity.crmid = vtiger_ws_sync.crmid)';
        $q = $selectClause . " " . $fromClause;
        $result = $adb->pquery($q, $params);
        $recordDetails = array();
        $deleteRecordDetails = array();
        while ($arre = $adb->fetchByAssoc($result)) {
            $key = $arre[$moduleMeta->getIdColumn()];
            if (vtws_isRecordDeleted($arre, $deleteColumnNames, $deleteFieldValues)) {
                if (!$moduleMeta->hasAccess()) {
                    continue;
                }
                $output["deleted"][] = vtws_getId($moduleMeta->getEntityId(), $key);
            } else {
                if (!$moduleMeta->hasAccess() || !$moduleMeta->hasPermission(EntityMeta::$RETRIEVE, $key)) {
                    continue;
                }
                try {
                    $output["updated"][] = DataTransform::sanitizeDataWithColumn($arre, $moduleMeta);
                } catch (WebServiceException $e) {
                    //ignore records the user doesn't have access to.
                    continue;
                } catch (Exception $e) {
                    throw new WebServiceException(WebServiceErrorCode::$INTERNALERROR, "Unknown Error while processing request");
                }
            }
        }
    }
    $q = "SELECT crmid FROM {$baseCRMTable} WHERE modifiedtime>?  and setype IN(" . generateQuestionMarks($accessableModules) . ")";
    $params = array($maxModifiedTime);
    foreach ($accessableModules as $entityModule) {
        if ($entityModule == "Events") {
            $entityModule = "Calendar";
        }
        $params[] = $entityModule;
    }
    if (!$applicationSync) {
        $q .= 'and smownerid IN(' . generateQuestionMarks($ownerIds) . ')';
        $params = array_merge($params, $ownerIds);
    }
    $result = $adb->pquery($q, $params);
    if ($adb->num_rows($result) > 0) {
        $output['more'] = true;
    } else {
        $output['more'] = false;
    }
    if (!$maxModifiedTime) {
        $modifiedtime = $mtime;
    } else {
        $modifiedtime = vtws_getSeconds($maxModifiedTime);
    }
    if (is_string($modifiedtime)) {
        $modifiedtime = intval($modifiedtime);
    }
    $output['lastModifiedTime'] = $modifiedtime;
    $error = $adb->hasFailedTransaction();
    $adb->completeTransaction();
    if ($error) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
    }
    VTWS_PreserveGlobal::flush();
    return $output;
}
Example #13
0
function vtws_convertlead($leadId, $assignedTo, $accountName, $avoidPotential, $potential, $user)
{
    global $adb, $log;
    if (empty($assignedTo)) {
        $assignedTo = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if ((bool) $avoidPotential !== true) {
        try {
            if (empty($potential)) {
                throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Invalid lead information given for potential");
            }
        } catch (Zend_Json_Exception $e) {
            throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Potentail information given is not in valid JSON format");
        }
    }
    $currencyInfo = getCurrencySymbolandCRate($user->currency_id);
    $rate = $currencyInfo['rate'];
    if ($potential['amount'] != '') {
        $potential['amount'] = convertToDollar($potential['amount'], $rate);
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadHandler->getMeta()->retrieveMeta();
    $leadInfo = vtws_retrieve($leadId, $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($leadId);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    $customFieldMapping = vtws_getConvertLeadFieldMapping();
    //check if accountName given in request is empty then default to lead company field.
    if (empty($accountName)) {
        $accountName = $leadInfo['company'];
    }
    $sql = "select vtiger_account.accountid from vtiger_account\n\t\tleft join vtiger_crmentity on vtiger_account.accountid = vtiger_crmentity.crmid\n\t\twhere vtiger_crmentity.deleted=0 and vtiger_account.accountname = ?";
    $result = $adb->pquery($sql, array($accountName));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount != 0 && vtlib_isModuleActive('Accounts') === true) {
        $crmId = $adb->query_result($result, 0, "accountid");
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $crmId);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
        }
        //Retrieve the lead related products and relate them with this new account
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
        }
    } else {
        //don't create account if no company name is given in input and lead doest not have
        // company field populated, DONE TO RESPECT B2C model.
        if (!empty($accountName)) {
            $accountObject = VtigerWebserviceObject::fromName($adb, 'Accounts');
            $handlerPath = $accountObject->getHandlerPath();
            $handlerClass = $accountObject->getHandlerClass();
            require_once $handlerPath;
            $accountHandler = new $handlerClass($accountObject, $user, $adb, $log);
            if ($accountHandler->getMeta()->hasWriteAccess()) {
                $account = array();
                if (!empty($leadInfo["annualrevenue"])) {
                    $account['annual_revenue'] = $leadInfo["annualrevenue"];
                }
                if (!empty($leadInfo["noofemployees"])) {
                    $account['employees'] = $leadInfo["noofemployees"];
                }
                $account['accountname'] = $accountName;
                $account['industry'] = $leadInfo["industry"];
                $account['phone'] = $leadInfo["phone"];
                $account['fax'] = $leadInfo["fax"];
                $account['rating'] = $leadInfo["rating"];
                $account['email1'] = $leadInfo["email"];
                $account['website'] = $leadInfo["website"];
                $account['bill_city'] = $leadInfo["city"];
                $account['bill_code'] = $leadInfo["code"];
                $account['bill_country'] = $leadInfo["country"];
                $account['bill_state'] = $leadInfo["state"];
                $account['bill_street'] = $leadInfo["lane"];
                $account['bill_pobox'] = $leadInfo["pobox"];
                $account['ship_city'] = $leadInfo["city"];
                $account['ship_code'] = $leadInfo["code"];
                $account['ship_country'] = $leadInfo["country"];
                $account['ship_state'] = $leadInfo["state"];
                $account['ship_street'] = $leadInfo["lane"];
                $account['ship_pobox'] = $leadInfo["pobox"];
                $account['assigned_user_id'] = $assignedTo;
                $account['description'] = $leadInfo['description'];
                $leadFields = $leadHandler->getMeta()->getModuleFields();
                $accountFields = $accountHandler->getMeta()->getModuleFields();
                foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                    $accountFieldId = $mappingDetails['Accounts'];
                    if (empty($accountFieldId)) {
                        continue;
                    }
                    $accountField = vtws_getFieldfromFieldId($accountFieldId, $accountFields);
                    if ($accountField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                    if ($leadField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadFieldName = $leadField->getFieldName();
                    $accountFieldName = $accountField->getFieldName();
                    $account[$accountFieldName] = $leadInfo[$leadFieldName];
                }
                $account = vtws_create('Accounts', $account, $user);
                $accountIdComponents = vtws_getIdComponents($account['id']);
                $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $accountIdComponents[1]);
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
                }
                //Retrieve the lead related products and relate them with this new account
                $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
                }
                $status = vtws_saveLeadRelations($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
                }
            }
        }
    }
    $contactObject = VtigerWebserviceObject::fromName($adb, 'Contacts');
    $handlerPath = $contactObject->getHandlerPath();
    $handlerClass = $contactObject->getHandlerClass();
    require_once $handlerPath;
    $contactHandler = new $handlerClass($contactObject, $user, $adb, $log);
    if (!empty($crmId)) {
        $accountId = $crmId;
        $webserviceAccountId = vtws_getWebserviceEntityId('Accounts', $crmId);
    } elseif (!empty($accountName)) {
        if (count($accountIdComponents) === 2) {
            $accountId = $accountIdComponents[1];
            $webserviceAccountId = vtws_getId($accountIdComponents[0], $accountIdComponents[1]);
        }
    } else {
        $accountId = '';
        $webserviceAccountId = '';
    }
    if ($contactHandler->getMeta()->hasWriteAccess()) {
        $contact = array();
        $contact['assigned_user_id'] = $assignedTo;
        $contact['description'] = $leadInfo['description'];
        $contact['account_id'] = $webserviceAccountId;
        $contact['salutationtype'] = $leadInfo["salutationtype"];
        $contact['firstname'] = $leadInfo["firstname"];
        $contact['lastname'] = $leadInfo["lastname"];
        $contact['email'] = $leadInfo["email"];
        $contact['phone'] = $leadInfo["phone"];
        $contact['mobile'] = $leadInfo["mobile"];
        $contact['title'] = $leadInfo["designation"];
        $contact['fax'] = $leadInfo["fax"];
        $contact['yahooid'] = $leadInfo['yahooid'];
        $contact['leadsource'] = $leadInfo['leadsource'];
        $contact['mailingcity'] = $leadInfo["city"];
        $contact['mailingzip'] = $leadInfo["code"];
        $contact['mailingcountry'] = $leadInfo["country"];
        $contact['mailingstate'] = $leadInfo["state"];
        $contact['mailingstreet'] = $leadInfo["lane"];
        $contact['mailingpobox'] = $leadInfo["pobox"];
        $leadFields = $leadHandler->getMeta()->getModuleFields();
        $contactFields = $contactHandler->getMeta()->getModuleFields();
        foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
            $contactFieldId = $mappingDetails['Contacts'];
            if (empty($contactFieldId)) {
                continue;
            }
            $contactField = vtws_getFieldfromFieldId($contactFieldId, $contactFields);
            if ($contactField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
            if ($leadField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadFieldName = $leadField->getFieldName();
            $contactFieldName = $contactField->getFieldName();
            $contact[$contactFieldName] = $leadInfo[$leadFieldName];
        }
        $contact = vtws_create('Contacts', $contact, $user);
        $contactIdComponents = vtws_getIdComponents($contact['id']);
        $contactId = $contactIdComponents[1];
        //To convert relates Activites and Email.
        $status = vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Activities to the Contact");
        }
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Contact");
        }
        //Retrieve the lead related products and relate them with this new contact
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Contact");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Contact");
        }
        //Retrieve the lead related Campaigns and relate them with this new contact --Minnie
        $status = vtws_saveLeadRelatedCampaigns($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Campaigns to the Contact");
        }
    }
    if ((bool) $avoidPotential != true) {
        $potentialObject = VtigerWebserviceObject::fromName($adb, 'Potentials');
        $handlerPath = $potentialObject->getHandlerPath();
        $handlerClass = $potentialObject->getHandlerClass();
        require_once $handlerPath;
        $potentialHandler = new $handlerClass($potentialObject, $user, $adb, $log);
        if ($potentialHandler->getMeta()->hasWriteAccess()) {
            if (!empty($webserviceAccountId)) {
                $relatedTo = $webserviceAccountId;
            } else {
                if (!empty($contactId)) {
                    $relatedTo = vtws_getWebserviceEntityId('Contacts', $contactId);
                }
            }
            $potential['assigned_user_id'] = $assignedTo;
            $potential['description'] = $leadInfo['description'];
            $potential['related_to'] = $relatedTo;
            $potential['leadsource'] = $leadInfo['leadsource'];
            $leadFields = $leadHandler->getMeta()->getModuleFields();
            $potentialFields = $potentialHandler->getMeta()->getModuleFields();
            foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                $potentialFieldId = $mappingDetails['Potentials'];
                if (empty($potentialFieldId)) {
                    continue;
                }
                $potentialField = vtws_getFieldfromFieldId($potentialFieldId, $potentialFields);
                if ($potentialField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                if ($leadField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadFieldName = $leadField->getFieldName();
                $potentialFieldName = $potentialField->getFieldName();
                $potential[$potentialFieldName] = $leadInfo[$leadFieldName];
            }
            $potential = vtws_create('Potentials', $potential, $user);
            $potentialIdComponents = vtws_getIdComponents($potential['id']);
            if (!empty($accountId) && !empty($contactId)) {
                $sql = "insert into vtiger_contpotentialrel values(?,?)";
                $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
                if ($result === false) {
                    throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
                }
            }
            //Retrieve the lead related products and relate them with this new potential
            $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Potential");
            }
            $status = vtws_saveLeadRelations($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Potential");
            }
            $potentialId = $potentialIdComponents[1];
        }
    }
    //Updating the converted status
    if ($accountId != '' || $contactId != '') {
        $sql = "UPDATE vtiger_leaddetails SET converted = 1 where leadid=?";
        $result = $adb->pquery($sql, array($leadIdComponents[1]));
        if ($result === false) {
            throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_MARK_CONVERTED, "Failed mark lead converted");
        }
        //updating the campaign-lead relation --Minnie
        $sql = "delete from vtiger_campaignleadrel where leadid=?";
        $adb->pquery($sql, array($leadIdComponents[1]));
    }
    $result = array('leadId' => $leadId);
    if (!empty($webserviceAccountId)) {
        $result['accountId'] = $webserviceAccountId;
    } else {
        $result['accountId'] = '';
    }
    if (!empty($contactId)) {
        $result['contactId'] = vtws_getWebserviceEntityId('Contacts', $contactId);
    } else {
        $result['contactId'] = '';
    }
    if (!empty($potentialId)) {
        $result['potentialId'] = $potential['id'];
    } else {
        $result['potentialId'] = '';
    }
    return $result;
}
Example #14
0
 /**
  * Function to get contents of this task
  * @param <Object> $entity
  * @return <Array> contents
  */
 public function getContents($entity, $entityCache = false)
 {
     if (!$this->contents) {
         global $adb, $current_user;
         $taskContents = array();
         $entityId = $entity->getId();
         $utils = new VTWorkflowUtils();
         $adminUser = $utils->adminUser();
         if (!$entityCache) {
             $entityCache = new VTEntityCache($adminUser);
         }
         $fromUserId = Users::getActiveAdminId();
         $entityOwnerId = $entity->get('assigned_user_id');
         if ($entityOwnerId) {
             list($moduleId, $fromUserId) = explode('x', $entityOwnerId);
         }
         $ownerEntity = $entityCache->forId($entityOwnerId);
         if ($ownerEntity->getModuleName() === 'Groups') {
             list($moduleId, $recordId) = vtws_getIdComponents($entityId);
             $fromUserId = Vtiger_Util_Helper::getCreator($recordId);
         }
         if ($this->fromEmail && !($ownerEntity->getModuleName() === 'Groups' && strpos($this->fromEmail, 'assigned_user_id : (Users) ') !== false)) {
             $et = new VTEmailRecipientsTemplate($this->fromEmail);
             $fromEmailDetails = $et->render($entityCache, $entityId);
             $con1 = strpos($fromEmailDetails, '&lt;');
             $con2 = strpos($fromEmailDetails, '&gt;');
             if ($con1 && $con2) {
                 list($fromName, $fromEmail) = explode('&lt;', $fromEmailDetails);
                 list($fromEmail, $rest) = explode('&gt;', $fromEmail);
             } else {
                 $fromName = "";
                 $fromEmail = $fromEmailDetails;
             }
         } else {
             $userObj = CRMEntity::getInstance('Users');
             $userObj->retrieveCurrentUserInfoFromFile($fromUserId);
             if ($userObj) {
                 $fromEmail = $userObj->email1;
                 $fromName = $userObj->user_name;
             } else {
                 $result = $adb->pquery('SELECT user_name, email1 FROM vtiger_users WHERE id = ?', array($fromUserId));
                 $fromEmail = $adb->query_result($result, 0, 'email1');
                 $fromName = $adb->query_result($result, 0, 'user_name');
             }
         }
         if (!$fromEmail) {
             $utils->revertUser();
             return false;
         }
         $taskContents['fromEmail'] = $fromEmail;
         $taskContents['fromName'] = $fromName;
         if ($entity->getModuleName() === 'Events') {
             $contactId = $entity->get('contact_id');
             if ($contactId) {
                 $contactIds = '';
                 list($wsId, $recordId) = explode('x', $entityId);
                 $webserviceObject = VtigerWebserviceObject::fromName($adb, 'Contacts');
                 $result = $adb->pquery('SELECT contactid FROM vtiger_cntactivityrel WHERE activityid = ?', array($recordId));
                 $numOfRows = $adb->num_rows($result);
                 for ($i = 0; $i < $numOfRows; $i++) {
                     $contactIds .= vtws_getId($webserviceObject->getEntityId(), $adb->query_result($result, $i, 'contactid')) . ',';
                 }
             }
             $entity->set('contact_id', trim($contactIds, ','));
             $entityCache->cache[$entityId] = $entity;
         }
         $et = new VTEmailRecipientsTemplate($this->recepient);
         $toEmail = $et->render($entityCache, $entityId);
         $ecct = new VTEmailRecipientsTemplate($this->emailcc);
         $ccEmail = $ecct->render($entityCache, $entityId);
         $ebcct = new VTEmailRecipientsTemplate($this->emailbcc);
         $bccEmail = $ebcct->render($entityCache, $entityId);
         if (strlen(trim($toEmail, " \t\n,")) == 0 && strlen(trim($ccEmail, " \t\n,")) == 0 && strlen(trim($bccEmail, " \t\n,")) == 0) {
             $utils->revertUser();
             return false;
         }
         $taskContents['toEmail'] = $toEmail;
         $taskContents['ccEmail'] = $ccEmail;
         $taskContents['bccEmail'] = $bccEmail;
         $st = new VTSimpleTemplate($this->subject);
         $taskContents['subject'] = $st->render($entityCache, $entityId);
         $ct = new VTSimpleTemplate($this->content);
         $taskContents['content'] = $ct->render($entityCache, $entityId);
         $this->contents = $taskContents;
         $utils->revertUser();
     }
     if (is_array($this->contents)) {
         $this->contents = Zend_Json::encode($this->contents);
     }
     return $this->contents;
 }
 public function createRecords()
 {
     $adb = PearDatabase::getInstance();
     $moduleName = $this->module;
     $focus = CRMEntity::getInstance($moduleName);
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleObjectId = $moduleMeta->getEntityId();
     $moduleFields = $moduleMeta->getModuleFields();
     $tableName = Import_Utils::getDbTableName($this->user);
     $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Controller::$IMPORT_RECORD_NONE;
     if ($this->batchImport) {
         $configReader = new ConfigReader('modules/Import/config.inc', 'ImportConfig');
         $importBatchLimit = $configReader->getConfig('importBatchLimit');
         $sql .= ' LIMIT ' . $importBatchLimit;
     }
     $result = $adb->query($sql);
     $numberOfRecords = $adb->num_rows($result);
     if ($numberOfRecords <= 0) {
         return;
     }
     $fieldMapping = $this->fieldMapping;
     $fieldColumnMapping = $moduleMeta->getFieldColumnMapping();
     for ($i = 0; $i < $numberOfRecords; ++$i) {
         $row = $adb->raw_query_result_rowdata($result, $i);
         $rowId = $row['id'];
         $entityInfo = null;
         $fieldData = array();
         foreach ($fieldMapping as $fieldName => $index) {
             $fieldData[$fieldName] = $row[$fieldName];
         }
         $mergeType = $this->mergeType;
         $createRecord = false;
         if (method_exists($focus, 'importRecord')) {
             $entityInfo = $focus->importRecord($this, $fieldData);
         } else {
             if (!empty($mergeType) && $mergeType != Import_Utils::$AUTO_MERGE_NONE) {
                 $queryGenerator = new QueryGenerator($moduleName, $this->user);
                 $queryGenerator->initForDefaultCustomView();
                 $fieldsList = array('id');
                 $queryGenerator->setFields($fieldsList);
                 $mergeFields = $this->mergeFields;
                 foreach ($mergeFields as $index => $mergeField) {
                     if ($index != 0) {
                         $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                     }
                     $comparisonValue = $fieldData[$mergeField];
                     $fieldInstance = $moduleFields[$mergeField];
                     if ($fieldInstance->getFieldDataType() == 'owner') {
                         $userId = getUserId_Ol($comparisonValue);
                         $comparisonValue = getUserFullName($userId);
                     }
                     if ($fieldInstance->getFieldDataType() == 'reference') {
                         if (strpos($comparisonValue, '::::') > 0) {
                             $referenceFileValueComponents = explode('::::', $comparisonValue);
                         } else {
                             $referenceFileValueComponents = explode(':::', $comparisonValue);
                         }
                         if (count($referenceFileValueComponents) > 1) {
                             $comparisonValue = trim($referenceFileValueComponents[1]);
                         }
                     }
                     $queryGenerator->addCondition($mergeField, $comparisonValue, 'e');
                 }
                 $query = $queryGenerator->getQuery();
                 $duplicatesResult = $adb->query($query);
                 $noOfDuplicates = $adb->num_rows($duplicatesResult);
                 if ($noOfDuplicates > 0) {
                     if ($mergeType == Import_Utils::$AUTO_MERGE_IGNORE) {
                         $entityInfo['status'] = self::$IMPORT_RECORD_SKIPPED;
                     } elseif ($mergeType == Import_Utils::$AUTO_MERGE_OVERWRITE || $mergeType == Import_Utils::$AUTO_MERGE_MERGEFIELDS) {
                         for ($index = 0; $index < $noOfDuplicates - 1; ++$index) {
                             $duplicateRecordId = $adb->query_result($duplicatesResult, $index, $fieldColumnMapping['id']);
                             $entityId = vtws_getId($moduleObjectId, $duplicateRecordId);
                             vtws_delete($entityId, $this->user);
                         }
                         $baseRecordId = $adb->query_result($duplicatesResult, $noOfDuplicates - 1, $fieldColumnMapping['id']);
                         $baseEntityId = vtws_getId($moduleObjectId, $baseRecordId);
                         if ($mergeType == Import_Utils::$AUTO_MERGE_OVERWRITE) {
                             $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                             $fieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_update($fieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_UPDATED;
                             //Prepare data for event handler
                             $entityData = array();
                             $entityData['rowId'] = $rowId;
                             $entityData['tableName'] = $tableName;
                             $entityData['entityInfo'] = $entityInfo;
                             $entityData['fieldData'] = $fieldData;
                             $entityData['moduleName'] = $moduleName;
                             $entityData['user'] = $this->user;
                             cbEventHandler::do_action('corebos.entity.import.overwrite', $entityData);
                         }
                         if ($mergeType == Import_Utils::$AUTO_MERGE_MERGEFIELDS) {
                             $filteredFieldData = array();
                             $defaultFieldValues = $this->getDefaultFieldValues($moduleMeta);
                             foreach ($fieldData as $fieldName => $fieldValue) {
                                 if (!empty($fieldValue)) {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             $existingFieldValues = vtws_retrieve($baseEntityId, $this->user);
                             foreach ($existingFieldValues as $fieldName => $fieldValue) {
                                 if (empty($fieldValue) && empty($filteredFieldData[$fieldName]) && !empty($defaultFieldValues[$fieldName])) {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             $filteredFieldData = $this->transformForImport($filteredFieldData, $moduleMeta, false, true);
                             $filteredFieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_revise($filteredFieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_MERGED;
                             //Prepare data for event handler
                             $entityData = array();
                             $entityData['rowId'] = $rowId;
                             $entityData['tableName'] = $tableName;
                             $entityData['entityInfo'] = $entityInfo;
                             $entityData['fieldData'] = $fieldData;
                             $entityData['moduleName'] = $moduleName;
                             $entityData['user'] = $this->user;
                             cbEventHandler::do_action('corebos.entity.import.merge', $entityData);
                         }
                     } else {
                         $createRecord = true;
                     }
                 } else {
                     $createRecord = true;
                 }
             } else {
                 $createRecord = true;
             }
             if ($createRecord) {
                 $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                 if ($fieldData == null) {
                     $entityInfo = null;
                 } else {
                     $entityInfo = vtws_create($moduleName, $fieldData, $this->user);
                     $entityInfo['status'] = self::$IMPORT_RECORD_CREATED;
                     //Prepare data for event handler
                     $entityData = array();
                     $entityData['rowId'] = $rowId;
                     $entityData['tableName'] = $tableName;
                     $entityData['entityInfo'] = $entityInfo;
                     $entityData['fieldData'] = $fieldData;
                     $entityData['moduleName'] = $moduleName;
                     $entityData['user'] = $this->user;
                     cbEventHandler::do_action('corebos.entity.import.create', $entityData);
                 }
             }
         }
         if ($entityInfo == null) {
             $entityInfo = array('id' => null, 'status' => self::$IMPORT_RECORD_FAILED);
         }
         $this->importedRecordInfo[$rowId] = $entityInfo;
         $this->updateImportStatus($rowId, $entityInfo);
     }
     unset($result);
     return true;
 }
Example #16
0
 public function revise($element)
 {
     $ids = vtws_getIdComponents($element["id"]);
     $element = DataTransform::sanitizeForInsert($element, $this->meta);
     $element = $this->restrictFields($element, true);
     $success = $this->__retrieve($ids[1]);
     if (!$success) {
         throw new WebServiceException(WebServiceErrorCode::$RECORDNOTFOUND, "Record not found");
     }
     $allDetails = $this->getElement();
     foreach ($allDetails as $index => $value) {
         if (!isset($element)) {
             $element[$index] = $value;
         }
     }
     $success = $this->__revise($element, $ids[1]);
     if (!$success) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
     }
     return $this->retrieve(vtws_getId($this->meta->getEntityId(), $ids[1]));
 }
Example #17
0
 public function process()
 {
     $variableList = $this->getTemplateVariableListForModule($this->module);
     $handler = vtws_getModuleHandlerFromName($this->module, $this->user);
     $meta = $handler->getMeta();
     $referenceFields = $meta->getReferenceFieldDetails();
     $fieldColumnMapping = $meta->getFieldColumnMapping();
     $columnTableMapping = $meta->getColumnTableMapping();
     $tableList = array();
     $columnList = array();
     $allColumnList = $meta->getUserAccessibleColumns();
     if (count($variableList) > 0) {
         foreach ($variableList as $column) {
             if (in_array($column, $allColumnList)) {
                 $columnList[] = $column;
             }
         }
         foreach ($columnList as $column) {
             if (!empty($columnTableMapping[$column])) {
                 $tableList[$columnTableMapping[$column]] = '';
             }
         }
         $tableList = array_keys($tableList);
         $defaultTableList = $meta->getEntityDefaultTableList();
         foreach ($defaultTableList as $defaultTable) {
             if (!in_array($defaultTable, $tableList)) {
                 $tableList[] = $defaultTable;
             }
         }
         // right now this is will be limited to module type, entities.
         // need to extend it to non-module entities when we have a reliable way of getting
         // record type from the given record id. non webservice id.
         // can extend to non-module entity without many changes as long as the reference field
         // refers to one type of entity, either module entities or non-module entities.
         if (count($tableList) > 0) {
             $sql = 'select ' . implode(', ', $columnList) . ' from ' . $tableList[0];
             $moduleTableIndexList = $meta->getEntityTableIndexList();
             foreach ($tableList as $index => $tableName) {
                 if ($tableName != $tableList[0]) {
                     $sql .= ' INNER JOIN ' . $tableName . ' ON ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=' . $tableName . '.' . $moduleTableIndexList[$tableName];
                 }
             }
             $sql .= ' WHERE';
             $deleteQuery = $meta->getEntityDeletedQuery();
             if (!empty($deleteQuery)) {
                 $sql .= ' ' . $meta->getEntityDeletedQuery() . ' AND';
             }
             $sql .= ' ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=?';
             $params = array($this->recordId);
             $db = PearDatabase::getInstance();
             $result = $db->pquery($sql, $params);
             $it = new SqlResultIterator($db, $result);
             //assuming there can only be one row.
             $values = array();
             foreach ($it as $row) {
                 foreach ($columnList as $column) {
                     $values[$column] = $row->get($column);
                 }
             }
             $moduleFields = $meta->getModuleFields();
             foreach ($moduleFields as $fieldName => $webserviceField) {
                 if (isset($values[$fieldColumnMapping[$fieldName]]) && $values[$fieldColumnMapping[$fieldName]] !== null) {
                     if (strcasecmp($webserviceField->getFieldDataType(), 'reference') === 0) {
                         $details = $webserviceField->getReferenceList();
                         if (count($details) == 1) {
                             $referencedObjectHandler = vtws_getModuleHandlerFromName($details[0], $this->user);
                         } else {
                             $type = getSalesEntityType($values[$fieldColumnMapping[$fieldName]]);
                             $referencedObjectHandler = vtws_getModuleHandlerFromName($type, $this->user);
                         }
                         $referencedObjectMeta = $referencedObjectHandler->getMeta();
                         $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'owner') === 0) {
                         $referencedObjectHandler = vtws_getModuleHandlerFromName(vtws_getOwnerType($values[$fieldColumnMapping[$fieldName]]), $this->user);
                         $referencedObjectMeta = $referencedObjectHandler->getMeta();
                         $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'picklist') === 0) {
                         $values[$fieldColumnMapping[$fieldName]] = getTranslatedString($values[$fieldColumnMapping[$fieldName]], $this->module);
                     } elseif (strcasecmp($webserviceField->getFieldDataType(), 'datetime') === 0) {
                         $values[$fieldColumnMapping[$fieldName]] = $values[$fieldColumnMapping[$fieldName]] . ' ' . DateTimeField::getDBTimeZone();
                     }
                 }
             }
             foreach ($columnList as $column) {
                 $needle = '$' . strtolower($this->module) . "-{$column}\$";
                 $this->processedDescription = str_replace($needle, $values[$column], $this->processedDescription);
             }
         }
     }
     $this->processed = true;
 }
Example #18
0
function vtws_getWebserviceGroupFromGroups($groups)
{
    global $adb;
    $webserviceObject = VtigerWebserviceObject::fromName($adb, 'Groups');
    foreach ($groups as $index => $group) {
        $groups[$index]['id'] = vtws_getId($webserviceObject->getEntityId(), $group['id']);
    }
    return $groups;
}
Example #19
0
function vtws_sync($mtime, $elementType, $user)
{
    global $adb, $recordString, $modifiedTimeString;
    $ignoreModules = array("");
    $typed = true;
    $dformat = "Y-m-d H:i:s";
    $datetime = date($dformat, $mtime);
    $setypeArray = array();
    $setypeData = array();
    $setypeHandler = array();
    $setypeNoAccessArray = array();
    if (!isset($elementType) || $elementType == '' || $elementType == null) {
        $typed = false;
    }
    $adb->startTransaction();
    $q = "select crmid,setype from vtiger_crmentity where modifiedtime >? and smownerid=? and deleted=0";
    $params = array($datetime, $user->id);
    if ($typed) {
        $q = $q . " and setype=?";
        array_push($params, $elementType);
    }
    $result = $adb->pquery($q, $params);
    do {
        if ($arre) {
            if (strpos($arre["setype"], " ") === FALSE) {
                if ($arre["setype"] == 'Calendar') {
                    $seType = vtws_getCalendarEntityType($arre['crmid']);
                } else {
                    $seType = $arre["setype"];
                }
                if (array_search($seType, $ignoreModules) === FALSE) {
                    $setypeArray[$arre["crmid"]] = $seType;
                    if (!$setypeData[$seType]) {
                        $webserviceObject = VtigerWebserviceObject::fromName($adb, $seType);
                        $handlerPath = $webserviceObject->getHandlerPath();
                        $handlerClass = $webserviceObject->getHandlerClass();
                        require_once $handlerPath;
                        $setypeHandler[$seType] = new $handlerClass($webserviceObject, $user, $adb, $log);
                        $meta = $setypeHandler[$seType]->getMeta();
                        $setypeData[$seType] = new VtigerCRMObject(getTabId($meta->getEntityName()), true);
                    }
                }
            }
        }
        $arre = $adb->fetchByAssoc($result);
    } while ($arre);
    $output = array();
    $output["updated"] = array();
    foreach ($setypeArray as $key => $val) {
        $handler = $setypeHandler[$val];
        $meta = $handler->getMeta();
        if (!$meta->hasAccess() || !$meta->hasWriteAccess() || !$meta->hasPermission(EntityMeta::$RETRIEVE, $key)) {
            if (!$setypeNoAccessArray[$val]) {
                $setypeNoAccessArray[] = $val;
            }
            continue;
        }
        try {
            $error = $setypeData[$val]->read($key);
            if (!$error) {
                //Ignore records whose fetch results in an error.
                continue;
            }
            $output["updated"][] = DataTransform::filterAndSanitize($setypeData[$val]->getFields(), $meta);
        } catch (WebServiceException $e) {
            //ignore records the user doesn't have access to.
            continue;
        } catch (Exception $e) {
            throw new WebServiceException(WebServiceErrorCode::$INTERNALERROR, "Unknown Error while processing request");
        }
    }
    $setypeArray = array();
    $setypeData = array();
    $q = "select crmid,setype,modifiedtime from vtiger_crmentity where modifiedtime >? and smownerid=? and deleted=1";
    $params = array($datetime, $user->id);
    if ($typed) {
        $q = $q . " and setype=?";
        array_push($params, $elementType);
    }
    $result = $adb->pquery($q, $params);
    do {
        if ($arre) {
            if (strpos($arre["setype"], " ") === FALSE) {
                if ($arre["setype"] == 'Calendar') {
                    $seType = vtws_getCalendarEntityType($arre['crmid']);
                } else {
                    $seType = $arre["setype"];
                }
                if (array_search($seType, $ignoreModules) === FALSE) {
                    $setypeArray[$arre["crmid"]] = $seType;
                    if (!$setypeData[$seType]) {
                        $webserviceObject = VtigerWebserviceObject::fromName($adb, $seType);
                        $handlerPath = $webserviceObject->getHandlerPath();
                        $handlerClass = $webserviceObject->getHandlerClass();
                        require_once $handlerPath;
                        $setypeHandler[$seType] = new $handlerClass($webserviceObject, $user, $adb, $log);
                        $meta = $setypeHandler[$seType]->getMeta();
                        $setypeData[$seType] = new VtigerCRMObject(getTabId($meta->getEntityName()), true);
                    }
                }
            }
        }
        $arre = $adb->fetchByAssoc($result);
    } while ($arre);
    $output["deleted"] = array();
    foreach ($setypeArray as $key => $val) {
        $handler = $setypeHandler[$val];
        $meta = $handler->getMeta();
        if (!$meta->hasAccess() || !$meta->hasWriteAccess()) {
            if (!$setypeNoAccessArray[$val]) {
                $setypeNoAccessArray[] = $val;
            }
            continue;
        }
        $output["deleted"][] = vtws_getId($meta->getEntityId(), $key);
    }
    $q = "select max(modifiedtime) as modifiedtime from vtiger_crmentity where modifiedtime >? and smownerid=?";
    $params = array($datetime, $user->id);
    if ($typed) {
        $q = $q . " and setype=?";
        array_push($params, $elementType);
    } else {
        if (sizeof($setypeNoAccessArray) > 0) {
            $q = $q . " and setype not in ('" . generateQuestionMarks($setypeNoAccessArray) . "')";
            array_push($params, $setypeNoAccessArray);
        }
    }
    $result = $adb->pquery($q, $params);
    $arre = $adb->fetchByAssoc($result);
    $modifiedtime = $arre['modifiedtime'];
    if (!$modifiedtime) {
        $modifiedtime = $mtime;
    } else {
        $modifiedtime = vtws_getSeconds($modifiedtime);
    }
    if (is_string($modifiedtime)) {
        $modifiedtime = intval($modifiedtime);
    }
    $output['lastModifiedTime'] = $modifiedtime;
    $error = $adb->hasFailedTransaction();
    $adb->completeTransaction();
    if ($error) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    VTWS_PreserveGlobal::flush();
    return $output;
}