/** * * @param WebserviceId $id * @param String $oldPassword * @param String $newPassword * @param String $confirmPassword * @param Users $user * */ function vtws_changePassword($id, $oldPassword, $newPassword, $confirmPassword, $user) { vtws_preserveGlobal('current_user', $user); $idComponents = vtws_getIdComponents($id); if ($idComponents[1] == $user->id || is_admin($user)) { $newUser = new Users(); $newUser->retrieve_entity_info($idComponents[1], 'Users'); if (!is_admin($user)) { if (empty($oldPassword)) { throw new WebServiceException(WebServiceErrorCode::$INVALIDOLDPASSWORD, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$INVALIDOLDPASSWORD)); } if (!$user->verifyPassword($oldPassword)) { throw new WebServiceException(WebServiceErrorCode::$INVALIDOLDPASSWORD, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$INVALIDOLDPASSWORD)); } } if (strcmp($newPassword, $confirmPassword) === 0) { $success = $newUser->change_password($oldPassword, $newPassword); $error = $newUser->db->hasFailedTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } if (!$success) { throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$CHANGEPASSWORDFAILURE)); } } else { throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$CHANGEPASSWORDFAILURE)); } VTWS_PreserveGlobal::flush(); return array('message' => 'Changed password successfully'); } }
/** Function to save the user information into the database * @param $module -- module name:: Type varchar * */ function save($module_name) { $adb = PearDatabase::getInstance(); $log = vglobal('log'); //Event triggering code require_once "include/events/include.inc"; //In Bulk mode stop triggering events if (!self::isBulkSaveMode()) { $em = new VTEventsManager($adb); // Initialize Event trigger cache $em->initTriggerCache(); $entityData = VTEntityData::fromCRMEntity($this); $em->triggerEvent("vtiger.entity.beforesave.modifiable", $entityData); $em->triggerEvent("vtiger.entity.beforesave", $entityData); $em->triggerEvent("vtiger.entity.beforesave.final", $entityData); } if ($this->mode != 'edit') { $sql = 'SELECT id FROM vtiger_users WHERE user_name = ? OR email1 = ?'; $result = $adb->pquery($sql, array($this->column_fields['user_name'], $this->column_fields['email1'])); if ($adb->num_rows($result) > 0) { Vtiger_Functions::throwNewException('LBL_USER_EXISTS'); throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_USER_EXISTS')); return false; } } else { $query = 'SELECT `roleid` FROM `vtiger_user2role` WHERE `userid` = ? LIMIT 1;'; $oldRoleResult = $adb->pquery($query, [$this->id]); $oldRole = $adb->query_result($oldRoleResult, 0, 'roleid'); if ($oldRole != $this->column_fields['roleid']) { $query = 'DELETE FROM `vtiger_module_dashboard_widgets` WHERE `userid` = ?;'; $adb->pquery($query, [$this->id]); } } //Save entity being called with the modulename as parameter $this->saveentity($module_name); if ($em) { //Event triggering code $em->triggerEvent("vtiger.entity.aftersave", $entityData); $em->triggerEvent("vtiger.entity.aftersave.final", $entityData); //Event triggering code ends } // Added for Reminder Popup support $query_prev_interval = $adb->pquery("SELECT reminder_interval from vtiger_users where id=?", array($this->id)); $prev_reminder_interval = $adb->query_result($query_prev_interval, 0, 'reminder_interval'); //$focus->imagename = $image_upload_array['imagename']; $this->saveHomeStuffOrder($this->id); SaveTagCloudView($this->id); // Added for Reminder Popup support $this->resetReminderInterval($prev_reminder_interval); //Creating the Privileges Flat File if (isset($this->column_fields['roleid'])) { updateUser2RoleMapping($this->column_fields['roleid'], $this->id); } //After adding new user, set the default activity types for new user Vtiger_Util_Helper::setCalendarDefaultActivityTypesForUser($this->id); require_once 'modules/Users/CreateUserPrivilegeFile.php'; createUserPrivilegesfile($this->id); createUserSharingPrivilegesfile($this->id); }
function vtws_convertlead($entityvalues, $user) { global $adb, $log; if (empty($entityvalues['assignedTo'])) { $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id); } if (empty($entityvalues['transferRelatedRecordsTo'])) { $entityvalues['transferRelatedRecordsTo'] = 'Contacts'; } $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads'); $handlerPath = $leadObject->getHandlerPath(); $handlerClass = $leadObject->getHandlerClass(); require_once $handlerPath; $leadHandler = new $handlerClass($leadObject, $user, $adb, $log); $leadInfo = vtws_retrieve($entityvalues['leadId'], $user); $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?"; $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']); $result = $adb->pquery($sql, array($leadIdComponents[1])); if ($result === false) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $rowCount = $adb->num_rows($result); if ($rowCount > 0) { throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted"); } $entityIds = array(); $availableModules = array('Accounts', 'Contacts', 'Potentials'); if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['create'])) { return null; } foreach ($availableModules as $entityName) { if ($entityvalues['entities'][$entityName]['create']) { $entityvalue = $entityvalues['entities'][$entityName]; $entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']); $handlerPath = $entityObject->getHandlerPath(); $handlerClass = $entityObject->getHandlerClass(); require_once $handlerPath; $entityHandler = new $handlerClass($entityObject, $user, $adb, $log); $entityObjectValues = array(); $entityObjectValues['assigned_user_id'] = $entityvalues['assignedTo']; $entityObjectValues = vtws_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo); //update potential related to property if ($entityvalue['name'] == 'Potentials') { if (!empty($entityIds['Accounts'])) { $entityObjectValues['related_to'] = $entityIds['Accounts']; } if (!empty($entityIds['Contacts'])) { $entityObjectValues['contact_id'] = $entityIds['Contacts']; } } //update the contacts relation if ($entityvalue['name'] == 'Contacts') { if (!empty($entityIds['Accounts'])) { $entityObjectValues['account_id'] = $entityIds['Accounts']; } } try { $create = true; if ($entityvalue['name'] == 'Accounts') { $sql = "SELECT vtiger_account.accountid FROM vtiger_account,vtiger_crmentity WHERE vtiger_crmentity.crmid=vtiger_account.accountid AND vtiger_account.accountname=? AND vtiger_crmentity.deleted=0"; $result = $adb->pquery($sql, array($entityvalue['accountname'])); if ($adb->num_rows($result) > 0) { $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $adb->query_result($result, 0, 'accountid')); $create = false; } } if ($create) { $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user); $entityIds[$entityName] = $entityRecord['id']; } } catch (Exception $e) { throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']); } } } try { $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']); $accountId = $accountIdComponents[1]; $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']); $contactId = $contactIdComponents[1]; if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) { $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']); $potentialId = $potentialIdComponents[1]; $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"); } } $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues); $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]); vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]); vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user); } catch (Exception $e) { foreach ($entityIds as $entity => $id) { vtws_delete($id, $user); } return null; } return $entityIds; }
public function query($q) { $parser = new Parser($this->user, $q); $error = $parser->parse(); if ($error) { return $parser->getError(); } $mysql_query = $parser->getSql(); $meta = $parser->getObjectMetaData(); $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $output[] = DataTransform::sanitizeDataWithColumn($row, $meta); } return $output; }
function vtws_convertlead($entityvalues, $user) { $adb = PearDatabase::getInstance(); $log = vglobal('log'); $log->debug('Start ' . __CLASS__ . ':' . __FUNCTION__); if (empty($entityvalues['assignedTo'])) { $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id); } if (empty($entityvalues['transferRelatedRecordsTo'])) { $entityvalues['transferRelatedRecordsTo'] = 'Accounts'; } $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads'); $handlerPath = $leadObject->getHandlerPath(); $handlerClass = $leadObject->getHandlerClass(); require_once $handlerPath; $leadHandler = new $handlerClass($leadObject, $user, $adb, $log); $leadInfo = vtws_retrieve($entityvalues['leadId'], $user); $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?"; $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']); $result = $adb->pquery($sql, array($leadIdComponents[1])); if ($result === false) { $log->error('Error converting a lead: ' . vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $rowCount = $adb->num_rows($result); if ($rowCount > 0) { $log->error('Error converting a lead: Lead is already converted'); throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted"); } require_once "include/events/include.inc"; $em = new VTEventsManager($adb); // Initialize Event trigger cache $em->initTriggerCache(); $entityData = VTEntityData::fromEntityId($adb, $leadIdComponents[1]); $em->triggerEvent('entity.convertlead.before', [$entityvalues, $user, $leadInfo]); $entityIds = []; $availableModules = ['Accounts', 'Contacts', 'Potentials']; if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['create'])) { return null; } foreach ($availableModules as $entityName) { if ($entityvalues['entities'][$entityName]['create']) { $entityvalue = $entityvalues['entities'][$entityName]; $entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']); $handlerPath = $entityObject->getHandlerPath(); $handlerClass = $entityObject->getHandlerClass(); require_once $handlerPath; $entityHandler = new $handlerClass($entityObject, $user, $adb, $log); $entityObjectValues = array(); $entityObjectValues['assigned_user_id'] = $entityvalues['assignedTo']; $entityObjectValues = vtws_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo); //update potential related to property if ($entityvalue['name'] == 'Potentials') { if (!empty($entityIds['Accounts'])) { $entityObjectValues['related_to'] = $entityIds['Accounts']; } if (!empty($entityIds['Contacts'])) { $entityObjectValues['contact_id'] = $entityIds['Contacts']; } } //update the contacts relation if ($entityvalue['name'] == 'Contacts') { if (!empty($entityIds['Accounts'])) { $entityObjectValues['parent_id'] = $entityIds['Accounts']; } } try { $create = true; if ($entityvalue['name'] == 'Accounts' && $entityvalue['convert_to_id'] && is_int($entityvalue['convert_to_id'])) { $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $entityvalue['convert_to_id']); $create = false; } if ($create) { $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user); $entityIds[$entityName] = $entityRecord['id']; } } catch (Exception $e) { $log->error('Error converting a lead: ' . $e->getMessage()); throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']); } } } try { $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']); $accountId = $accountIdComponents[1]; $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']); $contactId = $contactIdComponents[1]; if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) { $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']); $potentialId = $potentialIdComponents[1]; $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"); } } $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues); $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]); vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]); vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user); if ($em) { $em->triggerEvent('entity.convertlead.after', [$entityvalues, $user, $leadInfo, $entityIds]); } } catch (Exception $e) { $log->error('Error converting a lead: ' . $e->getMessage()); foreach ($entityIds as $entity => $id) { vtws_delete($id, $user); } return null; } $log->debug('End ' . __CLASS__ . ':' . __FUNCTION__); return $entityIds; }
/** Function to save the user information into the database * @param $module -- module name:: Type varchar * */ function save($module_name) { $adb = PearDatabase::getInstance(); $log = vglobal('log'); if ($this->mode != 'edit') { $sql = 'SELECT id FROM vtiger_users WHERE user_name = ? OR email1 = ?'; $result = $adb->pquery($sql, array($this->column_fields['user_name'], $this->column_fields['email1'])); if ($adb->num_rows($result) > 0) { Vtiger_Functions::throwNewException('LBL_USER_EXISTS'); throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_USER_EXISTS')); return false; } } //Save entity being called with the modulename as parameter $this->saveentity($module_name); // Added for Reminder Popup support $query_prev_interval = $adb->pquery("SELECT reminder_interval from vtiger_users where id=?", array($this->id)); $prev_reminder_interval = $adb->query_result($query_prev_interval, 0, 'reminder_interval'); //$focus->imagename = $image_upload_array['imagename']; $this->saveHomeStuffOrder($this->id); SaveTagCloudView($this->id); // Added for Reminder Popup support $this->resetReminderInterval($prev_reminder_interval); //Creating the Privileges Flat File if (isset($this->column_fields['roleid'])) { updateUser2RoleMapping($this->column_fields['roleid'], $this->id); } //After adding new user, set the default activity types for new user Vtiger_Util_Helper::setCalendarDefaultActivityTypesForUser($this->id); require_once 'modules/Users/CreateUserPrivilegeFile.php'; createUserPrivilegesfile($this->id); createUserSharingPrivilegesfile($this->id); }
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; }
public function query($q) { $parser = new Parser($this->user, $q); if (stripos($q, 'related.') > 0) { // related query require_once 'include/Webservices/Utils.php'; require_once 'include/Webservices/GetRelatedRecords.php'; $queryParameters['columns'] = trim(substr($q, 6, stripos($q, ' from ') - 5)); $moduleRegex = "/[fF][rR][Oo][Mm]\\s+([^\\s;]+)/"; preg_match($moduleRegex, $q, $m); $relatedModule = trim($m[1]); $moduleRegex = "/[rR][eE][lL][aA][tT][eE][dD]\\.([^\\s;]+)\\s*=\\s*([^\\s;]+)/"; preg_match($moduleRegex, $q, $m); $moduleName = trim($m[1]); $id = trim($m[2], "(')"); $mysql_query = __getRLQuery($id, $moduleName, $relatedModule, $queryParameters, $this->user); // where, limit and order $afterwhere = substr($q, stripos($q, ' where ') + 6); // eliminate related conditions $relatedCond = "/\\(*[rR][eE][lL][aA][tT][eE][dD]\\.([^\\s;]+)\\s*=\\s*([^\\s;]+)\\)*\\s*([aA][nN][dD]|[oO][rR]\\s)*/"; preg_match($relatedCond, $afterwhere, $pieces); $glue = isset($pieces[3]) ? trim($pieces[3]) : 'and'; $afterwhere = trim(preg_replace($relatedCond, '', $afterwhere), ' ;'); $relatedCond = "/\\s+([aA][nN][dD]|[oO][rR])+\\s+([oO][rR][dD][eE][rR])+/"; $afterwhere = trim(preg_replace($relatedCond, ' order ', $afterwhere), ' ;'); $relatedCond = "/\\s+([aA][nN][dD]|[oO][rR])+\\s+([lL][iI][mM][iI][tT])+/"; $afterwhere = trim(preg_replace($relatedCond, ' limit ', $afterwhere), ' ;'); // if related is at the end of condition we need to strip last and|or if (strtolower(substr($afterwhere, -3)) == 'and') { $afterwhere = substr($afterwhere, 0, strlen($afterwhere) - 3); } if (strtolower(substr($afterwhere, -2)) == 'or') { $afterwhere = substr($afterwhere, 0, strlen($afterwhere) - 2); } // transform REST ids $relatedCond = "/=\\s*'*\\d+x(\\d+)'*/"; $afterwhere = preg_replace($relatedCond, ' = $1 ', $afterwhere); // kill unbalanced parenthesis $balanced = 0; $pila = array(); for ($ch = 0; $ch < strlen($afterwhere); $ch++) { if ($afterwhere[$ch] == '(') { $pila[$balanced] = array('pos' => $ch, 'dir' => '('); $balanced++; } elseif ($afterwhere[$ch] == ')') { if ($balanced > 0 and $pila[$balanced - 1]['dir'] == '(') { array_pop($pila); $balanced--; } else { $pila[$balanced] = array('pos' => $ch, 'dir' => ')'); $balanced++; } } } foreach ($pila as $paren) { $afterwhere[$paren['pos']] = ' '; } // transform artificial commentcontent for FAQ and Ticket comments if (strtolower($relatedModule) == 'modcomments' and (strtolower($moduleName) == 'helpdesk' or strtolower($moduleName) == 'faq')) { $afterwhere = str_ireplace('commentcontent', 'comments', $afterwhere); } // transform fieldnames to columnnames $handler = vtws_getModuleHandlerFromName($relatedModule, $this->user); $meta = $handler->getMeta(); $fldmap = $meta->getFieldColumnMapping(); $tblmap = $meta->getColumnTableMapping(); $tok = strtok($afterwhere, ' '); $chgawhere = ''; while ($tok !== false) { if (!empty($fldmap[$tok])) { $chgawhere .= (strpos($tok, '.') ? '' : $tblmap[$fldmap[$tok]] . '.') . $fldmap[$tok] . ' '; } else { $chgawhere .= $tok . ' '; } $tok = strtok(' '); } $afterwhere = $chgawhere; if (!empty($afterwhere)) { $start = strtolower(substr(trim($afterwhere), 0, 5)); if ($start != 'limit' and $start != 'order') { // there is a condition we add the glue $mysql_query .= " {$glue} "; } $mysql_query .= " {$afterwhere}"; } if (stripos($q, 'count(*)') > 0) { $mysql_query = str_ireplace(' as count ', '', mkCountQuery($mysql_query)); } } else { $error = $parser->parse(); if ($error) { return $parser->getError(); } $mysql_query = $parser->getSql(); $meta = $parser->getObjectMetaData(); } $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $output[] = DataTransform::sanitizeDataWithColumn($row, $meta); } return $output; }
function vtws_convertlead($leadId, $assignedTo, $accountName, $avoidPotential, $potential, $transferRelatedRecordsTo, $user) { global $adb, $log; if (empty($assignedTo)) { $assignedTo = vtws_getWebserviceEntityId('Users', $user->id); } if (empty($transferRelatedRecordsTo)) { $transferRelatedRecordsTo = 'Contacts'; } 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"); } } $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, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $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, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $rowCount = $adb->num_rows($result); if ($rowCount != 0 && vtlib_isModuleActive('Accounts') === true) { $crmId = $adb->query_result($result, 0, "accountid"); if ($transferRelatedRecordsTo == 'Accounts') { vtws_transferLeadRelatedRecords($leadIdComponents[1], $crmId, 'Accounts'); } } 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']); if ($transferRelatedRecordsTo == 'Accounts') { vtws_transferLeadRelatedRecords($leadIdComponents[1], $accountIdComponents[1], 'Accounts'); } } } } $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['secondaryemail'] = $leadInfo['secondaryemail']; $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]; if ($transferRelatedRecordsTo == 'Contacts') { vtws_transferLeadRelatedRecords($leadIdComponents[1], $contactIdComponents[1], 'Contacts'); } //To convert relates Activites and Email. if ($transferRelatedRecordsTo == 'Accounts') { $transferToId = $accountId; } else { $transferToId = $contactId; } $status = vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $transferToId); if ($status === false) { throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Activities 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"); } } $potentialId = $potentialIdComponents[1]; vtws_transferLeadRelatedRecords($leadIdComponents[1], $potentialId, "Potentials"); } } //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])); $sql = "DELETE FROM vtiger_tracker WHERE item_id=?"; $adb->pquery($sql, array($leadIdComponents[1])); //update the modifiedtime and modified by information for the record $leadModifiedTime = $adb->formatDate(date('Y-m-d H:i:s'), true); $crmentityUpdateSql = "UPDATE vtiger_crmentity SET modifiedtime=?, modifiedby=? WHERE crmid=?"; $adb->pquery($crmentityUpdateSql, array($leadModifiedTime, $user->id, $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; }
public function query($q) { $mysql_query = $this->wsVTQL2SQL($q, $meta, $queryRelatedModules); $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $newrow = DataTransform::sanitizeDataWithColumn($row, $meta); if (__FQNExtendedQueryIsFQNQuery($q)) { // related query $relflds = array_diff_key($row, $newrow); foreach ($queryRelatedModules as $relmod => $relmeta) { $lrm = strtolower($relmod); $newrflds = array(); foreach ($relflds as $fldname => $fldvalue) { $fldmod = substr($fldname, 0, strlen($relmod)); if (isset($row[$fldname]) and $fldmod == $lrm) { $newkey = substr($fldname, strlen($lrm)); $newrflds[$newkey] = $fldvalue; } } $relrow = DataTransform::sanitizeDataWithColumn($newrflds, $relmeta); $newrelrow = array(); foreach ($relrow as $key => $value) { $newrelrow[$lrm . $key] = $value; } $newrow = array_merge($newrow, $newrelrow); } } $output[] = $newrow; } return $output; }