/** * Function to get all the available picklist values for the current field * @return <Array> List of picklist values if the field is of type MultiReferenceValue. */ public function getPicklistValues() { $picklistValues = $this->get('picklistValues'); if (!empty($picklistValues)) { return $picklistValues; } $params = $this->get('field')->getFieldParams(); $db = PearDatabase::getInstance(); $currentUser = Users_Record_Model::getCurrentUserModel(); $fieldInfo = Vtiger_Functions::getModuleFieldInfoWithId($params['field']); $queryGenerator = new QueryGenerator($params['module'], $currentUser); $queryGenerator->setFields([$fieldInfo['columnname']]); if ($params['filterField'] != '-') { $queryGenerator->addCondition($params['filterField'], $params['filterValue'], 'e'); } $query = $queryGenerator->getQuery(); $result = $db->query($query); $values = []; while ($value = $db->getSingleValue($result)) { $values[] = $value; } $this->set('picklistValues', $values); return $values; }
protected function getKeyMetricsWithCount() { global $log; $log->debug("Entering ./dashboards/KeyMetrics.php::getKeyMetricsWithCount"); global $current_user, $adb; $current_user = Users_Record_Model::getCurrentUserModel(); require_once 'modules/CustomView/ListViewTop.php'; $metriclists = getMetricList(); foreach ($metriclists as $key => $metriclist) { $metricresult = NULL; $queryGenerator = new QueryGenerator($metriclist['module'], $current_user); $queryGenerator->initForCustomViewById($metriclist['id']); if ($metriclist['module'] == "Calendar") { // For calendar we need to eliminate emails or else it will break in status empty condition $queryGenerator->addCondition('activitytype', "Emails", 'n', QueryGenerator::$AND); } $metricsql = $queryGenerator->getQuery(); $metricresult = $adb->query(Vtiger_Functions::mkCountQuery($metricsql)); if ($metricresult) { $rowcount = $adb->fetch_array($metricresult); $metriclists[$key]['count'] = $rowcount['count']; } } return $metriclists; }
private function convertMap2Array() { global $adb, $current_user; $xml = $this->getXMLContent(); if (isset($xml->records)) { foreach ($xml->records->record as $k => $v) { if (isset($v->action)) { $action = strtolower((string) $v->action); if (!in_array($action, $this->actions)) { $action = $this->default_action; } } else { $action = $this->default_action; } if (isset($v->id)) { $rs = $adb->pquery('select setype from vtiger_crmentity where crmid=? and deleted=0', array((int) $v->id)); if ($adb->num_rows($rs) == 1) { $recinfo = $adb->fetch_array($rs); $this->mapping[$action]['ids'][] = (int) $v->id; $this->mapping[$action][$recinfo['setype']][] = (int) $v->id; if (!in_array($recinfo['setype'], $this->mapping['modules'])) { $this->mapping['modules'][] = $recinfo['setype']; } } } else { $tabid = getTabid((string) $v->module); $ui4rs = $adb->pquery('select fieldname from vtiger_field where uitype=4 and tabid=?', array($tabid)); $ui4 = $adb->query_result($ui4rs, 0, 0); $queryGenerator = new QueryGenerator((string) $v->module, $current_user); $queryGenerator->setFields(array('id')); $queryGenerator->addCondition($ui4, (string) $v->value, 'e'); $query = $queryGenerator->getQuery(); $idrs = $adb->pquery($query, array()); if ($idrs and $adb->num_rows($idrs) > 0) { $id = $adb->query_result($idrs, 0, 0); $this->mapping[$action]['ids'][] = (int) $id; $this->mapping[$action][(string) $v->module][] = (int) $id; if (!in_array($recinfo['setype'], $this->mapping['modules'])) { $this->mapping['modules'][] = $recinfo['setype']; } } } } } }
/** * Function to search emails for send email * @param <String> $searchValue * @return <Array> Result of searched emails */ public function searchEmails($searchValue) { $emailsResult = array(); $db = PearDatabase::getInstance(); $currentUserModel = Users_Record_Model::getCurrentUserModel(); $emailSupportedModulesList = $this->getEmailRelatedModules(); foreach ($emailSupportedModulesList as $moduleName) { $searchFields = array(); $moduleModel = Vtiger_Module_Model::getInstance($moduleName); $emailFieldModels = $moduleModel->getFieldsByType('email'); foreach ($emailFieldModels as $fieldName => $fieldModel) { if ($fieldModel->isViewable()) { $searchFields[] = $fieldName; } } $emailFields = $searchFields; $nameFields = $moduleModel->getNameFields(); foreach ($nameFields as $fieldName) { $fieldModel = Vtiger_Field_Model::getInstance($fieldName, $moduleModel); if ($fieldModel->isViewable()) { $searchFields[] = $fieldName; } } if ($emailFields) { $moduleInstance = CRMEntity::getInstance($moduleName); $queryGenerator = new QueryGenerator($moduleName, $currentUserModel); $listFields = $searchFields; $listFields[] = 'id'; $queryGenerator->setFields($listFields); //Opensource fix for showing up deleted records on email search $queryGenerator->startGroup(""); foreach ($searchFields as $key => $emailField) { $queryGenerator->addCondition($emailField, trim($searchValue), 'c', 'OR'); } $queryGenerator->endGroup(); $result = $db->pquery($queryGenerator->getQuery(), array()); $numOfRows = $db->num_rows($result); for ($i = 0; $i < $numOfRows; $i++) { $row = $db->query_result_rowdata($result, $i); foreach ($emailFields as $emailField) { $emailFieldValue = $row[$emailField]; if ($emailFieldValue) { $recordLabel = getEntityFieldNameDisplay($moduleName, $nameFields, $row); if (strpos($emailFieldValue, $searchValue) !== false || strpos($recordLabel, $searchValue) !== false) { $emailsResult[vtranslate($moduleName, $moduleName)][$row[$moduleInstance->table_index]][] = array('value' => $emailFieldValue, 'label' => $recordLabel . ' <b>(' . $emailFieldValue . ')</b>'); } } } } } } return $emailsResult; }
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; }
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; }
/** * @param String $term: search term * @param String $filter: operator to use: eq, neq, startswith, endswith, contains * @param String $searchinmodule: valid module to search in * @param String $fields: comma separated list of fields to search in * @param String $returnfields: comma separated list of fields to return as result, if empty $fields will be returned * @param Number $limit: maximum number of values to return * @param Users $user * @return Array values found: crmid => array($returnfields) */ function getFieldAutocomplete($term, $filter, $searchinmodule, $fields, $returnfields, $limit, $user) { global $current_user, $log, $adb, $default_charset; $respuesta = array(); if (empty($searchinmodule) or empty($fields)) { return $respuesta; } if (!(vtlib_isModuleActive($searchinmodule) and isPermitted($searchinmodule, 'DetailView'))) { return $respuesta; } if (empty($returnfields)) { $returnfields = $fields; } if (empty($limit)) { $limit = 30; } // hard coded default if (empty($term)) { $term = '%'; $op = 'like'; } else { switch ($filter) { case 'eq': $op = 'e'; break; case 'neq': $op = 'n'; break; case 'startswith': $op = 's'; break; case 'endswith': $op = 'ew'; break; case 'contains': $op = 'c'; break; default: $op = 'e'; break; } } $current_user = VTWS_PreserveGlobal::preserveGlobal('current_user', $user); $smod = new $searchinmodule(); $sindex = $smod->table_index; $queryGenerator = new QueryGenerator($searchinmodule, $current_user); $sfields = explode(',', $fields); $rfields = explode(',', $returnfields); $flds = array_unique(array_merge($rfields, $sfields, array('id'))); $queryGenerator->setFields($flds); foreach ($sfields as $sfld) { $queryGenerator->addCondition($sfld, $term, $op); } $query = $queryGenerator->getQuery(); $rsemp = $adb->query($query); global $log; $log->fatal($rsemp); $wsid = vtyiicpng_getWSEntityId($searchinmodule); while ($emp = $adb->fetch_array($rsemp)) { $rsp = array(); foreach ($rfields as $rf) { $rsp[$rf] = html_entity_decode($emp[$rf], ENT_QUOTES, $default_charset); } $respuesta[] = array('crmid' => $wsid . $emp[$sindex], 'crmfields' => $rsp); if (count($respuesta) >= $limit) { break; } } VTWS_PreserveGlobal::flush(); return $respuesta; }
/** * Function to display the Search Results * @param Vtiger_Request $request */ function showSearchResults(Vtiger_Request $request) { $db = PearDatabase::getInstance(); $viewer = $this->getViewer($request); $moduleName = $request->getModule(); $advFilterList = $request->get('advfilterlist'); //used to show the save modify filter option $isAdvanceSearch = false; $matchingRecords = array(); if (is_array($advFilterList) && count($advFilterList) > 0) { $isAdvanceSearch = true; $user = Users_Record_Model::getCurrentUserModel(); $queryGenerator = new QueryGenerator($moduleName, $user); $queryGenerator->setFields(array('id')); vimport('~~/modules/CustomView/CustomView.php'); $customView = new CustomView($moduleName); $dateSpecificConditions = $customView->getStdFilterConditions(); foreach ($advFilterList as $groupindex => $groupcolumns) { $filtercolumns = $groupcolumns['columns']; if (count($filtercolumns) > 0) { $queryGenerator->startGroup(''); foreach ($filtercolumns as $index => $filter) { $nameComponents = explode(':', $filter['columnname']); if (empty($nameComponents[2]) && $nameComponents[1] == 'crmid' && $nameComponents[0] == 'vtiger_crmentity') { $name = $queryGenerator->getSQLColumn('id'); } else { $name = $nameComponents[2]; } if (($nameComponents[4] == 'D' || $nameComponents[4] == 'DT') && in_array($filter['comparator'], $dateSpecificConditions)) { $filter['stdfilter'] = $filter['comparator']; $valueComponents = explode(',', $filter['value']); if ($filter['comparator'] == 'custom') { $filter['startdate'] = DateTimeField::convertToDBFormat($valueComponents[0]); $filter['enddate'] = DateTimeField::convertToDBFormat($valueComponents[1]); } $dateFilterResolvedList = $customView->resolveDateFilterValue($filter); $value[] = $queryGenerator->fixDateTimeValue($name, $dateFilterResolvedList['startdate']); $value[] = $queryGenerator->fixDateTimeValue($name, $dateFilterResolvedList['enddate'], false); $queryGenerator->addCondition($name, $value, 'BETWEEN'); } else { $queryGenerator->addCondition($name, $filter['value'], $filter['comparator']); } $columncondition = $filter['column_condition']; if (!empty($columncondition) && array_key_exists($index + 1, $filtercolumns)) { $queryGenerator->addConditionGlue($columncondition); } } $queryGenerator->endGroup(); $groupConditionGlue = $groupcolumns['condition']; if (!empty($groupConditionGlue)) { $queryGenerator->addConditionGlue($groupConditionGlue); } } } $query = $queryGenerator->getQuery(); //Remove the ordering for now to improve the speed //$query .= ' ORDER BY createdtime DESC'; $result = $db->pquery($query, array()); $rows = $db->num_rows($result); for ($i = 0; $i < $rows; ++$i) { $row = $db->query_result_rowdata($result, $i); $recordInstance = Vtiger_Record_Model::getInstanceById($row[0]); $moduleName = $recordInstance->getModuleName(); $matchingRecords[$moduleName][$row[0]] = $recordInstance; } $viewer->assign('SEARCH_MODULE', $moduleName); } else { $searchKey = $request->get('value'); $searchModule = false; if ($request->get('searchModule')) { $searchModule = $request->get('searchModule'); } $viewer->assign('SEARCH_KEY', $searchKey); $viewer->assign('SEARCH_MODULE', $searchModule); $matchingRecords = Vtiger_Record_Model::getSearchResult($searchKey, $searchModule); } $matchingRecordsList = array(); if ($matchingRecords[$moduleName]) { $matchingRecordsList[$moduleName] = $matchingRecords[$moduleName]; } foreach ($matchingRecords as $module => $recordModelsList) { $matchingRecordsList[$module] = $recordModelsList; } $viewer->assign('MODULE', $moduleName); $viewer->assign('MATCHING_RECORDS', $matchingRecordsList); $viewer->assign('IS_ADVANCE_SEARCH', $isAdvanceSearch); echo $viewer->view('UnifiedSearchResults.tpl', '', true); }
$queryGenerator = new QueryGenerator('Contacts', $current_user); $queryGenerator->setFields(array('id', 'firstname')); $queryGenerator->addCondition('firstname', 'joe', 'e'); $queryGenerator->addCondition('id', '133', 'n', $queryGenerator::$AND); $query = $queryGenerator->getQuery(); echo "{$query}<br>"; testquery($query); $queryGenerator = new QueryGenerator('Accounts', $current_user); $queryGenerator->setFields(array('id', 'accountname')); $queryGenerator->addCondition('id', '133', 'n', $queryGenerator::$AND); $query = $queryGenerator->getQuery(); echo "{$query}<br>"; testquery($query); $queryGenerator = new QueryGenerator('Contacts', $current_user); $queryGenerator->setFields(array('id', 'firstname')); $queryGenerator->addCondition('assigned_user_id', 'Administrator', 'e'); $query = $queryGenerator->getQuery(); echo "{$query}<br>"; testquery($query); echo "<h2>exists condition</h2>"; $queryGenerator = new QueryGenerator('Contacts', $current_user); $queryGenerator->setFields(array('id', 'accountname', 'firstname')); $queryGenerator->addReferenceModuleFieldCondition('Accounts', 'account_id', 'accountname', 'EDFG Group Limited', 'exists'); $query = $queryGenerator->getQuery(); echo "{$query}<br>"; testquery($query); echo "<h2>Query with smownerid of rel module</h2>"; $queryGenerator = new QueryGenerator("Contacts", $current_user); $queryGenerator->setFields(array('id', 'accountname', 'Accounts.assigned_user_id')); $queryGenerator->addReferenceModuleFieldCondition('Accounts', 'account_id', 'accountname', 'EDFG Group Limited', 'exists'); $query = $queryGenerator->getQuery();
} if (!empty($stfields['stime'])) { $queryFields[] = $stfields['stime']; } if (!empty($stfields['etime'])) { $queryFields[] = $stfields['etime']; } if (isset($stfields['subject'])) { $descflds = explode(',', $stfields['subject']); foreach ($descflds as $dfld) { $queryFields[] = $dfld; } } $queryGenerator->setFields($queryFields); if ($record != "") { $queryGenerator->addCondition('id', $record, 'e', $queryGenerator::$AND); } else { $dtflds = getDateFieldsOfModule($modtab[$activitytypeid]); $queryGenerator->startGroup(); foreach ($dtflds as $field) { $queryGenerator->addCondition($field, array(0 => $start_date, 1 => $end_date), 'bw', $queryGenerator::$OR); } $queryGenerator->startGroup('OR'); $queryGenerator->addCondition($stfields['start'], $start_date, 'b'); $queryGenerator->addCondition($stfields['end'], $end_date, 'a', $queryGenerator::$AND); $queryGenerator->endGroup(); $queryGenerator->endGroup(); $queryGenerator->addCondition('assigned_user_id', getUserFullName($userid), 'e', $queryGenerator::$AND); if (count($Event_Status) > 0) { $evuniq = array_diff(array('Held', 'Not Held', 'Planned'), array_unique($Event_Status)); $encompas_group = false;
/** * Function to display the Search Results * @param Vtiger_Request $request */ function showSearchResults(Vtiger_Request $request) { $db = PearDatabase::getInstance(); $viewer = $this->getViewer($request); $moduleName = $request->getModule(); $advFilterList = $request->get('advfilterlist'); //used to show the save modify filter option $isAdvanceSearch = false; $matchingRecords = array(); if (is_array($advFilterList) && count($advFilterList) > 0) { $isAdvanceSearch = true; $user = Users_Record_Model::getCurrentUserModel(); $queryGenerator = new QueryGenerator($moduleName, $user); $queryGenerator->setFields(['id']); vimport('~modules/CustomView/CustomView.php'); $customView = new CustomView($moduleName); $dateSpecificConditions = $customView->getStdFilterConditions(); foreach ($advFilterList as $groupindex => $groupcolumns) { $filtercolumns = $groupcolumns['columns']; if (count($filtercolumns) > 0) { $queryGenerator->startGroup(''); foreach ($filtercolumns as $index => $filter) { $nameComponents = explode(':', $filter['columnname']); if (empty($nameComponents[2]) && $nameComponents[1] == 'crmid' && $nameComponents[0] == 'vtiger_crmentity') { $name = $queryGenerator->getSQLColumn('id'); } else { $name = $nameComponents[2]; } if (($nameComponents[4] == 'D' || $nameComponents[4] == 'DT') && in_array($filter['comparator'], $dateSpecificConditions)) { $filter['stdfilter'] = $filter['comparator']; $valueComponents = explode(',', $filter['value']); if ($filter['comparator'] == 'custom') { $filter['startdate'] = DateTimeField::convertToDBFormat($valueComponents[0]); $filter['enddate'] = DateTimeField::convertToDBFormat($valueComponents[1]); } $dateFilterResolvedList = $customView->resolveDateFilterValue($filter); $value[] = $queryGenerator->fixDateTimeValue($name, $dateFilterResolvedList['startdate']); $value[] = $queryGenerator->fixDateTimeValue($name, $dateFilterResolvedList['enddate'], false); $queryGenerator->addCondition($name, $value, 'BETWEEN'); } else { $queryGenerator->addCondition($name, $filter['value'], $filter['comparator']); } $columncondition = $filter['column_condition']; if (!empty($columncondition) && array_key_exists($index + 1, $filtercolumns)) { $queryGenerator->addConditionGlue($columncondition); } } $queryGenerator->endGroup(); $groupConditionGlue = $groupcolumns['condition']; if (!empty($groupConditionGlue)) { $queryGenerator->addConditionGlue($groupConditionGlue); } } } $query = $queryGenerator->getQuery(); //Remove the ordering for now to improve the speed //$query .= ' ORDER BY createdtime DESC'; $result = $db->query($query); while ($row = $db->fetch_array($result)) { $recordInstance = Vtiger_Record_Model::getInstanceById(current($row)); $moduleName = $recordInstance->getModuleName(); $recordInstance->set('permitted', true); $matchingRecords[$moduleName][current($row)] = $recordInstance; } $viewer->assign('SEARCH_MODULE', $moduleName); } else { $searchKey = $request->get('value'); $searchModule = false; if ($request->get('searchModule')) { $searchModule = $request->get('searchModule'); } $viewer->assign('SEARCH_KEY', $searchKey); $viewer->assign('SEARCH_MODULE', $searchModule); $matchingRecords = Vtiger_Record_Model::getSearchResult($searchKey, $searchModule, $request->get('limit')); } $recordsList = $matchingRecordsList = []; if ($matchingRecords[$moduleName]) { $matchingRecordsList[$moduleName] = $matchingRecords[$moduleName]; } foreach ($matchingRecords as $module => $recordModelsList) { $matchingRecordsList[$module] = $recordModelsList; } if ($request->get('html') == 'true') { $viewer->assign('MODULE', $moduleName); $viewer->assign('MATCHING_RECORDS', $matchingRecordsList); $viewer->assign('IS_ADVANCE_SEARCH', $isAdvanceSearch); echo $viewer->view('UnifiedSearchResults.tpl', '', true); } else { foreach ($matchingRecordsList as $module => $modules) { foreach ($modules as $recordID => $recordModel) { $label = decode_html($recordModel->getName()); $label .= ' (' . Vtiger_Functions::getOwnerRecordLabel($recordModel->get('smownerid')) . ')'; if (!$recordModel->get('permitted')) { $label .= ' <span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span>'; } $recordsList[] = ['id' => $recordID, 'module' => $module, 'category' => vtranslate($module, $module), 'label' => $label, 'permitted' => $recordModel->get('permitted')]; } } $response = new Vtiger_Response(); $response->setResult($recordsList); $response->emit(); } }
function getRelatedAccountContact($entityid, $module = '') { global $adb, $log, $current_user; if ($module == '' or $module != 'Accounts' and $module != 'Contacts') { if (GlobalVariable::getVariable('B2B', '1')) { $module = 'Accounts'; } else { $module = 'Contacts'; } } if (strpos($entityid, 'x') > 0 and !is_numeric($entityid)) { list($ent, $crmid) = explode('x', $entityid); } else { $crmid = $entityid; } $acid = 0; if (is_numeric($crmid)) { $setype = getSalesEntityType($crmid); switch ($setype) { case 'Accounts': $acid = $crmid; break; case 'Contacts': if ($module == 'Contacts') { $acid = $crmid; } else { $rspot = $adb->pquery('select accountid from vtiger_contactdetails where contactid=?', array($crmid)); $acid = $adb->query_result($rspot, 0, 'accountid'); } break; case 'Potentials': $rspot = $adb->pquery("select related_to from vtiger_potential where potentialid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'related_to'); break; case 'HelpDesk': $rspot = $adb->pquery("select parent_id from vtiger_troubletickets where ticketid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'parent_id'); break; case 'Quotes': $rspot = $adb->pquery("select accountid,contactid from vtiger_quotes where quoteid=?", array($crmid)); if ($module == 'Accounts') { $acid = $adb->query_result($rspot, 0, 'accountid'); } else { $acid = $adb->query_result($rspot, 0, 'contactid'); } break; case 'SalesOrder': $rspot = $adb->pquery("select accountid,contactid from vtiger_salesorder where salesorderid=?", array($crmid)); if ($module == 'Accounts') { $acid = $adb->query_result($rspot, 0, 'accountid'); } else { $acid = $adb->query_result($rspot, 0, 'contactid'); } break; case 'PurchaseOrder': $rspot = $adb->pquery("select contactid from vtiger_purchaseorder where purchaseorderid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'contactid'); break; case 'Invoice': $rspot = $adb->pquery("select accountid,contactid from vtiger_invoice where invoiceid=?", array($crmid)); if ($module == 'Accounts') { $acid = $adb->query_result($rspot, 0, 'accountid'); } else { $acid = $adb->query_result($rspot, 0, 'contactid'); } break; case 'InventoryDetails': $rspot = $adb->pquery("select account_id,contact_id from vtiger_inventorydetails where inventorydetailsid=?", array($crmid)); if ($module == 'Accounts') { $acid = $adb->query_result($rspot, 0, 'account_id'); } else { $acid = $adb->query_result($rspot, 0, 'contact_id'); } break; case 'ServiceContracts': $rspot = $adb->pquery("select sc_related_to from vtiger_servicecontracts where servicecontractsid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'sc_related_to'); break; case 'Assets': $rspot = $adb->pquery("select account from vtiger_assets where assetsid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'account'); break; case 'ProjectMilestone': $rspot = $adb->pquery("select linktoaccountscontacts\n\t\t\t\tfrom vtiger_project\n\t\t\t\tinner join vtiger_projectmilestone on vtiger_project.projectid = vtiger_projectmilestone.projectid\n\t\t\t\twhere projectmilestoneid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts'); break; case 'ProjectTask': $rspot = $adb->pquery("select linktoaccountscontacts\n\t\t\t\tfrom vtiger_project\n\t\t\t\tinner join vtiger_projecttask on vtiger_project.projectid = vtiger_projecttask.projectid\n\t\t\t\twhere projecttaskid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts'); break; case 'Project': $rspot = $adb->pquery("select linktoaccountscontacts from vtiger_project where projectid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts'); break; case 'CobroPago': $rspot = $adb->pquery("select parent_id from vtiger_cobropago where cobropagoid=?", array($crmid)); $acid = $adb->query_result($rspot, 0, 'parent_id'); break; case 'Calendar': case 'Events': if ($module == 'Accounts') { $rspot = $adb->pquery("select crmid from vtiger_seactivityrel where activityid=?", array($crmid)); if ($rspot and $adb->num_rows($rspot) > 0) { $acid = $adb->query_result($rspot, 0, 'crmid'); } } else { $rspot = $adb->pquery("select contactid from vtiger_cntactivityrel where activityid=?", array($crmid)); if ($rspot and $adb->num_rows($rspot) > 0) { $acid = $adb->query_result($rspot, 0, 'contactid'); } } break; default: // we look for uitype 10 $rsfld = $adb->pquery('SELECT fieldname from vtiger_fieldmodulerel INNER JOIN vtiger_field on vtiger_field.fieldid=vtiger_fieldmodulerel.fieldid WHERE module=? and relmodule=?', array($setype, $module)); if ($rsfld and $adb->num_rows($rsfld) > 0) { $fname = $adb->query_result($rsfld, 0, 'fieldname'); $queryGenerator = new QueryGenerator($setype, $current_user); $queryGenerator->setFields(array($fname)); $queryGenerator->addCondition('id', $crmid, 'e'); $query = $queryGenerator->getQuery(); $rspot = $adb->pquery($query, array()); $acid = $adb->query_result($rspot, 0, $fname); } } } if ($acid != 0) { $actype = getSalesEntityType($acid); if ($actype != $module) { $acid = 0; } } return $acid; }
function transferForAddIntoTitle($type, $row, $CD) { global $log, $current_user, $adb; list($CD['fieldname'], $void) = explode(':', $CD['fieldname']); if ($CD["uitype"] == "66") { $Col_Field = array($CD["fieldname"] => $row["parent_id"]); } else { $Col_Field = array($CD["fieldname"] => $row[$CD["columnname"]]); } if ($CD["fieldname"] == "duration_hours") { $Col_Field["duration_minutes"] = $row["duration_minutes"]; } if ($CD["fieldname"] == "contact_id") { $Col_Field["contact_id"] = getAssignedContactsForEvent($row["crmid"]); $CD["uitype"] = "1"; } if ($CD['module'] == 'Calendar' or $CD['module'] == 'Events') { $Cal_Data = getDetailViewOutputHtml($CD['uitype'], $CD['fieldname'], $CD['fieldlabel'], $Col_Field, '2', $calendar_tabid, 'Calendar'); $trmodule = 'Calendar'; } else { $queryGenerator = new QueryGenerator($CD['module'], $current_user); $queryGenerator->setFields(array($CD['columnname'])); $queryGenerator->addCondition('id', $row['parent_id'], 'e', $queryGenerator::$AND); $rec_query = $queryGenerator->getQuery(); $recinfo = $adb->pquery($rec_query, array()); $Cal_Data = array(); $Cal_Data[0] = getTranslatedString($CD['fieldlabel'], $CD['module']); $Cal_Data[1] = $adb->query_result($recinfo, 0, $CD['columnname']); $trmodule = $CD['module']; } if ($CD["uitype"] == "15") { $value = getTranslatedString($Cal_Data[1], $trmodule); } else { $value = $Cal_Data[1]; } if ($type == "1") { return $Cal_Data[1]; } else { // return "<br><b>".$Cal_Data[0]."</b>: ".$value; return '<table><tr><td><b>' . $Cal_Data[0] . ':</b></td><td onmouseover="vtlib_listview.trigger(\'cell.onmouseover\', $(this))" onmouseout="vtlib_listview.trigger(\'cell.onmouseout\', $(this))">' . $value . '</td></tr></table>'; } }
/** * * @param mixed $value * @param String $operator * @param WebserviceField $field */ private function getConditionValue($value, $operator, $field) { $operator = strtolower($operator); $db = PearDatabase::getInstance(); $noncommaSeparatedFieldTypes = array('currency', 'percentage', 'double', 'integer', 'number'); if (in_array($field->getFieldDataType(), $noncommaSeparatedFieldTypes)) { if (is_array($value)) { $valueArray = $value; } else { $valueArray = array($value); } // if ($field->getFieldDataType() == 'multipicklist' && in_array($operator, array('e', 'n'))) { // $valueArray = getCombinations($valueArray); // foreach ($valueArray as $key => $value) { // $valueArray[$key] = ltrim($value, ' |##| '); // } // } } elseif (is_string($value)) { $valueArray = explode(',', $value); } elseif (is_array($value)) { $valueArray = $value; } else { $valueArray = array($value); } $sql = array(); if ($operator == 'exists') { global $current_user, $adb; $mid = getTabModuleName($field->getTabId()); $qg = new QueryGenerator($mid, $current_user); $qg->addCondition($field->getFieldName(), $value, 'e'); $sql[] = 'SELECT EXISTS(SELECT 1 ' . $qg->getFromClause() . $qg->getWhereClause() . ')'; return $sql; } if ($operator == 'i' or $operator == 'in' or $operator == 'ni' or $operator == 'nin') { $vals = array_map(array($db, 'quote'), $valueArray); $sql[] = (($operator == 'ni' or $operator == 'nin') ? ' NOT ' : '') . 'IN (' . implode(',', $vals) . ')'; return $sql; } if ($operator == 'between' || $operator == 'bw' || $operator == 'notequal') { if ($field->getFieldName() == 'birthday') { $valueArray[0] = getValidDBInsertDateTimeValue($valueArray[0]); $valueArray[1] = getValidDBInsertDateTimeValue($valueArray[1]); $sql[] = "BETWEEN DATE_FORMAT(" . $db->quote($valueArray[0]) . ", '%m%d') AND " . "DATE_FORMAT(" . $db->quote($valueArray[1]) . ", '%m%d')"; } else { if ($this->isDateType($field->getFieldDataType())) { $valueArray[0] = getValidDBInsertDateTimeValue($valueArray[0]); $valueArray[1] = getValidDBInsertDateTimeValue($valueArray[1]); } $sql[] = "BETWEEN " . $db->quote($valueArray[0]) . " AND " . $db->quote($valueArray[1]); } return $sql; } $yes = strtolower(getTranslatedString('yes')); $no = strtolower(getTranslatedString('no')); foreach ($valueArray as $value) { if (!$this->isStringType($field->getFieldDataType())) { $value = trim($value); } if ($operator == 'empty' || $operator == 'y') { $sql[] = sprintf("IS NULL OR %s = ''", $this->getSQLColumn($field->getFieldName())); continue; } if ($operator == 'ny') { $sql[] = sprintf("IS NOT NULL AND %s != ''", $this->getSQLColumn($field->getFieldName())); continue; } if (strtolower(trim($value)) == 'null' || trim($value) == '' && !$this->isStringType($field->getFieldDataType()) && ($operator == 'e' || $operator == 'n')) { if ($operator == 'e') { $sql[] = "IS NULL"; continue; } $sql[] = "IS NOT NULL"; continue; } elseif ($field->getFieldDataType() == 'boolean') { $value = strtolower($value); if ($value == 'yes' or $value == $yes) { $value = 1; } elseif ($value == 'no' or $value == $no) { $value = 0; } } elseif ($this->isDateType($field->getFieldDataType())) { $value = getValidDBInsertDateTimeValue($value); if (empty($value)) { $sql[] = 'IS NULL or ' . $field->getTableName() . '.' . $field->getFieldName() . " = ''"; return $sql; } } elseif ($field->getFieldDataType() == 'picklist' || $field->getFieldDataType() == 'multipicklist') { if (!isValueInPicklist($value, $field->getFieldName())) { $value = getTranslationKeyFromTranslatedValue($this->module, $value); } } else { if ($field->getFieldDataType() === 'currency') { $uiType = $field->getUIType(); if ($uiType == 72) { $value = CurrencyField::convertToDBFormat($value, null, true); } elseif ($uiType == 71) { $value = CurrencyField::convertToDBFormat($value, $this->user); } } } if ($field->getFieldName() == 'birthday' && !$this->isRelativeSearchOperators($operator)) { $value = "DATE_FORMAT(" . $db->quote($value) . ", '%m%d')"; } else { $value = $db->sql_escape_string($value); } if (trim($value) == '' && ($operator == 's' || $operator == 'ew' || $operator == 'c') && ($this->isStringType($field->getFieldDataType()) || $field->getFieldDataType() == 'picklist' || $field->getFieldDataType() == 'multipicklist')) { $sql[] = "LIKE ''"; continue; } if (trim($value) == '' && $operator == 'k' && $this->isStringType($field->getFieldDataType())) { $sql[] = "NOT LIKE ''"; continue; } switch ($operator) { case 'e': $sqlOperator = "="; break; case 'n': $sqlOperator = "<>"; break; case 's': $sqlOperator = "LIKE"; $value = "{$value}%"; break; case 'ew': $sqlOperator = "LIKE"; $value = "%{$value}"; break; case 'c': $sqlOperator = "LIKE"; $value = "%{$value}%"; break; case 'k': $sqlOperator = "NOT LIKE"; $value = "%{$value}%"; break; case 'l': $sqlOperator = "<"; break; case 'g': $sqlOperator = ">"; break; case 'm': $sqlOperator = "<="; break; case 'h': $sqlOperator = ">="; break; case 'a': $sqlOperator = ">"; break; case 'b': $sqlOperator = "<"; break; } if (!$this->isNumericType($field->getFieldDataType()) && ($field->getFieldName() != 'birthday' || $field->getFieldName() == 'birthday' && $this->isRelativeSearchOperators($operator))) { $value = "'{$value}'"; } if ($this->isNumericType($field->getFieldDataType()) && empty($value)) { $value = '0'; } $sql[] = "{$sqlOperator} {$value}"; } return $sql; }
$term = $filter['filters'][0]['value']; $op = isset($filter['filters'][0]['operator']) ? $filter['filters'][0]['operator'] : 'startswith'; } else { $term = vtlib_purify($_REQUEST['term']); $op = empty($filter) ? 'startswith' : $filter; } $ret = getReferenceAutocomplete($term, $op, $searchinmodule, $limit, $current_user); break; case 'getFieldValuesFromRecord': $crmid = vtlib_purify($_REQUEST['getFieldValuesFrom']); $module = getSalesEntityType($crmid); $fields = vtlib_purify($_REQUEST['getTheseFields']); $fields = explode(',', $fields); $queryGenerator = new QueryGenerator($module, $current_user); $queryGenerator->setFields($fields); $queryGenerator->addCondition('id', $crmid, 'e'); $query = $queryGenerator->getQuery(); $queryres = $adb->pquery($query, array()); if ($adb->num_rows($queryres) > 0) { $col = 0; foreach ($fields as $field) { $ret[$field] = $adb->query_result($queryres, 0, $col++); } } break; case 'getEmailTemplateDetails': $emltplid = vtlib_purify($_REQUEST['templateid']); $emltpl = getTemplateDetails($emltplid); $ret = array(); if (count($emltpl) > 0) { $ret['subject'] = $emltpl[2];