public static function getModuleMeta($moduleName, $user)
 {
     if (empty(self::$_cached_module_meta[$moduleName][$user->id])) {
         $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $user);
         self::$_cached_module_meta[$moduleName][$user->id] = $moduleHandler->getMeta();
     }
     return self::$_cached_module_meta[$moduleName][$user->id];
 }
 public function translateReferenceFieldNamesToIds($entityRecords, $user)
 {
     $entityRecordList = array();
     foreach ($entityRecords as $index => $record) {
         $entityRecordList[$record['module']][$index] = $record;
     }
     foreach ($entityRecordList as $module => $records) {
         $handler = vtws_getModuleHandlerFromName($module, $user);
         $meta = $handler->getMeta();
         $referenceFieldDetails = $meta->getReferenceFieldDetails();
         foreach ($referenceFieldDetails as $referenceFieldName => $referenceModuleDetails) {
             $recordReferenceFieldNames = array();
             foreach ($records as $index => $recordDetails) {
                 if (!empty($recordDetails[$referenceFieldName])) {
                     $recordReferenceFieldNames[] = $recordDetails[$referenceFieldName];
                 }
             }
             $entityNameIds = wsapp_getRecordEntityNameIds(array_values($recordReferenceFieldNames), $referenceModuleDetails, $user);
             if (is_array($entityNameIds)) {
                 $entityNameIds = array_change_key_case($entityNameIds, CASE_LOWER);
             }
             foreach ($records as $index => $recordInfo) {
                 if (!empty($entityNameIds[strtolower($recordInfo[$referenceFieldName])])) {
                     $recordInfo[$referenceFieldName] = $entityNameIds[strtolower($recordInfo[$referenceFieldName])];
                 } else {
                     if ($referenceFieldName == 'account_id') {
                         if ($recordInfo[$referenceFieldName] != NULL) {
                             $element['accountname'] = $recordInfo[$referenceFieldName];
                             $element['assigned_user_id'] = vtws_getWebserviceEntityId('Users', $user->id);
                             $element['module'] = "Accounts";
                             $createRecord = array($element);
                             $createRecord = $this->fillNonExistingMandatoryPicklistValues($createRecord);
                             $createRecord = $this->fillMandatoryFields($createRecord, $user);
                             foreach ($createRecord as $key => $record) {
                                 vtws_create($record['module'], $record, $user);
                             }
                             $entityNameIds = wsapp_getRecordEntityNameIds(array_values($recordReferenceFieldNames), $referenceModuleDetails, $user);
                             $recordInfo[$referenceFieldName] = $entityNameIds[$recordInfo[$referenceFieldName]];
                         }
                     } else {
                         $recordInfo[$referenceFieldName] = "";
                     }
                 }
                 $records[$index] = $recordInfo;
             }
         }
         $entityRecordList[$module] = $records;
     }
     $crmRecords = array();
     foreach ($entityRecordList as $module => $entityRecords) {
         foreach ($entityRecords as $index => $record) {
             $crmRecords[$index] = $record;
         }
     }
     return $crmRecords;
 }
示例#3
0
 /**
  *
  * @param String:ModuleName $module
  * @return EntityMeta
  */
 public function getMeta($module, $user)
 {
     $db = PearDatabase::getInstance();
     if (empty($this->moduleMetaInfo[$module])) {
         $handler = vtws_getModuleHandlerFromName($module, $user);
         $meta = $handler->getMeta();
         $this->moduleMetaInfo[$module] = $meta;
     }
     return $this->moduleMetaInfo[$module];
 }
/**
 * Retrieve inventory record with LineItems
 */
function vtws_retrieve_inventory($id)
{
    $current_user = vglobal('current_user');
    $record = vtws_retrieve($id, $current_user);
    $handler = vtws_getModuleHandlerFromName('LineItem', $user);
    $id = vtws_getIdComponents($id);
    $id = $id[1];
    $inventoryLineItems = $handler->getAllLineItemForParent($id);
    $record['LineItems'] = $inventoryLineItems;
    return $record;
}
示例#5
0
 /**
  * creates an instance of Vtiger_ModuleMeta_Model
  * @param <String> $name - module name
  * @param <Object> $user - Users Object
  * @return Vtiger_ModuleMeta_Model
  */
 public static function getInstance($name, $user)
 {
     $self = new Vtiger_ModuleMeta_Model();
     $self->moduleName = $name;
     $self->user = $user;
     if (!empty(self::$_cached_module_meta[$name][$user->id])) {
         $self->webserviceMeta = self::$_cached_module_meta[$name][$user->id];
         return $self;
     }
     $handler = vtws_getModuleHandlerFromName($self->moduleName, $user);
     $self->webserviceMeta = $handler->getMeta();
     self::$_cached_module_meta[$name][$user->id] = $self->webserviceMeta;
     return $self;
 }
 function isAssignToChanged($moduleName, $recordId, $user)
 {
     $wsModuleName = $this->getWsModuleName($moduleName);
     $handler = vtws_getModuleHandlerFromName($wsModuleName, $user);
     $meta = $handler->getMeta();
     $moduleOwnerFields = $meta->getOwnerFields();
     $assignToChanged = false;
     $vtEntityDelta = new VTEntityDelta();
     foreach ($moduleOwnerFields as $ownerField) {
         $assignToChanged = $vtEntityDelta->hasChanged($moduleName, $recordId, $ownerField);
         if ($assignToChanged) {
             break;
         }
     }
     return $assignToChanged;
 }
	public function getAccessibleFields($moduleName) {
		global $current_user;

		if(empty(self::$_cached_module_meta[$moduleName][$current_user->id])) {
			$moduleHandler = vtws_getModuleHandlerFromName($moduleName, $current_user);
			self::$_cached_module_meta[$moduleName][$current_user->id] = $moduleHandler->getMeta();
		}
		$meta = self::$_cached_module_meta[$moduleName][$current_user->id];
		$moduleFields = $meta->getModuleFields();
		$accessibleFields = array();
		foreach($moduleFields as $fieldName => $fieldInstance) {
			if($fieldInstance->getPresence() === 1) {
				continue;
			}
			$accessibleFields[$fieldName] = $fieldInstance;
		}
		return $accessibleFields;
	}
示例#8
0
function wsapp_getRecordEntityNameIds($entityNames, $modules, $user)
{
    $entityMetaList = array();
    $db = PearDatabase::getInstance();
    if (empty($entityNames)) {
        return;
    }
    if (!is_array($entityNames)) {
        $entityNames = array($entityNames);
    }
    if (empty($modules)) {
        return array();
    }
    if (!is_array($modules)) {
        $modules = array($modules);
    }
    $entityNameIds = array();
    foreach ($modules as $moduleName) {
        if (empty($entityMetaList[$moduleName])) {
            $handler = vtws_getModuleHandlerFromName($moduleName, $user);
            $meta = $handler->getMeta();
            $entityMetaList[$moduleName] = $meta;
        }
        $meta = $entityMetaList[$moduleName];
        $nameFieldsArray = explode(",", $meta->getNameFields());
        if (count($nameFieldsArray) > 1) {
            $nameFields = "concat(" . implode(",' ',", $nameFieldsArray) . ")";
        } else {
            $nameFields = $nameFieldsArray[0];
        }
        $query = "SELECT " . $meta->getObectIndexColumn() . " as id,{$nameFields} as entityname FROM " . $meta->getEntityBaseTable() . " as moduleentity INNER JOIN vtiger_crmentity as crmentity WHERE {$nameFields} IN(" . generateQuestionMarks($entityNames) . ") AND crmentity.deleted=0 AND crmentity.crmid = moduleentity." . $meta->getObectIndexColumn() . "";
        $result = $db->pquery($query, $entityNames);
        $num_rows = $db->num_rows($result);
        for ($i = 0; $i < $num_rows; $i++) {
            $id = $db->query_result($result, $i, 'id');
            $entityName = $db->query_result($result, $i, 'entityname');
            $entityNameIds[decode_html($entityName)] = vtws_getWebserviceEntityId($moduleName, $id);
        }
    }
    return $entityNameIds;
}
示例#9
0
 static function lookupMailInVtiger($searchTerm, $user)
 {
     $handler = vtws_getModuleHandlerFromName('Emails', $user);
     $meta = $handler->getMeta();
     $moduleFields = $meta->getModuleFields();
     $parentIdFieldInstance = $moduleFields['parent_id'];
     $referenceModules = $parentIdFieldInstance->getReferenceList();
     $filteredResult = array();
     foreach ($referenceModules as $referenceModule) {
         $referenceModuleHandler = vtws_getModuleHandlerFromName($referenceModule, $user);
         $referenceModuleMeta = $referenceModuleHandler->getMeta();
         $referenceModuleEmailFields = $referenceModuleMeta->getEmailFields();
         $referenceModuleEntityFields = $referenceModuleMeta->getNameFields();
         $referenceModuleEntityFieldsArray = explode(',', $referenceModuleEntityFields);
         $searchFieldList = array_merge($referenceModuleEmailFields, $referenceModuleEntityFieldsArray);
         if (!empty($searchFieldList) && !empty($referenceModuleEmailFields)) {
             $searchFieldListString = implode(',', $referenceModuleEmailFields);
             $where = null;
             for ($i = 0; $i < count($searchFieldList); $i++) {
                 if ($i == count($searchFieldList) - 1) {
                     $where .= sprintf($searchFieldList[$i] . " like '%s'", $searchTerm);
                 } else {
                     $where .= sprintf($searchFieldList[$i] . " like '%s' or ", $searchTerm);
                 }
             }
             if (!empty($where)) {
                 $where = "WHERE {$where}";
             }
             $result = vtws_query("select {$searchFieldListString} from {$referenceModule} {$where};", $user);
             foreach ($result as $record) {
                 foreach ($searchFieldList as $searchField) {
                     if (!empty($record[$searchField])) {
                         $filteredResult[] = array('id' => $record[$searchField], 'name' => $record[$searchField] . " - " . getTranslatedString($referenceModule), 'record' => $record['id']);
                     }
                 }
             }
         }
     }
     return $filteredResult;
 }
示例#10
0
 /**
  * Create new Email record (and link to given record) including attachments
  * @global Users $current_user
  * @global PearDataBase $db
  * @param  MailManager_Message_Model $mailrecord
  * @param String $module
  * @param CRMEntity $linkfocus
  * @return Integer
  */
 public function __CreateNewEmail($mailrecord, $module, $linkfocus)
 {
     $currentUserModel = Users_Record_Model::getCurrentUserModel();
     $handler = vtws_getModuleHandlerFromName('Emails', $currentUserModel);
     $meta = $handler->getMeta();
     if ($meta->hasWriteAccess() != true) {
         return false;
     }
     $recordModel = Vtiger_Record_Model::getCleanInstance('Emails');
     $recordModel->set('subject', $mailrecord->_subject);
     if (!empty($module)) {
         $recordModel->set('parent_type', $module);
     }
     if (!empty($linkfocus->id)) {
         $recordModel->set('parent_id', "{$linkfocus->id}@-1|");
     }
     $recordModel->set('description', $mailrecord->getBodyHTML());
     $recordModel->set('assigned_user_id', $currentUserModel->get('id'));
     //Opensource fix mailmanager related data
     $recordModel->set('date_start', date('Y-m-d', $mailrecord->_date));
     $recordModel->set('time_start', date('H:i', $mailrecord->_date));
     $recordModel->set('email_flag', 'MailManager');
     $from = $mailrecord->_from[0];
     $to = $mailrecord->_to[0];
     $cc = !empty($mailrecord->_cc) ? implode(',', $mailrecord->_cc) : '';
     $bcc = !empty($mailrecord->_bcc) ? implode(',', $mailrecord->_bcc) : '';
     //emails field were restructured and to,bcc and cc field are JSON arrays
     $recordModel->set('from_email', $from);
     $recordModel->set('saved_toid', $to);
     $recordModel->set('ccmail', $cc);
     $recordModel->set('bccmail', $bcc);
     $recordModel->save();
     // TODO: Handle attachments of the mail (inline/file)
     $this->__SaveAttachements($mailrecord, 'Emails', $recordModel);
     return $recordModel->getId();
 }
示例#11
0
 function yy_r41()
 {
     global $adb;
     if (!$this->out['meta']) {
         $module = $this->out['moduleName'];
         $handler = vtws_getModuleHandlerFromName($module, $this->user);
         $objectMeta = $handler->getMeta();
         $this->out['meta'] = $objectMeta;
         $meta = $this->out['meta'];
         $fieldcol = $meta->getFieldColumnMapping();
         $columns = array();
         if (in_array('*', $this->out['column_list'])) {
             $columns = array_values($fieldcol);
         } elseif (!in_array('count(*)', array_map(strtolower, $this->out['column_list']))) {
             foreach ($this->out['column_list'] as $ind => $field) {
                 $columns[] = $fieldcol[$field];
             }
         }
         if ($this->out['where_condition']) {
             foreach ($this->out['where_condition']['column_names'] as $ind => $field) {
                 $columns[] = $fieldcol[$field];
             }
         }
         $tables = $this->getTables($this->out, $columns);
         if (!in_array($objectMeta->getEntityBaseTable(), $tables)) {
             $tables[] = $objectMeta->getEntityBaseTable();
         }
         $defaultTableList = $objectMeta->getEntityDefaultTableList();
         foreach ($defaultTableList as $tableName) {
             if (!in_array($tableName, $tables)) {
                 array_push($tables, $tableName);
             }
         }
         $firstTable = $objectMeta->getEntityBaseTable();
         $tabNameIndex = $objectMeta->getEntityTableIndexList();
         $firstIndex = $tabNameIndex[$firstTable];
         foreach ($tables as $ind => $table) {
             if ($firstTable != $table) {
                 if (!isset($tabNameIndex[$table]) && $table == "vtiger_crmentity") {
                     $this->out['defaultJoinConditions'] = $this->out['defaultJoinConditions'] . " LEFT JOIN {$table} ON {$firstTable}.{$firstIndex}={$table}.crmid";
                 } else {
                     $this->out['defaultJoinConditions'] = $this->out['defaultJoinConditions'] . " LEFT JOIN {$table} ON {$firstTable}.{$firstIndex}={$table}.{$tabNameIndex[$table]}";
                 }
             } else {
                 $this->out['tableName'] = $table;
             }
         }
     }
 }
 public function createEntityRecord($moduleName, $entityLabel)
 {
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleFields = $moduleMeta->getModuleFields();
     $mandatoryFields = $moduleMeta->getMandatoryFields();
     $entityNameFieldsString = $moduleMeta->getNameFields();
     $entityNameFields = explode(',', $entityNameFieldsString);
     $fieldData = array();
     foreach ($entityNameFields as $entityNameField) {
         $entityNameField = trim($entityNameField);
         if (in_array($entityNameField, $mandatoryFields)) {
             $fieldData[$entityNameField] = $entityLabel;
         }
     }
     foreach ($mandatoryFields as $mandatoryField) {
         if (empty($fieldData[$mandatoryField])) {
             $fieldInstance = $moduleFields[$mandatoryField];
             if ($fieldInstance->getFieldDataType() == 'owner') {
                 $fieldData[$mandatoryField] = $this->user->id;
             } else {
                 $defaultValue = $fieldInstance->getDefault();
                 if (!empty($defaultValue)) {
                     $fieldData[$mandatoryField] = $defaultValue;
                 } else {
                     $fieldData[$mandatoryField] = '????';
                 }
             }
         }
     }
     $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta);
     $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user);
     $focus = CRMEntity::getInstance($moduleName);
     $focus->updateMissingSeqNumber($moduleName);
     return $entityIdInfo;
 }
示例#13
0
 public function getWhereClause($onlyWhereQuery = false)
 {
     $current_user = vglobal('current_user');
     if (!empty($this->query) || !empty($this->whereClause)) {
         return $this->whereClause;
     }
     $deletedQuery = $this->meta->getEntityDeletedQuery();
     $sql = '';
     if (!empty($deletedQuery) && !$onlyWhereQuery) {
         $sql .= " WHERE {$deletedQuery}";
     }
     if ($this->conditionInstanceCount > 0) {
         $sql .= ' AND ';
     } elseif (empty($deletedQuery)) {
         $sql .= ' WHERE ';
     }
     $baseModule = $this->getModule();
     $moduleFieldList = $this->getModuleFields();
     $baseTable = $this->meta->getEntityBaseTable();
     $moduleTableIndexList = $this->meta->getEntityTableIndexList();
     $baseTableIndex = $moduleTableIndexList[$baseTable];
     $groupSql = $this->groupInfo;
     $fieldSqlList = array();
     foreach ($this->conditionals as $index => $conditionInfo) {
         $fieldName = $conditionInfo['name'];
         $field = $moduleFieldList[$fieldName];
         if (empty($field) || $conditionInfo['operator'] == 'None') {
             continue;
         }
         $fieldSql = '(';
         $fieldGlue = '';
         $valueSqlList = $this->getConditionValue($conditionInfo['value'], $conditionInfo['operator'], $field);
         $operator = strtolower($conditionInfo['operator']);
         if ($operator == 'between' && $this->isDateType($field->getFieldDataType())) {
             $start = explode(' ', $conditionInfo['value'][0]);
             if (count($start) == 2) {
                 $conditionInfo['value'][0] = getValidDBInsertDateTimeValue($start[0] . ' ' . $start[1]);
             }
             $end = explode(' ', $conditionInfo['values'][1]);
             // Dates will be equal for Today, Tomorrow, Yesterday.
             if (count($end) == 2) {
                 if ($start[0] == $end[0]) {
                     $dateTime = new DateTime($conditionInfo['value'][0]);
                     $nextDay = $dateTime->modify('+1 days');
                     $nextDay = $nextDay->format('Y-m-d H:i:s');
                     $values = explode(' ', $nextDay);
                     $conditionInfo['value'][1] = getValidDBInsertDateTimeValue($values[0]) . ' ' . $values[1];
                 } else {
                     $end = $conditionInfo['value'][1];
                     $dateObject = new DateTimeField($end);
                     $conditionInfo['value'][1] = $dateObject->getDBInsertDateTimeValue();
                 }
             }
         }
         if (!is_array($valueSqlList)) {
             $valueSqlList = array($valueSqlList);
         }
         foreach ($valueSqlList as $valueSql) {
             if (in_array($fieldName, $this->referenceFieldList)) {
                 if ($conditionInfo['operator'] == 'y') {
                     $columnName = $field->getColumnName();
                     $tableName = $field->getTableName();
                     // We are checking for zero since many reference fields will be set to 0 if it doest not have any value
                     $fieldSql .= "{$fieldGlue} {$tableName}.{$columnName} {$valueSql} OR {$tableName}.{$columnName} = '0'";
                     $fieldGlue = ' OR';
                 } else {
                     $moduleList = $this->referenceFieldInfoList[$fieldName];
                     foreach ($moduleList as $module) {
                         $nameFields = $this->moduleNameFields[$module];
                         $nameFieldList = explode(',', $nameFields);
                         $meta = $this->getMeta($module);
                         $columnList = array();
                         foreach ($nameFieldList as $column) {
                             if ($module == 'Users') {
                                 $instance = CRMEntity::getInstance($module);
                                 $referenceTable = $instance->table_name;
                                 if (count($this->ownerFields) > 0 || $this->getModule() == 'Quotes') {
                                     $referenceTable .= $fieldName;
                                 }
                             } else {
                                 $referenceField = $meta->getFieldByColumnName($column);
                                 $referenceTable = $referenceField->getTableName() . $fieldName;
                             }
                             if (isset($moduleTableIndexList[$referenceTable])) {
                                 $referenceTable = "{$referenceTable}{$fieldName}";
                             }
                             $columnList[$column] = "{$referenceTable}.{$column}";
                         }
                         if (count($columnList) > 1) {
                             $columnSql = getSqlForNameInDisplayFormat($columnList, $module);
                         } else {
                             $columnSql = implode('', $columnList);
                         }
                         $fieldSql .= "{$fieldGlue} trim({$columnSql}) {$valueSql}";
                         $fieldGlue = ' OR';
                     }
                 }
             } elseif (in_array($fieldName, $this->ownerFields)) {
                 if ($conditionInfo['operator'] == 'om') {
                     $fieldSql .= $fieldGlue . $field->getTableName() . '.' . $field->getColumnName() . " {$valueSql}";
                 } elseif ($fieldName == 'created_user_id') {
                     $concatSql = getSqlForNameInDisplayFormat(array('first_name' => "vtiger_users{$fieldName}.first_name", 'last_name' => "vtiger_users{$fieldName}.last_name"), 'Users');
                     $fieldSql .= "{$fieldGlue} (trim({$concatSql}) {$valueSql})";
                 } else {
                     $entityFields = Vtiger_Functions::getEntityModuleInfoFieldsFormatted('Users');
                     if (count($entityFields['fieldname']) > 1) {
                         $columns = [];
                         foreach ($entityFields['fieldname'] as $i => $fieldname) {
                             $columns[$fieldname] = $entityFields['tablename'] . '.' . $fieldname;
                         }
                         $concatSql = getSqlForNameInDisplayFormat($columns, 'Users');
                         $fieldSql .= "{$fieldGlue} (trim({$concatSql}) {$valueSql} OR " . "vtiger_groups.groupname {$valueSql})";
                     } else {
                         $columnSql = $entityFields['tablename'] . '.' . $entityFields['fieldname'];
                         $fieldSql .= "{$fieldGlue} (trim({$columnSql}) {$valueSql} OR " . "vtiger_groups.groupname {$valueSql})";
                     }
                 }
             } elseif ($field->getFieldDataType() == 'date' && ($baseModule == 'Events' || $baseModule == 'Calendar') && ($fieldName == 'date_start' || $fieldName == 'due_date')) {
                 $value = $conditionInfo['value'];
                 $operator = $conditionInfo['operator'];
                 if ($fieldName == 'date_start') {
                     $dateFieldColumnName = 'vtiger_activity.date_start';
                     $timeFieldColumnName = 'vtiger_activity.time_start';
                 } else {
                     $dateFieldColumnName = 'vtiger_activity.due_date';
                     $timeFieldColumnName = 'vtiger_activity.time_end';
                 }
                 if ($operator == 'bw') {
                     $values = explode(',', $value);
                     $startDateValue = explode(' ', $values[0]);
                     $endDateValue = explode(' ', $values[1]);
                     if (count($startDateValue) == 2 && count($endDateValue) == 2) {
                         $fieldSql .= " CAST(CONCAT({$dateFieldColumnName},' ',{$timeFieldColumnName}) AS DATETIME) {$valueSql}";
                     } else {
                         $fieldSql .= "{$dateFieldColumnName} {$valueSql}";
                     }
                 } else {
                     if (is_array($value)) {
                         $value = $value[0];
                     }
                     $values = explode(' ', $value);
                     if (count($values) == 2) {
                         $fieldSql .= "{$fieldGlue} CAST(CONCAT({$dateFieldColumnName},' ',{$timeFieldColumnName}) AS DATETIME) {$valueSql} ";
                     } else {
                         $fieldSql .= "{$fieldGlue} {$dateFieldColumnName} {$valueSql}";
                     }
                 }
             } elseif ($field->getFieldDataType() == 'datetime') {
                 $value = $conditionInfo['value'];
                 $operator = strtolower($conditionInfo['operator']);
                 if ($operator == 'bw') {
                     $values = explode(',', $value);
                     $startDateValue = explode(' ', $values[0]);
                     $endDateValue = explode(' ', $values[1]);
                     if ($startDateValue[1] == '00:00:00' && ($endDateValue[1] == '00:00:00' || $endDateValue[1] == '23:59:59')) {
                         $fieldSql .= "{$fieldGlue} CAST(" . $field->getTableName() . '.' . $field->getColumnName() . " AS DATE) {$valueSql}";
                     } else {
                         $fieldSql .= "{$fieldGlue} " . $field->getTableName() . '.' . $field->getColumnName() . ' ' . $valueSql;
                     }
                 } elseif ($operator == 'between' || $operator == 'notequal' || $operator == 'a' || $operator == 'b') {
                     $fieldSql .= "{$fieldGlue} " . $field->getTableName() . '.' . $field->getColumnName() . ' ' . $valueSql;
                 } else {
                     $values = explode(' ', $value);
                     if ($values[1] == '00:00:00') {
                         $fieldSql .= "{$fieldGlue} CAST(" . $field->getTableName() . '.' . $field->getColumnName() . " AS DATE) {$valueSql}";
                     } else {
                         $fieldSql .= "{$fieldGlue} " . $field->getTableName() . '.' . $field->getColumnName() . ' ' . $valueSql;
                     }
                 }
             } else {
                 if (($baseModule == 'Events' || $baseModule == 'Calendar') && ($field->getColumnName() == 'status' || $field->getColumnName() == 'eventstatus')) {
                     $otherFieldName = 'eventstatus';
                     if ($field->getColumnName() == 'eventstatus') {
                         $otherFieldName = 'taskstatus';
                     }
                     $otherField = $moduleFieldList[$otherFieldName];
                     $specialCondition = '';
                     $specialConditionForOtherField = '';
                     $conditionGlue = ' OR ';
                     if ($conditionInfo['operator'] == 'n' || $conditionInfo['operator'] == 'k' || $conditionInfo['operator'] == 'y') {
                         $conditionGlue = ' AND ';
                         if ($conditionInfo['operator'] == 'n') {
                             $specialCondition = ' OR ' . $field->getTableName() . '.' . $field->getColumnName() . ' IS NULL ';
                             if (!empty($otherField)) {
                                 $specialConditionForOtherField = ' OR ' . $otherField->getTableName() . '.' . $otherField->getColumnName() . ' IS NULL ';
                             }
                         }
                     }
                     $otherFieldValueSql = $valueSql;
                     if ($conditionInfo['operator'] == 'ny' && !empty($otherField)) {
                         $otherFieldValueSql = "IS NOT NULL AND " . $otherField->getTableName() . '.' . $otherField->getColumnName() . " != ''";
                     }
                     $fieldSql .= "{$fieldGlue} ((" . $field->getTableName() . '.' . $field->getColumnName() . ' ' . $valueSql . " {$specialCondition}) ";
                     if (!empty($otherField)) {
                         $fieldSql .= $conditionGlue . '(' . $otherField->getTableName() . '.' . $otherField->getColumnName() . ' ' . $otherFieldValueSql . ' ' . $specialConditionForOtherField . '))';
                     } else {
                         $fieldSql .= ')';
                     }
                 } else {
                     if ($fieldName == 'birthday' && !$this->isRelativeSearchOperators($conditionInfo['operator'])) {
                         $fieldSql .= "{$fieldGlue} DATE_FORMAT(" . $field->getTableName() . '.' . $field->getColumnName() . ",'%m%d') " . $valueSql;
                     } else {
                         $fieldSql .= "{$fieldGlue} " . $field->getTableName() . '.' . $field->getColumnName() . ' ' . $valueSql;
                     }
                 }
             }
             if (($conditionInfo['operator'] == 'n' || $conditionInfo['operator'] == 'k') && ($field->getFieldDataType() == 'owner' || $field->getFieldDataType() == 'picklist')) {
                 $fieldGlue = ' AND';
             } else {
                 $fieldGlue = ' OR';
             }
         }
         $fieldSql .= ')';
         $fieldSqlList[$index] = $fieldSql;
     }
     foreach ($this->manyToManyRelatedModuleConditions as $index => $conditionInfo) {
         $relatedModuleMeta = RelatedModuleMeta::getInstance($this->meta->getTabName(), $conditionInfo['relatedModule']);
         $relationInfo = $relatedModuleMeta->getRelationMeta();
         $relatedModule = $this->meta->getTabName();
         $fieldSql = "(" . $relationInfo['relationTable'] . '.' . $relationInfo[$conditionInfo['column']] . $conditionInfo['SQLOperator'] . $conditionInfo['value'] . ")";
         $fieldSqlList[$index] = $fieldSql;
     }
     // This is added to support reference module fields
     if ($this->referenceModuleField) {
         foreach ($this->referenceModuleField as $index => $conditionInfo) {
             $handler = vtws_getModuleHandlerFromName($conditionInfo['relatedModule'], $current_user);
             $meta = $handler->getMeta();
             $fieldName = $conditionInfo['fieldName'];
             $fields = $meta->getModuleFields();
             $fieldObject = $fields[$fieldName];
             $columnName = $fieldObject->getColumnName();
             $tableName = $fieldObject->getTableName();
             $valueSQL = $this->getConditionValue($conditionInfo['value'], $conditionInfo['SQLOperator'], $fieldObject);
             $fieldSql = "(" . $tableName . $conditionInfo['referenceField'] . '.' . $columnName . ' ' . $valueSQL[0] . ")";
             $fieldSqlList[$index] = $fieldSql;
         }
     }
     // This is needed as there can be condition in different order and there is an assumption in makeGroupSqlReplacements API
     // that it expects the array in an order and then replaces the sql with its the corresponding place
     ksort($fieldSqlList);
     $groupSql = $this->makeGroupSqlReplacements($fieldSqlList, $groupSql);
     if ($this->conditionInstanceCount > 0) {
         $this->conditionalWhere = $groupSql;
         $sql .= $groupSql;
     }
     if (!$onlyWhereQuery) {
         $sql .= " AND {$baseTable}.{$baseTableIndex} > 0";
         $instance = CRMEntity::getInstance($baseModule);
         $sql .= $instance->getUserAccessConditionsQuerySR($baseModule, $current_user);
     }
     $this->whereClause = $sql;
     return $sql;
 }
示例#14
0
	public function fillNonExistingMandatoryPicklistValues($recordList){
		//Meta is cached to eliminate overhead of doing the query every time to get the meta details(retrieveMeta)
		$modulesMetaCache = array();
		foreach($recordList as $index=>$recordDetails){
			if(!array_key_exists($recordDetails['module'], $modulesMetaCache)){
				$handler = vtws_getModuleHandlerFromName($recordDetails['module'], $this->user);
				$meta = $handler->getMeta();
				$modulesMetaCache[$recordDetails['module']] = $meta;
			}
			$moduleMeta = $modulesMetaCache[$recordDetails['module']];
			$mandatoryFieldsList = $meta->getMandatoryFields();
			$moduleFields = $meta->getModuleFields();
			foreach($mandatoryFieldsList as $fieldName){
				$fieldInstance = $moduleFields[$fieldName];
				if(empty($recordDetails[$fieldName]) &&
						($fieldInstance->getFieldDataType()=="multipicklist" || $fieldInstance->getFieldDataType()=="picklist")){
					$pickListDetails = $fieldInstance->getPicklistDetails($webserviceField);
					$defaultValue = $pickListDetails[0]['value'];
					$recordDetails[$fieldName] = $defaultValue;
				}
			}
			$recordList[$index]= $recordDetails;
		}
		return $recordList;
	}
示例#15
0
function vtws_updateConvertLeadStatus($entityIds, $leadId, $user)
{
    global $adb, $log;
    $leadIdComponents = vtws_getIdComponents($leadId);
    if ($entityIds['Accounts'] != '' || $entityIds['Contacts'] != '') {
        $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]));
    }
    $moduleArray = array('Accounts', 'Contacts', 'Potentials');
    foreach ($moduleArray as $module) {
        if (!empty($entityIds[$module])) {
            $idComponents = vtws_getIdComponents($entityIds[$module]);
            $id = $idComponents[1];
            $webserviceModule = vtws_getModuleHandlerFromName($module, $user);
            $meta = $webserviceModule->getMeta();
            $fields = $meta->getModuleFields();
            $field = $fields['isconvertedfromlead'];
            $tablename = $field->getTableName();
            $tableList = $meta->getEntityTableIndexList();
            $tableIndex = $tableList[$tablename];
            $adb->pquery("UPDATE {$tablename} SET isconvertedfromlead = ? WHERE {$tableIndex} = ?", array(1, $id));
        }
    }
}
示例#16
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;
 }
示例#17
0
function getAdvancedSearchCriteriaList($advft_criteria, $advft_criteria_groups, $module = '')
{
    global $currentModule, $current_user;
    if (empty($module)) {
        $module = $currentModule;
    }
    $advfilterlist = array();
    $moduleHandler = vtws_getModuleHandlerFromName($module, $current_user);
    $moduleMeta = $moduleHandler->getMeta();
    $moduleFields = $moduleMeta->getModuleFields();
    foreach ($advft_criteria as $column_index => $column_condition) {
        if (empty($column_condition)) {
            continue;
        }
        $adv_filter_column = $column_condition["columnname"];
        $adv_filter_comparator = $column_condition["comparator"];
        $adv_filter_value = $column_condition["value"];
        $adv_filter_column_condition = $column_condition["columncondition"];
        $adv_filter_groupid = $column_condition["groupid"];
        $column_info = explode(":", $adv_filter_column);
        $fieldName = $column_info[2];
        $fieldObj = $moduleFields[$fieldName];
        $fieldType = $fieldObj->getFieldDataType();
        if ($fieldType == 'currency') {
            // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
            if ($fieldObj->getUIType() == '72') {
                $adv_filter_value = CurrencyField::convertToDBFormat($adv_filter_value, null, true);
            } else {
                $currencyField = new CurrencyField($adv_filter_value);
                if ($module == 'Potentials' && $fieldName == 'amount') {
                    $currencyField->setNumberofDecimals(2);
                }
                $adv_filter_value = $currencyField->getDBInsertedValue();
            }
        }
        $criteria = array();
        $criteria['columnname'] = $adv_filter_column;
        $criteria['comparator'] = $adv_filter_comparator;
        $criteria['value'] = $adv_filter_value;
        $criteria['column_condition'] = $adv_filter_column_condition;
        $advfilterlist[$adv_filter_groupid]['columns'][] = $criteria;
    }
    foreach ($advft_criteria_groups as $group_index => $group_condition_info) {
        if (empty($group_condition_info)) {
            continue;
        }
        if (empty($advfilterlist[$group_index])) {
            continue;
        }
        $advfilterlist[$group_index]['condition'] = $group_condition_info["groupcondition"];
        $noOfGroupColumns = count($advfilterlist[$group_index]['columns']);
        if (!empty($advfilterlist[$group_index]['columns'][$noOfGroupColumns - 1]['column_condition'])) {
            $advfilterlist[$group_index]['columns'][$noOfGroupColumns - 1]['column_condition'] = '';
        }
    }
    $noOfGroups = count($advfilterlist);
    if (!empty($advfilterlist[$noOfGroups]['condition'])) {
        $advfilterlist[$noOfGroups]['condition'] = '';
    }
    return $advfilterlist;
}
示例#18
0
 /** to get the getModuleColumnsList for the given module
 	 * @param $module :: Type String
 	 * @returns  $ret_module_list Array in the following format
 	 * $ret_module_list =
 	  Array ('module' =>
 	  Array('BlockLabel1' =>
 	  Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel,
 	  Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1,
 	  Array('BlockLabel2' =>
 	  Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel,
 	  Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1,
 	  |
 	  Array('BlockLabeln' =>
 	  Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel,
 	  Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1,
 	 */
 function getModuleColumnsList($module)
 {
     global $current_user;
     $module_info = $this->getCustomViewModuleInfo($module);
     foreach ($this->module_list[$module] as $key => $value) {
         $columnlist = $this->getColumnsListbyBlock($module, $value, true);
         if (isset($columnlist)) {
             $ret_module_list[$module][$key] = $columnlist;
         }
     }
     $handler = vtws_getModuleHandlerFromName($module, $current_user);
     $meta = $handler->getMeta();
     $reffields = $meta->getReferenceFieldDetails();
     foreach ($reffields as $fld => $mods) {
         foreach ($mods as $mod) {
             if (!vtlib_isEntityModule($mod)) {
                 continue;
             }
             // reference to a module without fields
             if (isset($ret_module_list[$mod])) {
                 continue;
             }
             // we already have this one
             $module_info = $this->getCustomViewModuleInfo($mod);
             foreach ($this->module_list[$mod] as $key => $value) {
                 $columnlist = $this->getColumnsListbyBlock($mod, $value, false);
                 if (isset($columnlist)) {
                     $ret_module_list[$mod][$key] = $columnlist;
                 }
             }
         }
     }
     return $ret_module_list;
 }
示例#19
0
     $enddate = DateTimeField::convertToDBFormat($enddate);
 }
 $std_filter_list["startdate"] = $startdate;
 $std_filter_list["enddate"] = $enddate;
 if (empty($startdate) && empty($enddate)) {
     unset($std_filter_list);
 }
 //<<<<<<<standardfilters>>>>>>>>>
 //<<<<<<<advancedfilter>>>>>>>>>
 $json = new Zend_Json();
 $advft_criteria = $_REQUEST['advft_criteria'];
 $advft_criteria = $json->decode($advft_criteria);
 $advft_criteria_groups = $_REQUEST['advft_criteria_groups'];
 $advft_criteria_groups = $json->decode($advft_criteria_groups);
 //<<<<<<<advancedfilter>>>>>>>>
 $moduleHandler = vtws_getModuleHandlerFromName($cvmodule, $current_user);
 $moduleMeta = $moduleHandler->getMeta();
 $moduleFields = $moduleMeta->getModuleFields();
 if (!$cvid) {
     $genCVid = $adb->getUniqueID("vtiger_customview");
     if ($genCVid != "") {
         $customviewsql = "INSERT INTO vtiger_customview(cvid, viewname, setdefault, setmetrics, entitytype, status, userid) \r\n\t\t\t\tVALUES (?,?,?,?,?,?,?)";
         $customviewparams = array($genCVid, $viewname, 0, $setmetrics, $cvmodule, $status, $userid);
         $customviewresult = $adb->pquery($customviewsql, $customviewparams);
         $log->info("CustomView :: Save :: vtiger_customview created successfully");
         if ($setdefault == 1) {
             $sql_result = $adb->pquery("SELECT * FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?", array($current_user->id, $cv_tabid));
             if ($adb->num_rows($sql_result) > 0) {
                 $updatedefaultsql = "UPDATE vtiger_user_module_preferences SET default_cvid = ? WHERE userid = ? and tabid = ?";
                 $updatedefaultresult = $adb->pquery($updatedefaultsql, array($genCVid, $current_user->id, $cv_tabid));
             } else {
 public function delete($id)
 {
     $components = vtws_getIdComponents($id);
     $parentId = $components[1];
     $handler = vtws_getModuleHandlerFromName('LineItem', $this->user);
     $handler->cleanLineItemList($id);
     $result = parent::delete($id);
     return $result;
 }
示例#21
0
function importRecord($obj, $inventoryFieldData, $lineItemDetails)
{
    $adb = PearDatabase::getInstance();
    $log = vglobal('log');
    $moduleName = $obj->module;
    $fieldMapping = $obj->fieldMapping;
    $inventoryHandler = vtws_getModuleHandlerFromName($moduleName, $obj->user);
    $inventoryMeta = $inventoryHandler->getMeta();
    $moduleFields = $inventoryMeta->getModuleFields();
    $isRecordExist = isRecordExistInDB($inventoryFieldData, $inventoryMeta, $obj->user);
    $lineItemHandler = vtws_getModuleHandlerFromName('LineItem', $obj->user);
    $lineItemMeta = $lineItemHandler->getMeta();
    $lineItems = array();
    foreach ($lineItemDetails as $index => $lineItemFieldData) {
        $isLineItemExist = isRecordExistInDB($lineItemFieldData, $lineItemMeta, $obj->user);
        if ($isLineItemExist) {
            $count = $index;
            $lineItemData = array();
            $lineItemFieldData = $obj->transformForImport($lineItemFieldData, $lineItemMeta);
            foreach ($fieldMapping as $fieldName => $index) {
                if ($moduleFields[$fieldName]->getTableName() == 'vtiger_inventoryproductrel') {
                    $lineItemData[$fieldName] = $lineItemFieldData[$fieldName];
                    if ($fieldName != 'productid') {
                        $inventoryFieldData[$fieldName] = '';
                    }
                }
            }
            array_push($lineItems, $lineItemData);
        }
    }
    if (empty($lineItems)) {
        return null;
    } elseif ($isRecordExist == false) {
        foreach ($lineItemDetails[$count] as $key => $value) {
            $inventoryFieldData[$key] = $value;
        }
    }
    $fieldData = $obj->transformForImport($inventoryFieldData, $inventoryMeta);
    if (empty($fieldData) || empty($lineItemDetails)) {
        return null;
    }
    if ($fieldData['currency_id'] == ' ') {
        $fieldData['currency_id'] = '1';
    }
    $fieldData['LineItems'] = $lineItems;
    $webserviceObject = VtigerWebserviceObject::fromName($adb, $moduleName);
    $inventoryOperation = new VtigerInventoryOperation($webserviceObject, $obj->user, $adb, $log);
    $entityInfo = $inventoryOperation->create($moduleName, $fieldData);
    $entityInfo['status'] = $obj->getImportRecordStatus('created');
    return $entityInfo;
}
function __FQNExtendedQueryGetQuery($q, $user)
{
    global $adb, $log;
    $moduleRegex = "/[fF][rR][Oo][Mm]\\s+([^\\s;]+)(.*)/";
    preg_match($moduleRegex, $q, $m);
    $mainModule = trim($m[1]);
    // pickup meta data of module
    $webserviceObject = VtigerWebserviceObject::fromName($adb, $mainModule);
    $handlerPath = $webserviceObject->getHandlerPath();
    $handlerClass = $webserviceObject->getHandlerClass();
    require_once $handlerPath;
    $handler = new $handlerClass($webserviceObject, $user, $adb, $log);
    $meta = $handler->getMeta();
    $mainModule = $meta->getTabName();
    // normalize module name
    // check modules
    if (!$meta->isModuleEntity()) {
        throw new WebserviceException('INVALID_MODULE', "Given main module ({$mainModule}) cannot be found");
    }
    // check permission on module
    $entityName = $meta->getEntityName();
    $types = vtws_listtypes(null, $user);
    if (!in_array($entityName, $types['types'])) {
        throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation on module ({$mainModule}) is denied");
    }
    if (!$meta->hasReadAccess()) {
        throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to read module is denied");
    }
    // user has enough permission to start process
    $fieldcolumn = $meta->getFieldColumnMapping();
    $queryGenerator = new QueryGenerator($mainModule, $user);
    $queryColumns = trim(substr($q, 6, stripos($q, ' from ') - 5));
    $queryColumns = explode(',', $queryColumns);
    $queryColumns = array_map(trim, $queryColumns);
    $countSelect = $queryColumns == array('count(*)');
    $queryRelatedModules = array();
    foreach ($queryColumns as $k => $field) {
        if (strpos($field, '.') > 0) {
            list($m, $f) = explode('.', $field);
            if (!isset($queryRelatedModules[$m])) {
                $relhandler = vtws_getModuleHandlerFromName($m, $user);
                $relmeta = $relhandler->getMeta();
                $mn = $relmeta->getTabName();
                // normalize module name
                $queryRelatedModules[$mn] = $relmeta;
                if ($m != $mn) {
                    $queryColumns[$k] = $mn . '.' . $f;
                }
            }
        }
    }
    $queryColumns[] = 'id';
    // add ID column to follow REST interface behaviour
    $queryGenerator->setFields($queryColumns);
    // take apart conditionals
    $queryConditions = trim($m[2], ' ;');
    $moduleRegex = "/[fF][rR][Oo][Mm]\\s+([^\\s;]+)(.*)/";
    preg_match($moduleRegex, $q, $m);
    $queryConditions = trim($m[2], ' ;');
    if (strtolower(substr($queryConditions, 0, 5)) == 'where') {
        $queryConditions = substr($queryConditions, 6);
    }
    $orderbyCond = "/([oO][rR][dD][eE][rR]\\s+[bB][yY]\\s+)+(.*)/";
    preg_match($orderbyCond, $queryConditions, $ob);
    $obflds = isset($ob[2]) ? $ob[2] : '';
    if (stripos($obflds, ' limit ') > 0) {
        $obflds = substr($obflds, 0, stripos($obflds, ' limit '));
    }
    $limitCond = "/([lL][iI][mM][iI][tT]\\s+)+(.*)/";
    preg_match($limitCond, $queryConditions, $lm);
    $lmoc = isset($lm[2]) ? $lm[2] : '';
    if (stripos($lmoc, ' order ') > 0) {
        $lmoc = substr($lmoc, 0, stripos($lmoc, ' order '));
    }
    if (stripos($queryConditions, ' order ') > 0) {
        $queryConditions = substr($queryConditions, 0, stripos($queryConditions, ' order '));
    }
    if (stripos($queryConditions, ' limit ') > 0) {
        $queryConditions = substr($queryConditions, 0, stripos($queryConditions, ' limit '));
    }
    $qcst = strtolower(substr(trim($queryConditions), 0, 5));
    if ($qcst == 'order' or $qcst == 'limit') {
        $queryConditions = '';
    }
    // $queryConditions has all the where conditions
    // $obflds has the list of order by fields
    // $limit is the full correct limit SQL part
    // transform REST ids
    $relatedCond = "/=\\s*'*\\d+x(\\d+)'*/";
    $afterwhere = preg_replace($relatedCond, ' = $1 ', $afterwhere);
    // where
    if (strlen($queryConditions) > 0) {
        $queryGenerator->startGroup();
        $qc = trim($queryConditions);
        if (substr($qc, 0, 1) == '(') {
            $queryGenerator->startGroup();
            $qc = substr($qc, 1);
        }
        $inopRegex = "/\\s+in\\s+\\(/";
        $posand = stripos($qc, ' and ');
        $posor = stripos($qc, ' or ');
        $glue = '';
        while ($posand > 0 or $posor > 0 or strlen($qc)) {
            $endgroup = false;
            preg_match($inopRegex, $qc, $qcop);
            $inop = count($qcop) > 0;
            $lasttwo = '';
            if ($inop) {
                $lasttwo = str_replace(' ', '', $qc);
                $lasttwo = substr($lasttwo, -2);
            }
            if ($posand == 0 and $posor == 0) {
                if (!$inop and substr($qc, -1) == ')' or $inop and $lasttwo == '))') {
                    $qc = substr($qc, 0, strlen($qc) - 1);
                    $endgroup = true;
                }
                __FQNExtendedQueryAddCondition($queryGenerator, $qc, $glue, $mainModule, $fieldcolumn, $user);
                $qc = '';
            } elseif ($posand == 0 or $posand > $posor and $posor != 0) {
                $qcond = trim(substr($qc, 0, $posor));
                if (!$inop and substr($qcond, -1) == ')' or $inop and $lasttwo == '))') {
                    $qcond = substr($qcond, 0, strlen($qcond) - 1);
                    $endgroup = true;
                }
                __FQNExtendedQueryAddCondition($queryGenerator, $qcond, $glue, $mainModule, $fieldcolumn, $user);
                $glue = $queryGenerator::$OR;
                $qc = trim(substr($qc, $posor + 4));
            } else {
                $qcond = trim(substr($qc, 0, $posand));
                if (!$inop and substr($qcond, -1) == ')' or $inop and $lasttwo == '))') {
                    $qcond = substr($qcond, 0, strlen($qcond) - 1);
                    $endgroup = true;
                }
                __FQNExtendedQueryAddCondition($queryGenerator, $qcond, $glue, $mainModule, $fieldcolumn, $user);
                $glue = $queryGenerator::$AND;
                $qc = trim(substr($qc, $posand + 5));
            }
            if ($endgroup) {
                $queryGenerator->endGroup();
            }
            if (substr($qc, 0, 1) == '(') {
                $queryGenerator->startGroup($glue);
                $glue = '';
                $qc = substr($qc, 1);
            }
            $posand = stripos($qc, ' and ');
            $posor = stripos($qc, ' or ');
        }
        $queryGenerator->endGroup();
    }
    $query = 'select ';
    if ($countSelect) {
        $query .= 'count(*) ';
    } else {
        $query .= $queryGenerator->getSelectClauseColumnSQL() . ' ';
    }
    $query .= $queryGenerator->getFromClause() . ' ';
    $query .= $queryGenerator->getWhereClause() . ' ';
    // limit and order
    if (!empty($obflds)) {
        $obflds = trim($obflds);
        if (strtolower(substr($obflds, -3)) == 'asc') {
            $dir = ' asc ';
            $obflds = trim(substr($obflds, 0, strlen($obflds) - 3));
        } elseif (strtolower(substr($obflds, -4)) == 'desc') {
            $dir = ' desc ';
            $obflds = trim(substr($obflds, 0, strlen($obflds) - 4));
        } else {
            $dir = '';
        }
        $obflds = explode(',', $obflds);
        foreach ($obflds as $k => $field) {
            $obflds[$k] = __FQNExtendedQueryField2Column($field, $mainModule, $fieldcolumn, $user);
        }
        $query .= ' order by ' . implode(',', $obflds) . $dir . ' ';
    }
    if (!empty($lmoc)) {
        $query .= " limit {$lmoc} ";
    }
    return array($query, $queryRelatedModules);
}
示例#23
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;
 }
示例#24
0
 /**
  * Function to get related module fields
  * @param type $relModule
  * @param type $user
  * @return null
  */
 function getRelatedModuleFieldList($relModule, $user)
 {
     $handler = vtws_getModuleHandlerFromName($relModule, $user);
     $relMeta = $handler->getMeta();
     if (!$relMeta->isModuleEntity()) {
         return null;
     }
     $relModuleFields = $relMeta->getModuleFields();
     $relModuleFieldList = array();
     foreach ($relModuleFields as $relind => $relModuleField) {
         if ($relModule == 'Users') {
             if ($relModuleField->getFieldDataType() == 'string' || $relModuleField->getFieldDataType() == 'email' || $relModuleField->getFieldDataType() == 'phone') {
                 $skipFields = array(98, 115, 116, 31, 32);
                 if (!in_array($relModuleField->getUIType(), $skipFields) && $relModuleField->getFieldName() != 'asterisk_extension') {
                     $relModuleFieldList[] = array('module' => $relModule, 'fieldname' => $relModuleField->getFieldName(), 'columnname' => $relModuleField->getColumnName(), 'fieldlabel' => $relModuleField->getFieldLabelKey());
                 }
             }
         } else {
             $relModuleFieldList[] = array('module' => $relModule, 'fieldname' => $relModuleField->getFieldName(), 'columnname' => $relModuleField->getColumnName(), 'fieldlabel' => $relModuleField->getFieldLabelKey());
         }
     }
     return $relModuleFieldList;
 }
示例#25
0
 /**
  * Function to fillMandatory fields in vtiger with given values
  * @param type $recordLists
  * @param type $user
  * @return type
  */
 public function fillMandatoryFields($recordLists, $user)
 {
     $transformedRecords = array();
     foreach ($recordLists as $index => $record) {
         $handler = vtws_getModuleHandlerFromName($record['module'], $user);
         $meta = $handler->getMeta();
         $fields = $meta->getModuleFields();
         $mandatoryFields = $meta->getMandatoryFields();
         $ownerFields = $meta->getOwnerFields();
         foreach ($mandatoryFields as $fieldName) {
             // ignore owner fields
             if (in_array($fieldName, $ownerFields)) {
                 continue;
             }
             $fieldInstance = $fields[$fieldName];
             $currentFieldValue = $record[$fieldName];
             if (!empty($currentFieldValue)) {
                 continue;
             }
             $fieldDataType = $fieldInstance->getFieldDataType();
             $defaultValue = $fieldInstance->getDefault();
             $value = '';
             switch ($fieldDataType) {
                 case 'date':
                     $value = $defaultValue;
                     if (empty($defaultValue)) {
                         $dateObject = new DateTime();
                         $value = $dateObject->format('Y-m-d');
                     }
                     break;
                 case 'text':
                     $value = '?????';
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'phone':
                     $value = '?????';
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'boolean':
                     $value = false;
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'email':
                     $value = '?????';
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'string':
                     $value = '?????';
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'url':
                     $value = '?????';
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'integer':
                     $value = 0;
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'double':
                     $value = 0.0;
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
                 case 'currency':
                     $value = 0.0;
                     if (!empty($defaultValue)) {
                         $value = $defaultValue;
                     }
                     break;
             }
             $record[$fieldName] = $value;
         }
         $transformedRecords[$index] = $record;
     }
     return $transformedRecords;
 }
示例#26
0
 public function createEntityRecord($moduleName, $entityLabel)
 {
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleFields = $moduleMeta->getModuleFields();
     $mandatoryFields = $moduleMeta->getMandatoryFields();
     $entityNameFieldsString = $moduleMeta->getNameFields();
     $entityNameFields = explode(',', $entityNameFieldsString);
     $fieldData = array();
     foreach ($entityNameFields as $entityNameField) {
         $entityNameField = trim($entityNameField);
         if (in_array($entityNameField, $mandatoryFields)) {
             $fieldData[$entityNameField] = $entityLabel;
         }
     }
     foreach ($mandatoryFields as $mandatoryField) {
         if (empty($fieldData[$mandatoryField])) {
             $fieldInstance = $moduleFields[$mandatoryField];
             if ($fieldInstance->getFieldDataType() == 'owner') {
                 $fieldData[$mandatoryField] = $this->user->id;
             } else {
                 if (!in_array($mandatoryField, $entityNameFields) && $fieldInstance->getFieldDataType() != 'reference') {
                     $fieldData[$mandatoryField] = '????';
                 }
             }
         }
     }
     $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta);
     $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user);
     $adb = PearDatabase::getInstance();
     $entityIdComponents = vtws_getIdComponents($entityIdInfo['id']);
     $recordId = $entityIdComponents[1];
     $entityfields = getEntityFieldNames($moduleName);
     switch ($moduleName) {
         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));
     $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName);
     $focus = $recordModel->getEntity();
     $focus->id = $recordId;
     $focus->column_fields = $fieldData;
     $this->entityData[] = VTEntityData::fromCRMEntity($focus);
     $focus->updateMissingSeqNumber($moduleName);
     return $entityIdInfo;
 }
示例#27
0
文件: utils.php 项目: yunter/crm
function getEmailRelatedModules()
{
    global $current_user;
    $handler = vtws_getModuleHandlerFromName('Emails', $current_user);
    $meta = $handler->getMeta();
    $moduleFields = $meta->getModuleFields();
    $fieldModel = $moduleFields['parent_id'];
    $relatedModules = $fieldModel->getReferenceList();
    foreach ($relatedModules as $key => $value) {
        if ($value == 'Users') {
            unset($relatedModules[$key]);
        }
    }
    return $relatedModules;
}
}
$summaryFields = array('Accounts' => array('assigned_user_id', 'email1', 'phone', 'bill_city', 'bill_country', 'website'), 'Contacts' => array('assigned_user_id', 'email', 'phone', 'mailingcity', 'mailingcountry'), 'Leads' => array('assigned_user_id', 'email', 'phone', 'city', 'country', 'leadsource'), 'HelpDesk' => array('assigned_user_id', 'ticketstatus', 'parent_id', 'ticketseverities', 'description'), 'Potentials' => array('assigned_user_id', 'amount', 'sales_stage', 'closingdate'), 'Project' => array('assigned_user_id', 'targetenddate'));
foreach ($summaryFields as $moduleName => $fieldsList) {
    $updateQuery = 'UPDATE vtiger_field SET summaryfield = 1
						WHERE fieldname IN (' . generateQuestionMarks($fieldsList) . ') AND tabid = ' . getTabid($moduleName);
    Migration_Index_View::ExecuteQuery($updateQuery, $fieldsList);
}
Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ?', array('Active', 'vtiger_users', 'status'));
Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ?', array('12', 'vtiger_users', 'hour_format'));
// Adding users field into all the available profiles, this is used in email templates
// when non-admin sends an email with users field in the template
$module = 'Users';
$user = new $module();
$activeAdmin = Users::getActiveAdminId();
$user->retrieve_entity_info($activeAdmin, $module);
$handler = vtws_getModuleHandlerFromName($module, $user);
$meta = $handler->getMeta();
$moduleFields = $meta->getModuleFields();
$userAccessbleFields = array();
$skipFields = array(98, 115, 116, 31, 32);
foreach ($moduleFields as $fieldName => $webserviceField) {
    if ($webserviceField->getFieldDataType() == 'string' || $webserviceField->getFieldDataType() == 'email' || $webserviceField->getFieldDataType() == 'phone') {
        if (!in_array($webserviceField->getUitype(), $skipFields) && $fieldName != 'asterisk_extension') {
            $userAccessbleFields[$webserviceField->getFieldId()] .= $fieldName;
        }
    }
}
$tabId = getTabid($module);
$query = 'SELECT profileid FROM vtiger_profile';
$result = $adb->pquery($query, array());
for ($i = 0; $i < $adb->num_rows($result); $i++) {
示例#29
0
/**
 * Function to get customfield entries
 * @param string $module - Module name
 * return array  $cflist - customfield entries
 */
function getFieldListEntries($module)
{
    $tabid = getTabid($module);
    global $adb, $smarty, $log, $current_user;
    global $theme;
    $theme_path = "themes/" . $theme . "/";
    $image_path = "themes/images/";
    $dbQuery = "select vtiger_blocks.*,vtiger_tab.presence as tabpresence  from vtiger_blocks" . " inner join vtiger_tab on vtiger_tab.tabid = vtiger_blocks.tabid" . " where vtiger_blocks.tabid=?  and vtiger_tab.presence = 0 order by sequence";
    $result = $adb->pquery($dbQuery, array($tabid));
    $row = $adb->fetch_array($result);
    $focus = CRMEntity::getInstance($module);
    $nonEditableUiTypes = array('4', '70');
    // To get reference field names
    require_once 'include/Webservices/Utils.php';
    $handler = vtws_getModuleHandlerFromName($module, $current_user);
    $meta = $handler->getMeta();
    $referenceFieldNames = array_keys($meta->getReferenceFieldDetails());
    $cflist = array();
    $i = 0;
    if ($row != '') {
        do {
            if ($row["blocklabel"] == 'LBL_CUSTOM_INFORMATION') {
                $smarty->assign("CUSTOMSECTIONID", $row["blockid"]);
            }
            if ($row["blocklabel"] == 'LBL_RELATED_PRODUCTS') {
                $smarty->assign("RELPRODUCTSECTIONID", $row["blockid"]);
            }
            if ($row["blocklabel"] == 'LBL_COMMENTS' || $row['blocklabel'] == 'LBL_COMMENT_INFORMATION') {
                $smarty->assign("COMMENTSECTIONID", $row["blockid"]);
            }
            if ($row['blocklabel'] == 'LBL_TICKET_RESOLUTION') {
                $smarty->assign("SOLUTIONBLOCKID", $row["blockid"]);
            }
            if ($row['blocklabel'] == '') {
                continue;
            }
            $cflist[$i]['tabpresence'] = $row['tabpresence'];
            $cflist[$i]['module'] = $module;
            $cflist[$i]['blocklabel'] = getTranslatedString($row["blocklabel"], $module);
            $cflist[$i]['blockid'] = $row["blockid"];
            $cflist[$i]['display_status'] = $row["display_status"];
            $cflist[$i]['tabid'] = $tabid;
            $cflist[$i]['blockselect'] = $row["blockid"];
            $cflist[$i]['sequence'] = $row["sequence"];
            $cflist[$i]['iscustom'] = $row["iscustom"];
            if ($module != 'Invoices' && $module != 'Quotes' && $module != 'SalesOrder' && $module != 'Invoice') {
                $sql_field = "select * from  vtiger_field where block=? and vtiger_field.displaytype IN (1,2,4) order by sequence";
                $sql_field_params = array($row["blockid"]);
            } else {
                $sql_field = "select * from  vtiger_field where block=? and (vtiger_field.fieldlabel!='Total' and vtiger_field.fieldlabel!='Sub Total' and vtiger_field.fieldlabel!='Tax') and vtiger_field.displaytype IN (1,2,4) order by sequence";
                $sql_field_params = array($row["blockid"]);
            }
            $result_field = $adb->pquery($sql_field, $sql_field_params);
            $row_field = $adb->fetch_array($result_field);
            if ($row_field != '') {
                $cf_element = array();
                $cf_hidden_element = array();
                $count = 0;
                $hiddencount = 0;
                do {
                    $fieldid = $row_field['fieldid'];
                    $presence = $row_field['presence'];
                    $fieldname = $row_field['fieldname'];
                    $customfieldflag = InStrCount($row_field['fieldname'], 'cf_', true);
                    $quickcreate = $row_field['quickcreate'];
                    $massedit = $row_field['masseditable'];
                    $typeofdata = $row_field['typeofdata'];
                    $displaytype = $row_field['displaytype'];
                    $uitype = $row_field['uitype'];
                    $fld_type_name = getCustomFieldTypeName($row_field['uitype']);
                    $defaultValue = $row_field['defaultvalue'];
                    if (!empty($defaultValue) && ($uitype == '5' || $uitype == '6' || $uitype == '23')) {
                        $defaultValue = getValidDisplayDate($defaultValue);
                    }
                    $fieldlabel = getTranslatedString($row_field['fieldlabel'], $module);
                    $defaultPermitted = true;
                    $strictlyMandatory = false;
                    if (isset($focus->mandatory_fields) && !empty($focus->mandatory_fields) && in_array($fieldname, $focus->mandatory_fields)) {
                        $strictlyMandatory = true;
                        $defaultPermitted = false;
                    } elseif (in_array($uitype, $nonEditableUiTypes) || $displaytype == 2) {
                        $strictlyMandatory = true;
                        $defaultPermitted = false;
                    }
                    if (in_array($fieldname, $referenceFieldNames)) {
                        $defaultPermitted = false;
                    }
                    $visibility = getFieldInfo($fieldname, $typeofdata, $quickcreate, $massedit, $presence, $strictlyMandatory, $customfieldflag, $displaytype, $uitype);
                    $allValues = array();
                    if (in_array($uitype, array('15', '16', '33'))) {
                        $allValues = getAllPickListValues($fieldname);
                    }
                    if ($presence == 0 || $presence == 2) {
                        $cf_element[$count]['fieldselect'] = $fieldid;
                        $cf_element[$count]['blockid'] = $row['blockid'];
                        $cf_element[$count]['tabid'] = $tabid;
                        $cf_element[$count]['no'] = $count;
                        $cf_element[$count]['label'] = $fieldlabel;
                        $cf_element[$count]['fieldlabel'] = $row_field['fieldlabel'];
                        $cf_element[$count]['type'] = $fld_type_name;
                        $cf_element[$count]['typeofdata'] = $typeofdata;
                        $cf_element[$count]['uitype'] = $uitype;
                        $cf_element[$count]['columnname'] = $row_field['columnname'];
                        $cf_element[$count]['defaultvalue'] = array('permitted' => $defaultPermitted, 'value' => $defaultValue, '_allvalues' => $allValues);
                        $cf_element[$count] = array_merge($cf_element[$count], $visibility);
                        $count++;
                    } else {
                        $cf_hidden_element[$hiddencount]['fieldselect'] = $fieldid;
                        $cf_hidden_element[$hiddencount]['blockid'] = $row['blockid'];
                        $cf_hidden_element[$hiddencount]['tabid'] = $tabid;
                        $cf_hidden_element[$hiddencount]['no'] = $hiddencount;
                        $cf_hidden_element[$hiddencount]['label'] = $fieldlabel;
                        $cf_hidden_element[$hiddencount]['fieldlabel'] = $row_field['fieldlabel'];
                        $cf_hidden_element[$hiddencount]['type'] = $fld_type_name;
                        $cf_hidden_element[$hiddencount]['typeofdata'] = $typeofdata;
                        $cf_hidden_element[$hiddencount]['uitype'] = $uitype;
                        $cf_hidden_element[$hiddencount]['columnname'] = $row_field['columnname'];
                        $cf_hidden_element[$hiddencount]['defaultvalue'] = array('permitted' => $defaultPermitted, 'value' => $defaultValue, '_allvalues' => $allValues);
                        $cf_hidden_element[$hiddencount] = array_merge($cf_hidden_element[$hiddencount], $visibility);
                        $hiddencount++;
                    }
                } while ($row_field = $adb->fetch_array($result_field));
                $cflist[$i]['no'] = $count;
                $cflist[$i]['hidden_count'] = $hiddencount;
            } else {
                $cflist[$i]['no'] = 0;
            }
            $query_fields_not_in_block = 'select fieldid,fieldlabel,block from vtiger_field ' . 'inner join vtiger_blocks on vtiger_field.block=vtiger_blocks.blockid ' . 'where vtiger_field.block != ? and vtiger_blocks.blocklabel not in ("LBL_TICKET_RESOLUTION","LBL_COMMENTS","LBL_COMMENT_INFORMATION") ' . 'AND vtiger_field.tabid = ? and vtiger_field.displaytype IN (1,2,4) order by vtiger_field.sequence';
            $params = array($row['blockid'], $tabid);
            $fields = $adb->pquery($query_fields_not_in_block, $params);
            $row_field = $adb->fetch_array($fields);
            if ($row_field != '') {
                $movefields = array();
                $movefieldcount = 0;
                do {
                    $movefields[$movefieldcount]['fieldid'] = $row_field['fieldid'];
                    $movefields[$movefieldcount]['fieldlabel'] = getTranslatedString($row_field['fieldlabel'], $module);
                    $movefieldcount++;
                } while ($row_field = $adb->fetch_array($fields));
                $cflist[$i]['movefieldcount'] = $movefieldcount;
            } else {
                $cflist[$i]['movefieldcount'] = 0;
            }
            $cflist[$i]['field'] = $cf_element;
            $cflist[$i]['hiddenfield'] = $cf_hidden_element;
            $cflist[$i]['movefield'] = $movefields;
            $cflist[$i]['hascustomtable'] = $focus->customFieldTable;
            unset($cf_element);
            unset($cf_hidden_element);
            unset($movefields);
            $i++;
        } while ($row = $adb->fetch_array($result));
    }
    return $cflist;
}
示例#30
-1
 static function lookupMailInVtiger($searchTerm, $user)
 {
     $handler = vtws_getModuleHandlerFromName('Emails', $user);
     $meta = $handler->getMeta();
     $moduleFields = $meta->getModuleFields();
     $parentIdFieldInstance = $moduleFields['parent_id'];
     $referenceModules = $parentIdFieldInstance->getReferenceList();
     $filteredResult = array();
     foreach ($referenceModules as $referenceModule) {
         $referenceModuleHandler = vtws_getModuleHandlerFromName($referenceModule, $user);
         $referenceModuleMeta = $referenceModuleHandler->getMeta();
         $referenceModuleEmailFields = $referenceModuleMeta->getEmailFields();
         $referenceModuleEntityFields = $referenceModuleMeta->getNameFields();
         $referenceModuleEntityFieldsArray = explode(',', $referenceModuleEntityFields);
         $searchFieldList = array_merge($referenceModuleEmailFields, $referenceModuleEntityFieldsArray);
         if (!empty($searchFieldList) && !empty($referenceModuleEmailFields)) {
             $searchFieldListString = implode(',', $referenceModuleEmailFields);
             $where = null;
             for ($i = 0; $i < count($searchFieldList); $i++) {
                 if ($i == count($searchFieldList) - 1) {
                     $where .= sprintf($searchFieldList[$i] . " like '%s'", $searchTerm);
                 } else {
                     $where .= sprintf($searchFieldList[$i] . " like '%s' or ", $searchTerm);
                 }
             }
             if (!empty($where)) {
                 $where = "WHERE {$where}";
             }
             if ($referenceModule == 'Users' && !is_admin($user)) {
                 //Have to do seperate query since webservices will throw permission denied for users module for non admin users
                 global $adb;
                 $where .= " AND vtiger_users.status='Active'";
                 $query = "select {$searchFieldListString},id from vtiger_users {$where}";
                 $dbResult = $adb->pquery($query, array());
                 $num_rows = $adb->num_rows($dbResult);
                 $result = array();
                 for ($i = 0; $i < $num_rows; $i++) {
                     $row = $adb->query_result_rowdata($dbResult, $i);
                     $id = $row['id'];
                     $webserviceId = vtws_getWebserviceEntityId($referenceModule, $id);
                     $row['id'] = $webserviceId;
                     $result[] = $row;
                 }
             } else {
                 $result = vtws_query("select {$searchFieldListString} from {$referenceModule} {$where};", $user);
             }
             foreach ($result as $record) {
                 foreach ($searchFieldList as $searchField) {
                     if (!empty($record[$searchField])) {
                         $filteredResult[] = array('id' => $record[$searchField], 'name' => $record[$searchField] . " - " . getTranslatedString($referenceModule), 'record' => $record['id'], 'module' => $referenceModule);
                     }
                 }
             }
         }
     }
     return $filteredResult;
 }