Example #1
0
 public function getQueryByModuleField($sourceModule, $field, $record, $listQuery)
 {
     $bmqdivx = "sourceModule";
     $zlolzuy = "sourceModule";
     ${${"GLOBALS"}["qrqojbhxesaz"]} = array("Leads", "Accounts", "HelpDesk", "Potentials");
     if (${$bmqdivx} == "PriceBooks" && ${${"GLOBALS"}["tebjrruj"]} == "priceBookRelatedList" || in_array(${$zlolzuy}, ${${"GLOBALS"}["qrqojbhxesaz"]}) || in_array(${${"GLOBALS"}["smtqzdj"]}, getInventoryModules())) {
         ${${"GLOBALS"}["vdridpr"]} = " vtiger_service.discontinued = 1 ";
         $csusxhsru = "field";
         $hxsdmdnrcwm = "sourceModule";
         $hxnvgeuqzxj = "supportedModulesList";
         if (${$hxsdmdnrcwm} == "PriceBooks" && ${$csusxhsru} == "priceBookRelatedList") {
             ${${"GLOBALS"}["vdridpr"]} .= " AND vtiger_service.serviceid NOT IN (SELECT productid FROM vtiger_pricebookproductrel WHERE pricebookid = '{$record}') ";
         } elseif (in_array(${${"GLOBALS"}["smtqzdj"]}, ${$hxnvgeuqzxj})) {
             $hcfqbvtwpxs = "condition";
             ${$hcfqbvtwpxs} .= " AND vtiger_service.serviceid NOT IN (SELECT relcrmid FROM vtiger_crmentityrel WHERE crmid = '{$record}' UNION SELECT crmid FROM vtiger_crmentityrel WHERE relcrmid = '{$record}') ";
         }
         ${${"GLOBALS"}["myxgfagm"]} = stripos(${${"GLOBALS"}["texkhgc"]}, "where");
         if (${${"GLOBALS"}["myxgfagm"]}) {
             ${"GLOBALS"}["jstyvedywb"] = "overRideQuery";
             ${"GLOBALS"}["duyhsdq"] = "split";
             ${"GLOBALS"}["tarygvij"] = "condition";
             $ahusbk = "listQuery";
             $lxqmuyuxd = "split";
             ${${"GLOBALS"}["duyhsdq"]} = spliti("where", ${$ahusbk});
             ${${"GLOBALS"}["jstyvedywb"]} = ${${"GLOBALS"}["wdrbrwcxv"]}[0] . " WHERE " . ${$lxqmuyuxd}[1] . " AND " . ${${"GLOBALS"}["tarygvij"]};
         } else {
             $arzttzsxki = "overRideQuery";
             ${$arzttzsxki} = ${${"GLOBALS"}["texkhgc"]} . " WHERE " . ${${"GLOBALS"}["vdridpr"]};
         }
         return ${${"GLOBALS"}["mvklfvtelnt"]};
     }
 }
Example #2
0
 /**
  * Function searches the records in the module, if parentId & parentModule
  * is given then searches only those records related to them.
  * @param <String> $searchValue - Search value
  * @param <Integer> $parentId - parent recordId
  * @param <String> $parentModule - parent module name
  * @return <Array of Vtiger_Record_Model>
  */
 public function searchRecord($searchValue, $parentId = false, $parentModule = false, $relatedModule = false)
 {
     if (!empty($searchValue) && empty($parentId) && empty($parentModule) && in_array($relatedModule, getInventoryModules())) {
         $matchingRecords = Products_Record_Model::getSearchResult($searchValue, $this->getName());
     } else {
         return parent::searchRecord($searchValue);
     }
     return $matchingRecords;
 }
 function applyChange()
 {
     if ($this->hasError()) {
         $this->sendError();
     }
     if ($this->isApplied()) {
         $this->sendMsg('Changeset ' . get_class($this) . ' already applied!');
     } else {
         require_once 'modules/com_vtiger_workflow/VTTaskManager.inc';
         $taskTypes = array();
         $defaultModules = array('include' => getInventoryModules(), 'exclude' => array());
         $taskType = array("name" => "ConvertInventoryModule", "label" => "ConvertInventoryModule", "classname" => "ConvertInventoryModule", "classpath" => "modules/com_vtiger_workflow/tasks/convert_inventorymodule.inc", "templatepath" => "com_vtiger_workflow/taskforms/convert_inventorymodule.tpl", "modules" => $defaultModules, "sourcemodule" => '');
         VTTaskType::registerTaskType($taskType);
         $this->sendMsg('Changeset ' . get_class($this) . ' applied!');
         $this->markApplied();
     }
     $this->finishExecution();
 }
 function applyChange()
 {
     global $adb;
     if ($this->hasError()) {
         $this->sendError();
     }
     if ($this->isApplied()) {
         $this->sendMsg('Changeset ' . get_class($this) . ' already applied!');
     } else {
         $imods = getInventoryModules();
         foreach ($imods as $mod) {
             $module = Vtiger_Module::getInstance($mod);
             $module->enableTools(array('Import', 'Export'));
         }
         $this->sendMsg('Changeset ' . get_class($this) . ' applied!');
         $this->markApplied();
     }
     $this->finishExecution();
 }
Example #5
0
 /**
  * Function to get list view query for popup window
  * @param <String> $sourceModule Parent module
  * @param <String> $field parent fieldname
  * @param <Integer> $record parent id
  * @param <String> $listQuery
  * @return <String> Listview Query
  */
 public function getQueryByModuleField($sourceModule, $field, $record, $listQuery)
 {
     $supportedModulesList = array('Leads', 'Accounts', 'HelpDesk', 'Potentials');
     if ($sourceModule == 'PriceBooks' && $field == 'priceBookRelatedList' || in_array($sourceModule, $supportedModulesList) || in_array($sourceModule, getInventoryModules())) {
         $condition = " vtiger_service.discontinued = 1 ";
         if ($sourceModule == 'PriceBooks' && $field == 'priceBookRelatedList') {
             $condition .= " AND vtiger_service.serviceid NOT IN (SELECT productid FROM vtiger_pricebookproductrel WHERE pricebookid = '{$record}') ";
         } elseif (in_array($sourceModule, $supportedModulesList)) {
             $condition .= " AND vtiger_service.serviceid NOT IN (SELECT relcrmid FROM vtiger_crmentityrel WHERE crmid = '{$record}' UNION SELECT crmid FROM vtiger_crmentityrel WHERE relcrmid = '{$record}') ";
         }
         $pos = stripos($listQuery, 'where');
         if ($pos) {
             $overRideQuery = $listQuery . ' AND ' . $condition;
         } else {
             $overRideQuery = $listQuery . ' WHERE ' . $condition;
         }
         return $overRideQuery;
     }
 }
 protected function getTableFieldList($tableName)
 {
     $tableFieldList = array();
     $factory = WebserviceField::fromArray($this->pearDB, array('tablename' => $tableName));
     $dbTableFields = $factory->getTableFields();
     foreach ($dbTableFields as $dbField) {
         if ($dbField->primaryKey) {
             if ($this->idColumn === null) {
                 $this->idColumn = $dbField->name;
             } else {
                 throw new WebServiceException(WebServiceErrorCode::$UNKOWNENTITY, "Entity table with multi column primary key is not supported");
             }
         }
         $field = $this->getFieldArrayFromDBField($dbField, $tableName);
         if (preg_match('/tax\\d+/', $dbField->name) != 0) {
             $taxLabel = $this->getTaxLabelFromName($dbField->name);
             if (!empty($taxLabel)) {
                 $field['fieldlabel'] = $taxLabel;
             }
         }
         $webserviceField = WebserviceField::fromArray($this->pearDB, $field);
         $fieldDataType = $this->getFieldType($dbField, $tableName);
         if ($fieldDataType === null) {
             $fieldDataType = $this->getFieldDataTypeFromDBType($dbField->type);
         }
         $webserviceField->setFieldDataType($fieldDataType);
         if (strcasecmp($fieldDataType, 'reference') === 0) {
             if ($webserviceField->getFieldName() == 'parent_id') {
                 $webserviceField->setReferenceList(getInventoryModules());
             } else {
                 $webserviceField->setReferenceList(array('Products', 'Services'));
             }
         }
         array_push($tableFieldList, $webserviceField);
     }
     return $tableFieldList;
 }
Example #7
0
 function GetFirstSortByField($reportid)
 {
     $adb = PearDatabase::getInstance();
     $groupByField = "";
     $sortFieldQuery = "SELECT * FROM vtiger_reportsortcol\n                            LEFT JOIN vtiger_reportgroupbycolumn ON (vtiger_reportsortcol.sortcolid = vtiger_reportgroupbycolumn.sortid and vtiger_reportsortcol.reportid = vtiger_reportgroupbycolumn.reportid)\n                            WHERE columnname!='none' and vtiger_reportsortcol.reportid=? ORDER By sortcolid";
     $sortFieldResult = $adb->pquery($sortFieldQuery, array($reportid));
     $inventoryModules = getInventoryModules();
     if ($adb->num_rows($sortFieldResult) > 0) {
         $fieldcolname = $adb->query_result($sortFieldResult, 0, 'columnname');
         list($tablename, $colname, $module_field, $fieldname, $typeOfData) = explode(":", $fieldcolname);
         list($modulename, $fieldlabel) = explode('__', $module_field, 2);
         $groupByField = $module_field;
         if ($typeOfData == "D") {
             $groupCriteria = $adb->query_result($sortFieldResult, 0, 'dategroupbycriteria');
             if (strtolower($groupCriteria) != 'none') {
                 if (in_array($groupCriteria, array_keys($this->groupByTimeParent))) {
                     $parentCriteria = $this->groupByTimeParent[$groupCriteria];
                     foreach ($parentCriteria as $criteria) {
                         $groupByCondition[] = $this->GetTimeCriteriaCondition($criteria, $groupByField);
                     }
                 }
                 $groupByCondition[] = $this->GetTimeCriteriaCondition($groupCriteria, $groupByField);
                 $groupByField = implode(", ", $groupByCondition);
             }
         } elseif (CheckFieldPermission($fieldname, $modulename) != 'true') {
             if (!(in_array($modulename, $inventoryModules) && $fieldname == 'serviceid')) {
                 $groupByField = $tablename . "." . $colname;
             }
         }
     }
     return $groupByField;
 }
Example #8
0
 function getQueryColumnsList($reportid, $outputformat = '')
 {
     // Have we initialized information already?
     if ($this->_columnslist !== false) {
         return $this->_columnslist;
     }
     global $adb;
     global $modules;
     global $log, $current_user, $current_language;
     $ssql = "select vtiger_pdfmaker_relblockcol.* from vtiger_pdfmaker_relblocks ";
     $ssql .= " left join vtiger_pdfmaker_relblockcol on vtiger_pdfmaker_relblockcol.relblockid = vtiger_pdfmaker_relblocks.relblockid";
     $ssql .= " where vtiger_pdfmaker_relblocks.relblockid = ?";
     $ssql .= " order by vtiger_pdfmaker_relblockcol.colid";
     $result = $adb->pquery($ssql, array($reportid));
     $permitted_fields = array();
     while ($columnslistrow = $adb->fetch_array($result)) {
         $fieldname = "";
         $fieldcolname = $columnslistrow["columnname"];
         list($tablename, $colname, $module_field, $fieldname, $single) = split(":", $fieldcolname);
         list($module, $field) = split("_", $module_field, 2);
         $inventory_fields = array('serviceid');
         $inventory_modules = getInventoryModules();
         require 'user_privileges/user_privileges_' . $current_user->id . '.php';
         if (sizeof($permitted_fields[$module]) == 0 && $is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
             $permitted_fields[$module] = $this->getaccesfield($module);
         }
         if (in_array($module, $inventory_modules)) {
             if (!empty($permitted_fields)) {
                 foreach ($inventory_fields as $value) {
                     array_push($permitted_fields[$module], $value);
                 }
             }
         }
         $selectedfields = explode(":", $fieldcolname);
         if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && !in_array($selectedfields[3], $permitted_fields[$module])) {
             //user has no access to this field, skip it.
             continue;
         }
         $concatSql = getSqlForNameInDisplayFormat(array('first_name' => $selectedfields[0] . ".first_name", 'last_name' => $selectedfields[0] . ".last_name"), 'Users');
         $querycolumns = $this->getEscapedColumns($selectedfields);
         if (isset($module) && $module != "") {
             $mod_strings = return_module_language($current_language, $module);
         }
         $targetTableName = $tablename;
         $fieldname = $selectedfields[3];
         $fieldlabel = trim(preg_replace("/{$module}/", " ", $selectedfields[2], 1));
         $mod_arr = explode('_', $fieldlabel);
         $fieldlabel = trim(str_replace("_", " ", $fieldlabel));
         //modified code to support i18n issue
         $fld_arr = explode(" ", $fieldlabel);
         if ($mod_arr[0] == '') {
             $mod = $module;
             $mod_lbl = $this->getTranslatedString($module, $module);
             //module
         } else {
             $mod = $mod_arr[0];
             array_shift($fld_arr);
             $mod_lbl = $this->getTranslatedString($fld_arr[0], $mod);
             //module
         }
         $fld_lbl_str = implode(" ", $fld_arr);
         $fld_lbl = $this->getTranslatedString($fld_lbl_str, $module);
         //fieldlabel
         $fieldlabel = $mod . "_" . $fieldname;
         if ($selectedfields[0] == "vtiger_usersRel1" && $selectedfields[1] == 'user_name' && $selectedfields[2] == 'Quotes_Inventory_Manager') {
             $columnslist[$fieldcolname] = "trim( {$concatSql} ) as " . $module . "_Inventory_Manager";
             $this->queryPlanner->addTable($selectedfields[0]);
             continue;
         }
         if (CheckFieldPermission($fieldname, $mod) != 'true' && $colname != "crmid" && (!in_array($fieldname, $inventory_fields) && in_array($module, $inventory_modules)) || empty($fieldname)) {
             continue;
         } else {
             $this->labelMapping[$selectedfields[2]] = str_replace(" ", "_", $fieldlabel);
             $header_label = $fieldlabel;
             // To check if the field in the report is a custom field
             // and if yes, get the label of this custom field freshly from the vtiger_field as it would have been changed.
             // Asha - Reference ticket : #4906
             if ($querycolumns == "") {
                 if ($selectedfields[4] == 'C') {
                     $field_label_data = split("_", $selectedfields[2]);
                     $module = $field_label_data[0];
                     if ($module != $this->primarymodule) {
                         $columnslist[$fieldcolname] = "case when (" . $selectedfields[0] . "." . $selectedfields[1] . "='1')then 'yes' else case when (vtiger_crmentity{$module}.crmid !='') then 'no' else '-' end end as '{$fieldlabel}'";
                         $this->queryPlanner->addTable("vtiger_crmentity{$module}");
                     } else {
                         $columnslist[$fieldcolname] = "case when (" . $selectedfields[0] . "." . $selectedfields[1] . "='1')then 'yes' else case when (vtiger_crmentity.crmid !='') then 'no' else '-' end end as '{$fieldlabel}'";
                         $this->queryPlanner->addTable("vtiger_crmentity{$module}");
                     }
                 } elseif ($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'status') {
                     $columnslist[$fieldcolname] = " case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end as Calendar_Status";
                 } elseif ($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'date_start') {
                     if ($module == 'Emails') {
                         $columnslist[$fieldcolname] = "cast(concat(vtiger_activity.date_start,'  ',vtiger_activity.time_start) as DATE) as Emails_Date_Sent";
                     } else {
                         $columnslist[$fieldcolname] = "cast(concat(vtiger_activity.date_start,'  ',vtiger_activity.time_start) AS DATETIME) AS Calendar_date_start";
                     }
                 } elseif (stristr($selectedfields[0], "vtiger_users") && $selectedfields[1] == 'user_name') {
                     $temp_module_from_tablename = str_replace("vtiger_users", "", $selectedfields[0]);
                     if ($module != $this->primarymodule) {
                         $condition = "and vtiger_crmentity" . $module . ".crmid!=''";
                         $this->queryPlanner->addTable("vtiger_crmentity{$module}");
                     } else {
                         $condition = "and vtiger_crmentity.crmid!=''";
                     }
                     if ($temp_module_from_tablename == $module) {
                         $columnslist[$fieldcolname] = " case when(" . $selectedfields[0] . ".last_name NOT LIKE '' {$condition} ) THEN " . $concatSql . " else vtiger_groups" . $module . ".groupname end as '" . $module . "_{$field}'";
                         $this->queryPlanner->addTable('vtiger_groups' . $module);
                         // Auto-include the dependent module table.
                     } else {
                         $columnslist[$fieldcolname] = $selectedfields[0] . ".user_name as '" . $header_label . "'";
                     }
                 } elseif (stristr($selectedfields[0], "vtiger_crmentity") && $selectedfields[1] == 'modifiedby') {
                     $targetTableName = 'vtiger_lastModifiedBy' . $module;
                     $concatSql = getSqlForNameInDisplayFormat(array('last_name' => $targetTableName . '.last_name', 'first_name' => $targetTableName . '.first_name'), 'Users');
                     $columnslist[$fieldcolname] = "trim({$concatSql}) as {$header_label}";
                     $this->queryPlanner->addTable("vtiger_crmentity{$module}");
                     $this->queryPlanner->addTable($targetTableName);
                 } elseif ($selectedfields[0] == "vtiger_crmentity" . $this->primarymodule) {
                     $columnslist[$fieldcolname] = "vtiger_crmentity." . $selectedfields[1] . " AS '" . $header_label . "'";
                 } elseif ($selectedfields[0] == 'vtiger_products' && $selectedfields[1] == 'unit_price') {
                     $columnslist[$fieldcolname] = "concat(" . $selectedfields[0] . ".currency_id,'::',innerProduct.actual_unit_price) as '" . $header_label . "'";
                     $this->queryPlanner->addTable("innerProduct");
                 } elseif (in_array($selectedfields[2], $this->append_currency_symbol_to_value)) {
                     if ($selectedfields[1] == 'discount_amount') {
                         $columnslist[$fieldcolname] = "CONCAT(" . $selectedfields[0] . ".currency_id,'::', IF(" . $selectedfields[0] . ".discount_amount != ''," . $selectedfields[0] . ".discount_amount, (" . $selectedfields[0] . ".discount_percent/100) * " . $selectedfields[0] . ".subtotal)) AS " . $header_label;
                     } else {
                         $columnslist[$fieldcolname] = "concat(" . $selectedfields[0] . ".currency_id,'::'," . $selectedfields[0] . "." . $selectedfields[1] . ") as '" . $header_label . "'";
                     }
                 } elseif ($selectedfields[0] == 'vtiger_notes' && ($selectedfields[1] == 'filelocationtype' || $selectedfields[1] == 'filesize' || $selectedfields[1] == 'folderid' || $selectedfields[1] == 'filestatus')) {
                     if ($selectedfields[1] == 'filelocationtype') {
                         $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when 'I' then 'Internal' when 'E' then 'External' else '-' end as '{$selectedfields['2']}'";
                     } else {
                         if ($selectedfields[1] == 'folderid') {
                             $columnslist[$fieldcolname] = "vtiger_attachmentsfolder.foldername as '{$selectedfields['2']}'";
                         } elseif ($selectedfields[1] == 'filestatus') {
                             $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when '1' then 'yes' when '0' then 'no' else '-' end as '{$selectedfields['2']}'";
                         } elseif ($selectedfields[1] == 'filesize') {
                             $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when '' then '-' else concat(" . $selectedfields[0] . "." . $selectedfields[1] . "/1024,'  ','KB') end as '{$selectedfields['2']}'";
                         }
                     }
                 } elseif ($selectedfields[0] == 'vtiger_inventoryproductrel') {
                     if ($selectedfields[1] == 'discount_amount') {
                         $columnslist[$fieldcolname] = " case when (vtiger_inventoryproductrel{$module}.discount_amount != '') then vtiger_inventoryproductrel{$module}.discount_amount else ROUND((vtiger_inventoryproductrel{$module}.listprice * vtiger_inventoryproductrel{$module}.quantity * (vtiger_inventoryproductrel{$module}.discount_percent/100)),3) end as '" . $header_label . "'";
                         $this->queryPlanner->addTable($selectedfields[0] . $module);
                     } else {
                         if ($selectedfields[1] == 'productid') {
                             $columnslist[$fieldcolname] = "vtiger_products{$module}.productname as '" . $header_label . "'";
                             $this->queryPlanner->addTable("vtiger_products{$module}");
                         } else {
                             if ($selectedfields[1] == 'serviceid') {
                                 $columnslist[$fieldcolname] = "vtiger_service{$module}.servicename as '" . $header_label . "'";
                                 $this->queryPlanner->addTable("vtiger_service{$module}");
                             } else {
                                 if ($selectedfields[1] == 'listprice') {
                                     $moduleInstance = CRMEntity::getInstance($module);
                                     $columnslist[$fieldcolname] = $selectedfields[0] . $module . "." . $selectedfields[1] . "/" . $moduleInstance->table_name . ".conversion_rate as '" . $header_label . "'";
                                     $this->queryPlanner->addTable($selectedfields[0] . $module);
                                 } else {
                                     $columnslist[$fieldcolname] = $selectedfields[0] . $module . "." . $selectedfields[1] . " as '" . $header_label . "'";
                                     $this->queryPlanner->addTable($selectedfields[0] . $module);
                                 }
                             }
                         }
                     }
                 } elseif (stristr($selectedfields[1], 'cf_') == true && stripos($selectedfields[1], 'cf_') == 0) {
                     $columnslist[$fieldcolname] = $selectedfields[0] . "." . $selectedfields[1] . " AS '" . $adb->sql_escape_string(decode_html($header_label)) . "'";
                 } else {
                     $columnslist[$fieldcolname] = $selectedfields[0] . "." . $selectedfields[1] . " AS '" . $header_label . "'";
                 }
             } else {
                 $columnslist[$fieldcolname] = $querycolumns;
             }
             $this->queryPlanner->addTable($targetTableName);
         }
     }
     // Save the information
     $this->_columnslist = $columnslist;
     $log->info("ReportRun :: Successfully returned getQueryColumnsList" . $reportid);
     return $columnslist;
 }
Example #9
0
 /**
  * Function that generates Export Query based on the mode
  * @param Vtiger_Request $request
  * @return <String> export query
  */
 function getExportQuery(Vtiger_Request $request)
 {
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $mode = $request->getMode();
     $cvId = $request->get('viewname');
     $moduleName = $request->get('source_module');
     $queryGenerator = new QueryGenerator($moduleName, $currentUser);
     $queryGenerator->initForCustomViewById($cvId);
     $fieldInstances = $this->moduleFieldInstances;
     $accessiblePresenceValue = array(0, 2);
     foreach ($fieldInstances as $field) {
         // Check added as querygenerator is not checking this for admin users
         $presence = $field->get('presence');
         if (in_array($presence, $accessiblePresenceValue)) {
             $fields[] = $field->getName();
         }
     }
     $queryGenerator->setFields($fields);
     $query = $queryGenerator->getQuery();
     if (in_array($moduleName, getInventoryModules())) {
         $query = $this->moduleInstance->getExportQuery($this->focus, $query);
     }
     $this->accessibleFields = $queryGenerator->getFields();
     switch ($mode) {
         case 'ExportAllData':
             return $query;
             break;
         case 'ExportCurrentPage':
             $pagingModel = new Vtiger_Paging_Model();
             $limit = $pagingModel->getPageLimit();
             $currentPage = $request->get('page');
             if (empty($currentPage)) {
                 $currentPage = 1;
             }
             $currentPageStart = ($currentPage - 1) * $limit;
             if ($currentPageStart < 0) {
                 $currentPageStart = 0;
             }
             $query .= ' LIMIT ' . $currentPageStart . ',' . $limit;
             return $query;
             break;
         case 'ExportSelectedRecords':
             $idList = $this->getRecordsListFromRequest($request);
             $baseTable = $this->moduleInstance->get('basetable');
             $baseTableColumnId = $this->moduleInstance->get('basetableid');
             if (!empty($idList)) {
                 if (!empty($baseTable) && !empty($baseTableColumnId)) {
                     $idList = implode(',', $idList);
                     $query .= ' AND ' . $baseTable . '.' . $baseTableColumnId . ' IN (' . $idList . ')';
                 }
             } else {
                 $query .= ' AND ' . $baseTable . '.' . $baseTableColumnId . ' NOT IN (' . implode(',', $request->get('excluded_ids')) . ')';
             }
             return $query;
             break;
         default:
             return $query;
             break;
     }
 }
Example #10
0
function getSelectClauseFields($module, $moduleMeta, $user)
{
    $moduleFieldNames = $moduleMeta->getModuleFields();
    $inventoryModules = getInventoryModules();
    if (in_array($module, $inventoryModules)) {
        $fields = vtws_describe('LineItem', $user);
        foreach ($fields['fields'] as $field) {
            unset($moduleFieldNames[$field['name']]);
        }
        foreach ($moduleFieldNames as $field => $fieldObj) {
            if (substr($field, 0, 5) == 'shtax') {
                unset($moduleFieldNames[$field]);
            }
        }
    }
    return array_keys($moduleFieldNames);
}
 public function transformForImport($fieldData, $moduleMeta, $fillDefault = true, $mergeMode = false)
 {
     $moduleFields = $moduleMeta->getModuleFields();
     $defaultFieldValues = $this->getDefaultFieldValues($moduleMeta);
     foreach ($fieldData as $fieldName => $fieldValue) {
         $fieldInstance = $moduleFields[$fieldName];
         if (!is_object($fieldInstance)) {
             continue;
         }
         // specially for Inventory module import which has virtual item line fields
         if ($fieldInstance->getFieldDataType() == 'owner') {
             global $adb;
             if (strpos($fieldValue, '::::') > 0) {
                 $fieldValueDetails = explode('::::', $fieldValue);
             } else {
                 $fieldValueDetails = explode(':::', $fieldValue);
             }
             if (count($fieldValueDetails) == 2) {
                 $fieldValue = $fieldValueDetails[1];
             }
             if (count($fieldValueDetails) == 3) {
                 $user_qry = 'select vtiger_users.id from vtiger_users where ' . $fieldValueDetails[2] . ' = ?';
                 $res = $adb->pquery($user_qry, array($fieldValueDetails[1]));
                 $ownerId = 0;
                 if ($res and $adb->num_rows($res) > 0) {
                     $ownerId = $adb->query_result($res, 0, 'id');
                 }
             } else {
                 $ownerId = getUserId_Ol($fieldValue);
                 if (empty($ownerId)) {
                     $ownerId = getGrpId($fieldValue);
                 }
             }
             if (empty($ownerId) && isset($defaultFieldValues[$fieldName])) {
                 $ownerId = $defaultFieldValues[$fieldName];
             }
             if (empty($ownerId) || !Import_Utils::hasAssignPrivilege($moduleMeta->getEntityName(), $ownerId)) {
                 $ownerId = $this->user->id;
             }
             $fieldData[$fieldName] = $ownerId;
         } elseif ($fieldInstance->getFieldDataType() == 'reference') {
             $entityId = false;
             if (!empty($fieldValue)) {
                 if (strpos($fieldValue, '::::') > 0) {
                     $fieldValueDetails = explode('::::', $fieldValue);
                 } else {
                     $fieldValueDetails = explode(':::', $fieldValue);
                 }
                 if (count($fieldValueDetails) > 1) {
                     $referenceModuleName = trim($fieldValueDetails[0]);
                     $entityLabel = trim($fieldValueDetails[1]);
                     if (!empty($fieldValueDetails[2])) {
                         $entityId = getEntityId($referenceModuleName, $entityLabel, $fieldValueDetails[2]);
                     } else {
                         $entityId = getEntityId($referenceModuleName, $entityLabel);
                     }
                 } else {
                     $referencedModules = $fieldInstance->getReferenceList();
                     $entityLabel = $fieldValue;
                     foreach ($referencedModules as $referenceModule) {
                         $referenceModuleName = $referenceModule;
                         if ($referenceModule == 'Users') {
                             $referenceEntityId = getUserId_Ol($entityLabel);
                             if (empty($referenceEntityId) || !Import_Utils::hasAssignPrivilege($moduleMeta->getEntityName(), $referenceEntityId)) {
                                 $referenceEntityId = $this->user->id;
                             }
                         } else {
                             $referenceEntityId = getEntityId($referenceModule, $entityLabel);
                         }
                         if ($referenceEntityId != 0) {
                             $entityId = $referenceEntityId;
                             break;
                         }
                     }
                 }
                 if ((empty($entityId) || $entityId == 0) && (!empty($referenceModuleName) and !in_array($referenceModuleName, getInventoryModules()))) {
                     if (isPermitted($referenceModuleName, 'EditView') == 'yes') {
                         $wsEntityIdInfo = $this->createEntityRecord($referenceModuleName, $entityLabel);
                         $wsEntityId = $wsEntityIdInfo['id'];
                         $entityIdComponents = vtws_getIdComponents($wsEntityId);
                         $entityId = $entityIdComponents[1];
                     }
                 }
                 $fieldData[$fieldName] = $entityId;
             } else {
                 $referencedModules = $fieldInstance->getReferenceList();
                 if ($referencedModules[0] == 'Users') {
                     if (isset($defaultFieldValues[$fieldName])) {
                         $fieldData[$fieldName] = $defaultFieldValues[$fieldName];
                     }
                     if (empty($fieldData[$fieldName]) || !Import_Utils::hasAssignPrivilege($moduleMeta->getEntityName(), $fieldData[$fieldName])) {
                         $fieldData[$fieldName] = $this->user->id;
                     }
                 } else {
                     $fieldData[$fieldName] = '';
                 }
             }
         } elseif ($fieldInstance->getFieldDataType() == 'picklist') {
             global $default_charset;
             if (empty($fieldValue) && isset($defaultFieldValues[$fieldName])) {
                 $fieldData[$fieldName] = $fieldValue = $defaultFieldValues[$fieldName];
             }
             $allPicklistDetails = $fieldInstance->getPicklistDetails();
             $allPicklistValues = array();
             foreach ($allPicklistDetails as $picklistDetails) {
                 $allPicklistValues[] = $picklistDetails['value'];
             }
             $encodePicklistValue = $fieldValue;
             if (!in_array($encodePicklistValue, $allPicklistValues)) {
                 $moduleObject = Vtiger_Module::getInstance($moduleMeta->getEntityName());
                 $fieldObject = Vtiger_Field::getInstance($fieldName, $moduleObject);
                 $fieldObject->setPicklistValues(array($fieldValue));
             }
         } else {
             if ($fieldInstance->getFieldDataType() == 'datetime' && !empty($fieldValue)) {
                 if ($fieldValue == null || $fieldValue == '0000-00-00 00:00:00') {
                     $fieldValue = '';
                 }
                 $valuesList = explode(' ', $fieldValue);
                 if (count($valuesList) == 1) {
                     $fieldValue = '';
                 }
                 $fieldValue = getValidDBInsertDateTimeValue($fieldValue);
                 if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2} ([0-1][0-9]|[2][0-3])([:][0-5][0-9]){1,2}\$/", $fieldValue) == 0) {
                     $fieldValue = '';
                 }
                 $fieldData[$fieldName] = $fieldValue;
             }
             if ($fieldInstance->getFieldDataType() == 'date' && !empty($fieldValue)) {
                 if ($fieldValue == null || $fieldValue == '0000-00-00') {
                     $fieldValue = '';
                 }
                 $fieldValue = getValidDBInsertDateValue($fieldValue);
                 if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2}\$/", $fieldValue) == 0) {
                     $fieldValue = '';
                 }
                 $fieldData[$fieldName] = $fieldValue;
             }
             if (empty($fieldValue) && isset($defaultFieldValues[$fieldName]) && !$mergeMode) {
                 $fieldData[$fieldName] = $fieldValue = $defaultFieldValues[$fieldName];
             }
         }
     }
     if ($fillDefault) {
         foreach ($defaultFieldValues as $fieldName => $fieldValue) {
             if (!isset($fieldData[$fieldName])) {
                 $fieldData[$fieldName] = $defaultFieldValues[$fieldName];
             }
         }
     }
     if (!$mergeMode) {
         //Do not check mandatory fields on merge !
         foreach ($moduleFields as $fieldName => $fieldInstance) {
             if (empty($fieldData[$fieldName]) && $fieldInstance->isMandatory()) {
                 return null;
             }
         }
     }
     return DataTransform::sanitizeData($fieldData, $moduleMeta);
 }
 public function getImportableFields($moduleName)
 {
     $focus = CRMEntity::getInstance($moduleName);
     if (method_exists($focus, 'getImportableFields')) {
         $importableFields = $focus->getImportableFields();
     } else {
         // if we are merging, then selected merge fields must be in selectable fields, so we fill in the mergeFields
         $mergeFields = array();
         if (isset($_REQUEST['merge_type']) and !empty($_REQUEST['merge_fields'])) {
             $json = vtlib_purify($_REQUEST['merge_fields']);
             $mergeFields = json_decode($json);
         }
         $moduleFields = $this->getAccessibleFields($moduleName);
         $importableFields = array();
         foreach ($moduleFields as $fieldName => $fieldInstance) {
             if ($this->isEditableField($fieldInstance) && ($fieldInstance->getTableName() != 'vtiger_crmentity' || $fieldInstance->getColumnName() != 'modifiedby') || $fieldInstance->getUIType() == '70' && $fieldName != 'modifiedtime' || in_array($fieldName, $mergeFields)) {
                 $importableFields[$fieldName] = $fieldInstance;
             }
         }
     }
     if (in_array($moduleName, getInventoryModules())) {
         include_once 'include/fields/InventoryLineField.php';
         $ilfields = new InventoryLineField();
         $importableFields = array_merge($importableFields, $ilfields->getInventoryLineFieldsByObject());
     }
     return $importableFields;
 }
Example #13
0
File: utils.php Project: yunter/crm
function getExportRecordIds($moduleName, $viewid, $input)
{
    global $adb, $current_user, $list_max_entries_per_page;
    $idstring = vtlib_purify($input['idstring']);
    $export_data = vtlib_purify($input['export_data']);
    if (in_array($moduleName, getInventoryModules()) && $export_data == 'currentpage') {
        $queryGenerator = new QueryGenerator($moduleName, $current_user);
        $queryGenerator->initForCustomViewById($viewid);
        if ($input['query'] == 'true') {
            $queryGenerator->addUserSearchConditions($input);
        }
        $queryGenerator->setFields(array('id'));
        $query = $queryGenerator->getQuery();
        $current_page = ListViewSession::getCurrentPage($moduleName, $viewid);
        $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page;
        if ($limit_start_rec < 0) {
            $limit_start_rec = 0;
        }
        $query .= ' LIMIT ' . $limit_start_rec . ',' . $list_max_entries_per_page;
        $result = $adb->pquery($query, array());
        $idstring = array();
        $focus = CRMEntity::getInstance($moduleName);
        for ($i = 0; $i < $adb->num_rows($result); $i++) {
            $idstring[] = $adb->query_result($result, $i, $focus->table_index);
        }
        $idstring = implode(';', $idstring);
        $export_data = 'selecteddata';
    }
    return $idstring . '#@@#' . $export_data;
}
Example #14
0
 public static function showResult($importInfo, $importStatusCount)
 {
     $moduleName = $importInfo['module'];
     $ownerId = $importInfo['user_id'];
     $viewer = new Vtiger_Viewer();
     $viewer->assign('SKIPPED_RECORDS', $skippedRecords);
     $viewer->assign('FOR_MODULE', $moduleName);
     $viewer->assign('MODULE', 'Import');
     $viewer->assign('OWNER_ID', $ownerId);
     $viewer->assign('IMPORT_RESULT', $importStatusCount);
     $viewer->assign('INVENTORY_MODULES', getInventoryModules());
     $viewer->assign('MERGE_ENABLED', $importInfo['merge_type']);
     $viewer->view('ImportResult.tpl', 'Import');
 }
Example #15
0
 public function process(Vtiger_Request $request)
 {
     $viewer = $this->getViewer($request);
     $moduleName = $request->get('source_module');
     $module = $request->getModule();
     $record = $request->get('record');
     $duplicate = $request->get('duplicate');
     $moduleModel = Vtiger_Module_Model::getInstance($moduleName);
     $recordStructureInstance = Vtiger_RecordStructure_Model::getInstanceForModule($moduleModel);
     if (!empty($record)) {
         $customViewModel = CustomView_Record_Model::getInstanceById($record);
         $viewer->assign('MODE', 'edit');
     } else {
         $customViewModel = new CustomView_Record_Model();
         $customViewModel->setModule($moduleName);
         $viewer->assign('MODE', '');
     }
     $viewer->assign('ADVANCE_CRITERIA', $customViewModel->transformToNewAdvancedFilter());
     $viewer->assign('CURRENTDATE', date('Y-n-j'));
     $viewer->assign('DATE_FILTERS', Vtiger_Field_Model::getDateFilterTypes());
     if ($moduleName == 'Calendar') {
         $advanceFilterOpsByFieldType = Calendar_Field_Model::getAdvancedFilterOpsByFieldType();
     } else {
         $advanceFilterOpsByFieldType = Vtiger_Field_Model::getAdvancedFilterOpsByFieldType();
     }
     $viewer->assign('ADVANCED_FILTER_OPTIONS', Vtiger_Field_Model::getAdvancedFilterOptions());
     $viewer->assign('ADVANCED_FILTER_OPTIONS_BY_TYPE', $advanceFilterOpsByFieldType);
     $dateFilters = Vtiger_Field_Model::getDateFilterTypes();
     foreach ($dateFilters as $comparatorKey => $comparatorInfo) {
         $comparatorInfo['startdate'] = DateTimeField::convertToUserFormat($comparatorInfo['startdate']);
         $comparatorInfo['enddate'] = DateTimeField::convertToUserFormat($comparatorInfo['enddate']);
         $comparatorInfo['label'] = vtranslate($comparatorInfo['label'], $module);
         $dateFilters[$comparatorKey] = $comparatorInfo;
     }
     $viewer->assign('DATE_FILTERS', $dateFilters);
     $viewer->assign('RECORD_STRUCTURE_MODEL', $recordStructureInstance);
     $recordStructure = $recordStructureInstance->getStructure();
     // for Inventory module we should now allow item details block
     if (in_array($moduleName, getInventoryModules())) {
         $itemsBlock = "LBL_ITEM_DETAILS";
         unset($recordStructure[$itemsBlock]);
     }
     $viewer->assign('RECORD_STRUCTURE', $recordStructure);
     // Added to show event module custom fields
     if ($moduleName == 'Calendar') {
         $relatedModuleName = 'Events';
         $relatedModuleModel = Vtiger_Module_Model::getInstance($relatedModuleName);
         $relatedRecordStructureInstance = Vtiger_RecordStructure_Model::getInstanceForModule($relatedModuleModel);
         $eventBlocksFields = $relatedRecordStructureInstance->getStructure();
         $viewer->assign('EVENT_RECORD_STRUCTURE_MODEL', $relatedRecordStructureInstance);
         $viewer->assign('EVENT_RECORD_STRUCTURE', $eventBlocksFields);
     }
     $viewer->assign('CUSTOMVIEW_MODEL', $customViewModel);
     if ($duplicate != '1') {
         $viewer->assign('RECORD_ID', $record);
     }
     $viewer->assign('MODULE', $module);
     $viewer->assign('SOURCE_MODULE', $moduleName);
     $viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
     if ($customViewModel->get('viewname') == 'All') {
         $viewer->assign('CV_PRIVATE_VALUE', CustomView_Record_Model::CV_STATUS_DEFAULT);
     } else {
         $viewer->assign('CV_PRIVATE_VALUE', CustomView_Record_Model::CV_STATUS_PRIVATE);
     }
     $viewer->assign('CV_PENDING_VALUE', CustomView_Record_Model::CV_STATUS_PENDING);
     $viewer->assign('CV_PUBLIC_VALUE', CustomView_Record_Model::CV_STATUS_PUBLIC);
     $viewer->assign('MODULE_MODEL', $moduleModel);
     echo $viewer->view('EditView.tpl', $module, true);
 }
Example #16
0
 function undoImport(Vtiger_Request $request)
 {
     $viewer = new Vtiger_Viewer();
     $db = PearDatabase::getInstance();
     $moduleName = $request->getModule();
     $ownerId = $request->get('foruser');
     $user = Users_Record_Model::getCurrentUserModel();
     $dbTableName = Import_Utils_Helper::getDbTableName($user);
     if (!$user->isAdminUser() && $user->id != $ownerId) {
         $viewer->assign('MESSAGE', 'LBL_PERMISSION_DENIED');
         $viewer->view('OperationNotPermitted.tpl', 'Vtiger');
         exit;
     }
     $previousBulkSaveMode = $VTIGER_BULK_SAVE_MODE;
     $VTIGER_BULK_SAVE_MODE = true;
     $query = "SELECT recordid FROM {$dbTableName} WHERE temp_status = ? AND recordid IS NOT NULL";
     //For inventory modules
     $inventoryModules = getInventoryModules();
     if (in_array($moduleName, $inventoryModules)) {
         $query .= ' GROUP BY subject';
     }
     //End
     $result = $db->pquery($query, array(Import_Data_Action::$IMPORT_RECORD_CREATED));
     $noOfRecords = $db->num_rows($result);
     $noOfRecordsDeleted = 0;
     $entityData = array();
     for ($i = 0; $i < $noOfRecords; $i++) {
         $recordId = $db->query_result($result, $i, 'recordid');
         if (isRecordExists($recordId) && isPermitted($moduleName, 'Delete', $recordId) == 'yes') {
             $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName);
             $recordModel->setId($recordId);
             $recordModel->delete();
             $focus = $recordModel->getEntity();
             $focus->id = $recordId;
             $entityData[] = VTEntityData::fromCRMEntity($focus);
             $noOfRecordsDeleted++;
         }
     }
     $entity = new VTEventsManager($db);
     $entity->triggerEvent('vtiger.batchevent.delete', $entityData);
     $VTIGER_BULK_SAVE_MODE = $previousBulkSaveMode;
     $viewer->assign('FOR_MODULE', $moduleName);
     $viewer->assign('MODULE', 'Import');
     $viewer->assign('TOTAL_RECORDS', $noOfRecords);
     $viewer->assign('DELETED_RECORDS_COUNT', $noOfRecordsDeleted);
     $viewer->view('ImportUndoResult.tpl', 'Import');
 }
Example #17
0
 public static function generateChartDataFromReports($queryResult, $groupbyField, $fieldDetails = '', $reportid = '')
 {
     require_once 'modules/Reports/CustomReportUtils.php';
     require_once 'include/Webservices/Utils.php';
     require_once 'include/Webservices/Query.php';
     global $adb, $current_user, $theme, $default_charset;
     $inventorymodules = array('Quotes', 'SalesOrder', 'PurchaseOrder', 'Invoice', 'Products', 'PriceBooks', 'Vendors', 'Services');
     $rows = $adb->num_rows($queryResult);
     $condition = "is";
     $current_theme = $theme;
     $groupByFields = array();
     $yaxisArray = array();
     $ChartDataArray = array();
     $target_val = array();
     $report = new ReportRun($reportid);
     $restrictedModules = array();
     if ($report->secondarymodule != '') {
         $reportModules = explode(":", $report->secondarymodule);
     } else {
         $reportModules = array();
     }
     array_push($reportModules, $report->primarymodule);
     $restrictedModules = false;
     foreach ($reportModules as $mod) {
         if (isPermitted($mod, 'index') != "yes" || vtlib_isModuleActive($mod) == false) {
             if (!is_array($restrictedModules)) {
                 $restrictedModules = array();
             }
             $restrictedModules[] = $mod;
         }
     }
     if (is_array($restrictedModules) && count($restrictedModules) > 0) {
         $ChartDataArray['error'] = "<h4>" . getTranslatedString('LBL_NO_ACCESS', 'Reports') . ' - ' . implode(',', $restrictedModules) . "</h4>";
         return $ChartDataArray;
     }
     if ($fieldDetails != '') {
         list($tablename, $colname, $module_field, $fieldname, $single) = explode(":", $fieldDetails);
         list($module, $field) = split("_", $module_field);
         $dateField = false;
         if ($single == 'D') {
             $dateField = true;
             $query = "SELECT * FROM vtiger_reportgroupbycolumn WHERE reportid=? ORDER BY sortid";
             $result = $adb->pquery($query, array($reportid));
             $criteria = $adb->query_result($result, 0, 'dategroupbycriteria');
         }
     }
     preg_match('/&amp;/', $groupbyField, $matches);
     if (!empty($matches)) {
         $groupfield = str_replace('&amp;', '&', $groupbyField);
         $groupbyField = $report->replaceSpecialChar($groupfield);
     }
     $handler = vtws_getModuleHandlerFromName($module, $current_user);
     $meta = $handler->getMeta();
     $meta->retrieveMeta();
     $referenceFields = $meta->getReferenceFieldDetails();
     if ($rows > 0) {
         $resultRow = $adb->query_result_rowdata($queryResult, 0);
         if (!array_key_exists($groupbyField, $resultRow)) {
             $ChartDataArray['error'] = "<h4>" . getTranslatedString('LBL_NO_PERMISSION_FIELD', 'Dashboard') . "</h4>";
             return $ChartDataArray;
         }
     }
     for ($i = 0; $i < $rows; $i++) {
         $groupFieldValue = $adb->query_result($queryResult, $i, strtolower($groupbyField));
         $decodedGroupFieldValue = html_entity_decode($groupFieldValue, ENT_QUOTES, $default_charset);
         if (!empty($groupFieldValue)) {
             if (in_array($module_field, $report->append_currency_symbol_to_value)) {
                 $valueComp = explode('::', $groupFieldValue);
                 $groupFieldValue = $valueComp[1];
             }
             if ($dateField) {
                 if (!empty($groupFieldValue)) {
                     $groupByFields[] = CustomReportUtils::getXAxisDateFieldValue($groupFieldValue, $criteria);
                 } else {
                     $groupByFields[] = "Null";
                 }
             } else {
                 if (in_array($fieldname, array_keys($referenceFields))) {
                     if (count($referenceFields[$fieldname]) > 1) {
                         $refenceModule = CustomReportUtils::getEntityTypeFromName($decodedGroupFieldValue, $referenceFields[$fieldname]);
                     } else {
                         $refenceModule = $referenceFields[$fieldname][0];
                     }
                     $groupByFields[] = $groupFieldValue;
                     if ($fieldname == 'currency_id' && in_array($module, $inventorymodules)) {
                         $tablename = 'vtiger_currency_info';
                     } elseif ($refenceModule == 'DocumentFolders' && $fieldname == 'folderid') {
                         $tablename = 'vtiger_attachmentsfolder';
                         $colname = 'foldername';
                     } else {
                         require_once "modules/{$refenceModule}/{$refenceModule}.php";
                         $focus = new $refenceModule();
                         $tablename = $focus->table_name;
                         $colname = $focus->list_link_field;
                         $condition = "c";
                     }
                 } else {
                     $groupByFields[] = $groupFieldValue;
                 }
             }
             $yaxisArray[] = $adb->query_result($queryResult, $i, 'groupby_count');
             if ($fieldDetails != '') {
                 if ($dateField) {
                     $advanceSearchCondition = CustomReportUtils::getAdvanceSearchCondition($fieldDetails, $criteria, $groupFieldValue);
                     if ($module == 'Calendar') {
                         $link_val = "index.php?module=" . $module . "&query=true&action=ListView&" . $advanceSearchCondition;
                     } else {
                         $link_val = "index.php?module=" . $module . "&query=true&action=index&" . $advanceSearchCondition;
                     }
                 } else {
                     $cvid = getCvIdOfAll($module);
                     $esc_search_str = urlencode($decodedGroupFieldValue);
                     if ($single == 'DT') {
                         $esc_search_str = urlencode($groupFieldValue);
                         if (strtolower($fieldname) == 'modifiedtime' || strtolower($fieldname) == 'createdtime') {
                             $tablename = 'vtiger_crmentity';
                             $colname = $fieldname;
                         }
                     }
                     if ($fieldname == 'assigned_user_id') {
                         $tablename = 'vtiger_crmentity';
                         $colname = 'smownerid';
                     }
                     if ($fieldname == 'serviceid' && in_array($module, getInventoryModules())) {
                         $fieldname = 'productid';
                     }
                     if ($module == 'Calendar') {
                         $link_val = "index.php?module=" . $module . "&action=ListView&search_text=" . $esc_search_str . "&search_field=" . $fieldname . "&searchtype=BasicSearch&query=true&operator=e&viewname=" . $cvid;
                     } else {
                         $link_val = "index.php?module=" . $module . "&action=index&search_text=" . $esc_search_str . "&search_field=" . $fieldname . "&searchtype=BasicSearch&query=true&operator=e&viewname=" . $cvid;
                     }
                 }
                 $target_val[] = $link_val;
             }
         }
     }
     if (count($groupByFields) == 0) {
         $ChartDataArray['error'] = "<div class='componentName'>" . getTranslatedString('LBL_NO_DATA', 'Reports') . "</div";
     }
     $ChartDataArray['xaxisData'] = $groupByFields;
     $ChartDataArray['yaxisData'] = $yaxisArray;
     $ChartDataArray['targetLink'] = $target_val;
     $theme = $current_theme;
     return $ChartDataArray;
 }
Example #18
0
    function GenerateReport($outputformat, $filtersql, $directOutput = false, &$returnfieldinfo = array())
    {
        global $adb, $current_user, $php_max_execution_time;
        global $modules, $app_strings, $mod_strings, $current_language;
        require 'user_privileges/user_privileges_' . $current_user->id . '.php';
        $picklistarray = array();
        $modules_selected = array();
        $modules_selected[] = $this->primarymodule;
        if (!empty($this->secondarymodule)) {
            $sec_modules = explode(":", $this->secondarymodule);
            for ($i = 0; $i < count($sec_modules); $i++) {
                $modules_selected[] = $sec_modules[$i];
            }
        }
        // Update Reference fields list list
        $referencefieldres = $adb->pquery("SELECT tabid, fieldlabel, uitype from vtiger_field WHERE uitype in (10,101)", array());
        if ($referencefieldres) {
            foreach ($referencefieldres as $referencefieldrow) {
                $uiType = $referencefieldrow['uitype'];
                $modprefixedlabel = getTabModuleName($referencefieldrow['tabid']) . ' ' . $referencefieldrow['fieldlabel'];
                $modprefixedlabel = str_replace(' ', '_', $modprefixedlabel);
                if ($uiType == 10 && !in_array($modprefixedlabel, $this->ui10_fields)) {
                    $this->ui10_fields[] = $modprefixedlabel;
                } elseif ($uiType == 101 && !in_array($modprefixedlabel, $this->ui101_fields)) {
                    $this->ui101_fields[] = $modprefixedlabel;
                }
            }
        }
        if ($outputformat == "HTML") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, $outputformat);
            $result = $adb->query($sSQL);
            $error_msg = $adb->database->ErrorMsg();
            if (!$result && $error_msg != '') {
                // Performance Optimization: If direct output is requried
                if ($directOutput) {
                    echo getTranslatedString('LBL_REPORT_GENERATION_FAILED', $currentModule) . "<br>" . $error_msg;
                    $error_msg = false;
                }
                // END
                return $error_msg;
            }
            // Performance Optimization: If direct output is required
            if ($directOutput) {
                echo '<table cellpadding="5" cellspacing="0" align="center" class="rptTable"><tr>';
            }
            // END
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $y = $adb->num_fields($result);
                $noofrows = $adb->num_rows($result);
                $this->number_of_rows = $noofrows;
                $custom_field_values = $adb->fetch_array($result);
                $groupslist = $this->getGroupingList($this->reportid);
                $column_definitions = $adb->getFieldsDefinition($result);
                $arrayHeaders = array();
                $header = '';
                for ($x = 0; $x < $y; $x++) {
                    $fld = $adb->field_name($result, $x);
                    $fld_type = $column_definitions[$x]->type;
                    list($module, $fieldLabel) = explode('_', $fld->name, 2);
                    $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
                    if (!empty($fieldInfo)) {
                        $field = WebserviceField::fromArray($adb, $fieldInfo);
                    }
                    if (!empty($fieldInfo)) {
                        $headerLabel = getTranslatedString($field->getFieldLabelKey(), $module);
                    } else {
                        $headerLabel = getTranslatedString(str_replace('_', " ", $fieldLabel), $module);
                    }
                    /*STRING TRANSLATION starts */
                    $moduleLabel = '';
                    if (in_array($module, $modules_selected)) {
                        $moduleLabel = getTranslatedString($module, $module);
                    }
                    if (empty($headerLabel)) {
                        $headerLabel = getTranslatedString(str_replace('_', " ", $fld->name));
                    }
                    if (!empty($this->secondarymodule)) {
                        if ($moduleLabel != '') {
                            $headerLabel = $moduleLabel . " " . $headerLabel;
                        }
                    }
                    $header .= "<td class='rptCellLabel'>" . $headerLabel . "</td>";
                    // Performance Optimization: If direct output is required
                    if ($directOutput) {
                        echo $header;
                        $header = '';
                    }
                    // END
                }
                // Performance Optimization: If direct output is required
                if ($directOutput) {
                    echo '</tr><tr>';
                }
                $valtemplate = '';
                $lastvalue = '';
                $secondvalue = '';
                $thirdvalue = '';
                $sHTML = '';
                do {
                    $arraylists = array();
                    $newvalue = '';
                    $snewvalue = '';
                    $tnewvalue = '';
                    if (count($groupslist) == 1) {
                        $newvalue = $custom_field_values[0];
                    } elseif (count($groupslist) == 2) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                    } elseif (count($groupslist) == 3) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                        $tnewvalue = $custom_field_values[2];
                    }
                    if ($newvalue == '') {
                        $newvalue = '-';
                    }
                    if ($snewvalue == '') {
                        $snewvalue = '-';
                    }
                    if ($tnewvalue == '') {
                        $tnewvalue = '-';
                    }
                    $valtemplate .= '<tr>';
                    // Performance Optimization
                    if ($directOutput) {
                        echo $valtemplate;
                        $valtemplate = '';
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        if ($fieldvalue == '') {
                            $fieldvalue = "-";
                        } else {
                            if ($fld->name == 'LBL_ACTION' && $fieldvalue != '-') {
                                $fieldvalue = "<a href='index.php?module={$this->primarymodule}&action=DetailView&record={$fieldvalue}' target='_blank'>" . getTranslatedString('LBL_VIEW_DETAILS') . "</a>";
                            }
                        }
                        if ($lastvalue == $fieldvalue && $this->reporttype == "summary") {
                            if ($this->reporttype == "summary") {
                                $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                            } else {
                                $valtemplate .= "<td class='rptData'>" . $fieldvalue . "</td>";
                            }
                        } else {
                            if ($secondvalue === $fieldvalue && $this->reporttype == "summary") {
                                if ($lastvalue === $newvalue) {
                                    $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                                } else {
                                    $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                }
                            } else {
                                if ($thirdvalue === $fieldvalue && $this->reporttype == "summary") {
                                    if ($secondvalue === $snewvalue) {
                                        $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                                    } else {
                                        $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                    }
                                } else {
                                    if ($this->reporttype == "tabular") {
                                        $valtemplate .= "<td class='rptData'>" . $fieldvalue . "</td>";
                                    } else {
                                        $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                    }
                                }
                            }
                        }
                        // Performance Optimization: If direct output is required
                        if ($directOutput) {
                            echo $valtemplate;
                            $valtemplate = '';
                        }
                    }
                    $valtemplate .= "</tr>";
                    // Performance Optimization: If direct output is required
                    if ($directOutput) {
                        echo $valtemplate;
                        $valtemplate = '';
                    }
                    $lastvalue = $newvalue;
                    $secondvalue = $snewvalue;
                    $thirdvalue = $tnewvalue;
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                // Performance Optimization
                if ($directOutput) {
                    echo "</tr></table>";
                    echo "<script type='text/javascript' id='__reportrun_directoutput_recordcount_script'>\n\t\t\t\t\t\tif(document.getElementById('_reportrun_total')) document.getElementById('_reportrun_total').innerHTML={$noofrows};</script>";
                } else {
                    $sHTML = '<table cellpadding="5" cellspacing="0" align="center" class="rptTable">
					<tr>' . $header . '<!-- BEGIN values -->
					<tr>' . $valtemplate . '</tr>
					</table>';
                }
                //<<<<<<<<construct HTML>>>>>>>>>>>>
                $return_data[] = $sHTML;
                $return_data[] = $noofrows;
                $return_data[] = $sSQL;
                return $return_data;
            }
        } elseif ($outputformat == "PDF") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql);
            $result = $adb->pquery($sSQL, array());
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $y = $adb->num_fields($result);
                $noofrows = $adb->num_rows($result);
                $this->number_of_rows = $noofrows;
                $custom_field_values = $adb->fetch_array($result);
                $column_definitions = $adb->getFieldsDefinition($result);
                $ILF = new InventoryLineField();
                $invMods = getInventoryModules();
                do {
                    $arraylists = array();
                    for ($i = 0; $i < $y - 1; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        list($module, $fieldLabel) = explode('_', $fld->name, 2);
                        $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
                        if (!empty($fieldInfo)) {
                            $field = WebserviceField::fromArray($adb, $fieldInfo);
                        } else {
                            if (in_array($module, $invMods)) {
                                if (substr($fld->table, 0, 26) == 'vtiger_inventoryproductrel') {
                                    foreach ($ILF->getInventoryLineFieldsByName() as $ilfname => $ilfinfo) {
                                        $ilflabel = getTranslatedString($ilfinfo['fieldlabel'], $module);
                                        if ($ilflabel == $fieldLabel) {
                                            $fieldInfo = $ilfinfo;
                                            $fieldInfo['tabid'] = getTabid($module);
                                            $fieldInfo['presence'] = 1;
                                            $field = WebserviceField::fromArray($adb, $fieldInfo);
                                            break;
                                        }
                                    }
                                } else {
                                    if (substr($fld->table, 0, 15) == 'vtiger_products' or substr($fld->table, 0, 14) == 'vtiger_service') {
                                        foreach ($ILF->getInventoryLineProductServiceNameFields() as $ilfname => $ilfinfo) {
                                            $ilflabel = getTranslatedString($ilfinfo['fieldlabel'], $module);
                                            if ($ilflabel == $fieldLabel) {
                                                $fieldInfo = $ilfinfo;
                                                $fieldInfo['tabid'] = getTabid($ilfinfo['module']);
                                                $fieldInfo['presence'] = 1;
                                                $field = WebserviceField::fromArray($adb, $fieldInfo);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (!empty($fieldInfo)) {
                            $headerLabel = getTranslatedString($field->getFieldLabelKey(), $module);
                        } else {
                            $headerLabel = getTranslatedString(str_replace('_', " ", $fieldLabel), $module);
                        }
                        /*STRING TRANSLATION starts */
                        $moduleLabel = '';
                        if (in_array($module, $modules_selected)) {
                            $moduleLabel = getTranslatedString($module, $module);
                        }
                        if (empty($headerLabel)) {
                            $headerLabel = getTranslatedString(str_replace('_', " ", $fld->name));
                        }
                        if (!empty($this->secondarymodule)) {
                            if ($moduleLabel != '') {
                                $headerLabel = $moduleLabel . " " . $headerLabel;
                            }
                        }
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        if (empty($returnfieldinfo[$headerLabel])) {
                            $returnfieldinfo[$headerLabel] = $field;
                        }
                        $arraylists[$headerLabel] = $fieldvalue;
                    }
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                return $arr_val;
            }
        } elseif ($outputformat == "TOTALXLS") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $totalpdf = array();
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            if (isset($this->totallist) and count($this->totallist) > 0) {
                if ($sSQL != '') {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    $rowcount = 0;
                    foreach ($totclmnflds as $key => $value) {
                        $col_header = trim(str_replace($modules, " ", $value));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $value = decode_html(trim($key));
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $rowcount++;
                    }
                }
            }
            return $totalpdf;
        } elseif ($outputformat == "TOTALHTML") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            $coltotalhtml = '';
            if (isset($this->totallist) and count($this->totallist) > 0) {
                if ($sSQL != "") {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    $coltotalhtml = "<table align='center' width='60%' cellpadding='3' cellspacing='0' border='0' class='rptTable'><tr><td class='rptCellLabel'>" . $mod_strings['Totals'] . "</td><td class='rptCellLabel'>" . $mod_strings['SUM'] . "</td><td class='rptCellLabel'>" . $mod_strings['AVG'] . "</td><td class='rptCellLabel'>" . $mod_strings['MIN'] . "</td><td class='rptCellLabel'>" . $mod_strings['MAX'] . "</td></tr>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    foreach ($totclmnflds as $key => $value) {
                        $coltotalhtml .= '<tr class="rptGrpHead" valign=top>';
                        $col_header = trim(str_replace($modules, " ", $value));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $coltotalhtml .= '<td class="rptData">' . $col_header . '</td>';
                        $value = decode_html(trim($key));
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $coltotalhtml .= '<tr>';
                        // Performation Optimization: If Direct output is desired
                        if ($directOutput) {
                            echo $coltotalhtml;
                            $coltotalhtml = '';
                        }
                    }
                    $coltotalhtml .= "</table>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                }
            }
            return $coltotalhtml;
        } elseif ($outputformat == "PRINT") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql);
            $result = $adb->query($sSQL);
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $noofrows = $adb->num_rows($result);
                $this->number_of_rows = $noofrows;
                $custom_field_values = $adb->fetch_array($result);
                $groupslist = $this->getGroupingList($this->reportid);
                $column_definitions = $adb->getFieldsDefinition($result);
                $y = $adb->num_fields($result);
                $arrayHeaders = array();
                $header = '';
                for ($x = 0; $x < $y - 1; $x++) {
                    $fld = $adb->field_name($result, $x);
                    $fld_type = $column_definitions[$x]->type;
                    list($module, $fieldLabel) = explode('_', $fld->name, 2);
                    $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
                    if (!empty($fieldInfo)) {
                        $field = WebserviceField::fromArray($adb, $fieldInfo);
                    }
                    if (!empty($fieldInfo)) {
                        $headerLabel = getTranslatedString($field->getFieldLabelKey(), $module);
                    } else {
                        $headerLabel = getTranslatedString(str_replace('_', " ", $fieldLabel), $module);
                    }
                    /*STRING TRANSLATION starts */
                    $moduleLabel = '';
                    if (in_array($module, $modules_selected)) {
                        $moduleLabel = getTranslatedString($module, $module);
                    }
                    if (empty($headerLabel)) {
                        $headerLabel = getTranslatedString(str_replace('_', " ", $fld->name));
                    }
                    if (!empty($this->secondarymodule)) {
                        if ($moduleLabel != '') {
                            $headerLabel = $moduleLabel . " " . $headerLabel;
                        }
                    }
                    $header .= "<th>" . $headerLabel . "</th>";
                }
                $valtemplate = '';
                $lastvalue = '';
                $secondvalue = '';
                $thirdvalue = '';
                do {
                    $arraylists = array();
                    $newvalue = '';
                    $snewvalue = '';
                    $tnewvalue = '';
                    if (count($groupslist) == 1) {
                        $newvalue = $custom_field_values[0];
                    } elseif (count($groupslist) == 2) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                    } elseif (count($groupslist) == 3) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                        $tnewvalue = $custom_field_values[2];
                    }
                    if ($newvalue == '') {
                        $newvalue = '-';
                    }
                    if ($snewvalue == '') {
                        $snewvalue = '-';
                    }
                    if ($tnewvalue == '') {
                        $tnewvalue = '-';
                    }
                    $valtemplate .= '<tr>';
                    for ($i = 0; $i < $y - 1; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        if ($lastvalue == $fieldvalue && $this->reporttype == "summary") {
                            if ($this->reporttype == "summary") {
                                $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                            } else {
                                $valtemplate .= "<td>" . $fieldvalue . "</td>";
                            }
                        } else {
                            if ($secondvalue == $fieldvalue && $this->reporttype == "summary") {
                                if ($lastvalue == $newvalue) {
                                    $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                                } else {
                                    $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                }
                            } else {
                                if ($thirdvalue == $fieldvalue && $this->reporttype == "summary") {
                                    if ($secondvalue == $snewvalue) {
                                        $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                                    } else {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    }
                                } else {
                                    if ($this->reporttype == "tabular") {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    } else {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    }
                                }
                            }
                        }
                    }
                    $valtemplate .= "</tr>";
                    $lastvalue = $newvalue;
                    $secondvalue = $snewvalue;
                    $thirdvalue = $tnewvalue;
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                $sHTML = '<tr>' . $header . '</tr>' . $valtemplate;
                $return_data[] = $sHTML;
                $return_data[] = $noofrows;
                return $return_data;
            }
        } elseif ($outputformat == "PRINT_TOTAL") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            $coltotalhtml = '';
            if (isset($this->totallist) and count($this->totallist) > 0) {
                if ($sSQL != "") {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    $coltotalhtml = "<br /><table align='center' width='60%' cellpadding='3' cellspacing='0' border='1' class='printReport'><tr><td class='rptCellLabel'>" . $mod_strings['Totals'] . "</td><td><b>" . $mod_strings['SUM'] . "</b></td><td><b>" . $mod_strings['AVG'] . "</b></td><td><b>" . $mod_strings['MIN'] . "</b></td><td><b>" . $mod_strings['MAX'] . "</b></td></tr>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    foreach ($totclmnflds as $key => $value) {
                        $coltotalhtml .= '<tr class="rptGrpHead">';
                        $col_header = getTranslatedString(trim(str_replace($modules, " ", $value)));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $coltotalhtml .= '<td class="rptData">' . $col_header . '</td>';
                        $value = decode_html(trim($key));
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $coltotalhtml .= '</tr>';
                        // Performation Optimization: If Direct output is desired
                        if ($directOutput) {
                            echo $coltotalhtml;
                            $coltotalhtml = '';
                        }
                    }
                    $coltotalhtml .= "</table>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                }
            }
            return $coltotalhtml;
        }
    }
Example #19
0
    public function addField($fieldType, $blockId, $params) {

        $db = PearDatabase::getInstance();

        $label = $params['fieldLabel'];
        if($this->checkFIeldExists($label)){
            throw new Exception(vtranslate('LBL_DUPLICATE_FIELD_EXISTS', 'Settings::LayoutEditor'), 513);
        }
        $supportedFieldTypes = $this->getAddSupportedFieldTypes();
        if(!in_array($fieldType, $supportedFieldTypes)) {
            throw new Exception(vtranslate('LBL_WRONG_FIELD_TYPE', 'Settings::LayoutEditor'), 513);
        }

		$columnName = $params['ColumnName'];
        $moduleName = $this->getName();

        $focus = CRMEntity::getInstance($moduleName);
        if ($params['fieldTableName'] !== '') {
            $tableName= $params['fieldTableName'];
        } elseif (isset($focus->customFieldTable)) {
            $tableName=$focus->customFieldTable[0];
        } else {
            $tableName= 'vtiger_'.strtolower($moduleName).'cf';
        }

        $details = $this->getTypeDetailsForAddField($fieldType, $params);
        $uitype = $details['uitype'];
        $typeofdata = $details['typeofdata'];
        $dbType = $details['dbType'];

        $quickCreate = in_array($moduleName,  getInventoryModules()) ? 3 : 1;

        $fieldModel = new Settings_LayoutEditor_Field_Model();
        $fieldModel->set('name', $columnName)
                   ->set('table', $tableName)
                   ->set('generatedtype',2)
                   ->set('uitype', $uitype)
                   ->set('label', $label)
                   ->set('typeofdata',$typeofdata)
                   ->set('quickcreate',$quickCreate)
                   ->set('columntype', $dbType);

        $blockModel = Vtiger_Block_Model::getInstance($blockId, $this);
        $blockModel->addField($fieldModel);
		
		if($fieldType == 'ModuleLinked') {
            $moduleListNames = explode(',',$params['pickListValues']);
			foreach ($moduleListNames as $key => $modname) {				// проверяем все имена модулей
				$rmoduleInstance = Vtiger_Module::getInstance($modname);
				if (!$rmoduleInstance) unset($moduleListNames[$key]);		// И удаляем если такого модуля нет
			}
			$fieldModel->setRelatedModules($moduleListNames);
		}

        if($fieldType == 'Picklist' || $fieldType == 'MultiSelectCombo') {
            $pickListValues = explode(',',$params['pickListValues']);
			// можно присоединиться к готовому списку с таким же columnname
            if ($pickListValues[0] != 'null') $fieldModel->setPicklistValues($pickListValues);
        }
        return $fieldModel;
    }
Example #20
0
 public function addField($fieldType, $blockId, $params)
 {
     $db = PearDatabase::getInstance();
     $label = $params['fieldLabel'];
     if ($this->checkFIeldExists($label)) {
         throw new Exception(vtranslate('LBL_DUPLICATE_FIELD_EXISTS', 'Settings::LayoutEditor'), 513);
     }
     $supportedFieldTypes = $this->getAddSupportedFieldTypes();
     if (!in_array($fieldType, $supportedFieldTypes)) {
         throw new Exception(vtranslate('LBL_WRONG_FIELD_TYPE', 'Settings::LayoutEditor'), 513);
     }
     $max_fieldid = $db->getUniqueID("vtiger_field");
     $columnName = 'cf_' . $max_fieldid;
     $custfld_fieldid = $max_fieldid;
     $moduleName = $this->getName();
     $focus = CRMEntity::getInstance($moduleName);
     if (isset($focus->customFieldTable)) {
         $tableName = $focus->customFieldTable[0];
     } else {
         $tableName = 'vtiger_' . strtolower($moduleName) . 'cf';
     }
     $details = $this->getTypeDetailsForAddField($fieldType, $params);
     $uitype = $details['uitype'];
     $typeofdata = $details['typeofdata'];
     $dbType = $details['dbType'];
     $quickCreate = in_array($moduleName, getInventoryModules()) ? 3 : 1;
     $fieldModel = new Settings_LayoutEditor_Field_Model();
     $fieldModel->set('name', $columnName)->set('table', $tableName)->set('generatedtype', 2)->set('uitype', $uitype)->set('label', $label)->set('typeofdata', $typeofdata)->set('quickcreate', $quickCreate)->set('columntype', $dbType);
     $blockModel = Vtiger_Block_Model::getInstance($blockId, $this);
     $blockModel->addField($fieldModel);
     if ($fieldType == 'Picklist' || $fieldType == 'MultiSelectCombo') {
         $pickListValues = explode(',', $params['pickListValues']);
         $fieldModel->setPicklistValues($pickListValues);
     }
     return $fieldModel;
 }
Example #21
0
 public function addField($fieldType, $blockId, $params)
 {
     $db = PearDatabase::getInstance();
     $label = $params['fieldLabel'];
     $type = $params['fieldTypeList'];
     $name = strtolower($params['fieldName']);
     $fieldparams = '';
     if ($this->checkFieldLableExists($label)) {
         throw new Exception(vtranslate('LBL_DUPLICATE_FIELD_EXISTS', 'Settings::LayoutEditor'), 513);
     }
     if ($this->checkFieldNameCharacters($name)) {
         throw new Exception(vtranslate('LBL_INVALIDCHARACTER', 'Settings::LayoutEditor'), 512);
     }
     if ($this->checkFieldNameExists($name)) {
         throw new Exception(vtranslate('LBL_DUPLICATE_FIELD_EXISTS', 'Settings::LayoutEditor'), 512);
     }
     $supportedFieldTypes = $this->getAddSupportedFieldTypes();
     if (!in_array($fieldType, $supportedFieldTypes)) {
         throw new Exception(vtranslate('LBL_WRONG_FIELD_TYPE', 'Settings::LayoutEditor'), 513);
     }
     $moduleName = $this->getName();
     $focus = CRMEntity::getInstance($moduleName);
     if ($type == 0) {
         $columnName = $name;
         $tableName = $focus->table_name;
     } elseif ($type == 1) {
         $max_fieldid = $db->getUniqueID("vtiger_field");
         $columnName = 'cf_' . $max_fieldid;
         $custfld_fieldid = $max_fieldid;
         if (isset($focus->customFieldTable)) {
             $tableName = $focus->customFieldTable[0];
         } else {
             $tableName = 'vtiger_' . strtolower($moduleName) . 'cf';
         }
     }
     if ($fieldType == 'Tree') {
         $fieldparams = (int) $params['tree'];
     } elseif ($fieldType == 'MultiReferenceValue') {
         $fieldparams['module'] = $params['MRVModule'];
         $fieldparams['field'] = $params['MRVField'];
         $fieldparams['filterField'] = $params['MRVFilterField'];
         $fieldparams['filterValue'] = $params['MRVFilterValue'];
     }
     $details = $this->getTypeDetailsForAddField($fieldType, $params);
     $uitype = $details['uitype'];
     $typeofdata = $details['typeofdata'];
     $dbType = $details['dbType'];
     $quickCreate = in_array($moduleName, getInventoryModules()) ? 3 : 1;
     $fieldModel = new Settings_LayoutEditor_Field_Model();
     $fieldModel->set('name', $columnName)->set('table', $tableName)->set('generatedtype', 2)->set('uitype', $uitype)->set('label', $label)->set('typeofdata', $typeofdata)->set('quickcreate', $quickCreate)->set('fieldparams', Zend_Json::encode($fieldparams))->set('columntype', $dbType);
     if (isset($details['displayType'])) {
         $fieldModel->set('displaytype', $details['displayType']);
     }
     $blockModel = Vtiger_Block_Model::getInstance($blockId, $this);
     $blockModel->addField($fieldModel);
     if ($fieldType == 'Picklist' || $fieldType == 'MultiSelectCombo') {
         $pickListValues = $params['pickListValues'];
         if (is_string($pickListValues)) {
             $pickListValues = [$pickListValues];
         }
         $fieldModel->setPicklistValues($pickListValues);
     }
     if ($fieldType == 'Related1M') {
         if (!is_array($params['referenceModule'])) {
             $moduleList[] = $params['referenceModule'];
         } else {
             $moduleList = $params['referenceModule'];
         }
         $fieldModel->setRelatedModules($moduleList);
         foreach ($moduleList as $module) {
             $targetModule = Vtiger_Module::getInstance($module);
             $targetModule->setRelatedList($this, $moduleName, array('Add'), 'get_dependents_list');
         }
     }
     return $fieldModel;
 }
 /**	Function used to add the tax type which will do database alterations
  *	@param string $taxlabel - tax label name to be added
  *	@param string $taxvalue - tax value to be added
  *      @param string $sh - sh or empty , if sh passed then the tax will be added in shipping and handling related table
  *      @return void
  */
 public function addTax()
 {
     $adb = PearDatabase::getInstance();
     $tableName = $this->getTableNameFromType();
     $taxid = $adb->getUniqueID($tableName);
     $taxLabel = $this->getName();
     $percentage = $this->get('percentage');
     //if the tax is not available then add this tax.
     //Add this tax as a column in related table
     if ($this->isShippingTax()) {
         $taxname = "shtax" . $taxid;
         $query = "ALTER TABLE vtiger_inventoryshippingrel ADD COLUMN {$taxname} decimal(7,3) DEFAULT NULL";
     } else {
         $taxname = "tax" . $taxid;
         $query = "ALTER TABLE vtiger_inventoryproductrel ADD COLUMN {$taxname} decimal(7,3) DEFAULT NULL";
     }
     $res = $adb->pquery($query, array());
     vimport('~~/include/utils/utils.php');
     if ($this->isProductTax()) {
         // TODO Review: if field addition is required in shipping-tax case too.
         // NOTE: shtax1, shtax2, shtax3 that is added as default should also be taken care.
         $inventoryModules = getInventoryModules();
         foreach ($inventoryModules as $moduleName) {
             // SalesPlatform.ru begin Fix save tax for Products/Services
             if ($moduleName == 'Act' || $moduleName == 'Consignment') {
                 continue;
             }
             // SalesPlatform.ru end
             $moduleInstance = Vtiger_Module::getInstance($moduleName);
             $blockInstance = Vtiger_Block::getInstance('LBL_ITEM_DETAILS', $moduleInstance);
             $field = new Vtiger_Field();
             $field->name = $taxname;
             $field->label = $taxLabel;
             $field->column = $taxname;
             $field->table = 'vtiger_inventoryproductrel';
             $field->uitype = '83';
             $field->typeofdata = 'V~O';
             $field->readonly = '0';
             $field->displaytype = '5';
             $field->masseditable = '0';
             $blockInstance->addField($field);
         }
     }
     //if the tax is added as a column then we should add this tax in the list of taxes
     if ($res) {
         $query = 'INSERT INTO ' . $tableName . ' values(?,?,?,?,?)';
         $params = array($taxid, $taxname, $taxLabel, $percentage, 0);
         $adb->pquery($query, $params);
         return $taxid;
     }
     throw new Error('Error occurred while adding tax');
 }
Example #23
0
 /** Function to get the selected columns list for a selected vtiger_report
  *  This function accepts the vtiger_reportid as the argument and get the selected columns
  *  for the given vtiger_reportid and it forms a combo lists and returns
  *  HTML of the combo values
  */
 function getSelectedColumnsList($reportid)
 {
     global $adb;
     global $modules;
     global $log, $current_user;
     $ssql = "select vtiger_selectcolumn.* from vtiger_report inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid";
     $ssql .= " left join vtiger_selectcolumn on vtiger_selectcolumn.queryid = vtiger_selectquery.queryid";
     $ssql .= " where vtiger_report.reportid = ?";
     $ssql .= " order by vtiger_selectcolumn.columnindex";
     $result = $adb->pquery($ssql, array($reportid));
     $permitted_fields = array();
     $selected_mod = split(":", $this->secmodule);
     array_push($selected_mod, $this->primodule);
     $inventoryModules = getInventoryModules();
     while ($columnslistrow = $adb->fetch_array($result)) {
         $fieldname = "";
         $fieldcolname = $columnslistrow["columnname"];
         $selmod_field_disabled = true;
         foreach ($selected_mod as $smod) {
             if (stripos($fieldcolname, ":" . $smod . "__") > -1 && vtlib_isModuleActive($smod)) {
                 $selmod_field_disabled = false;
                 break;
             }
         }
         if ($selmod_field_disabled == false) {
             list($tablename, $colname, $module_field, $fieldname, $single) = split(":", $fieldcolname);
             require 'user_privileges/user_privileges_' . $current_user->id . '.php';
             list($module, $field) = split("__", $module_field);
             if (sizeof($permitted_fields) == 0 && $is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                 $permitted_fields = $this->getaccesfield($module);
             }
             $querycolumns = $this->getEscapedColumns($selectedfields);
             $fieldlabel = trim(str_replace($module, " ", $module_field));
             $mod_arr = explode('__', $fieldlabel);
             $mod = $mod_arr[0] == '' ? $module : $mod_arr[0];
             $fieldlabel = trim(str_replace("__", " ", $fieldlabel));
             //modified code to support i18n issue
             $mod_lbl = getTranslatedString($mod, $module);
             //module
             $fld_lbl = getTranslatedString($fieldlabel, $module);
             //fieldlabel
             $fieldlabel = $mod_lbl . " " . $fld_lbl;
             if (in_array($mod, $inventoryModules) && $fieldname == 'serviceid') {
                 $shtml .= "<option permission='yes' value=\"" . $fieldcolname . "\">" . $fieldlabel . "</option>";
             } else {
                 if (CheckFieldPermission($fieldname, $mod) != 'true' && $colname != "crmid") {
                     $shtml .= "<option permission='no' value=\"" . $fieldcolname . "\" disabled = 'true'>" . $fieldlabel . "</option>";
                 } else {
                     $shtml .= "<option permission='yes' value=\"" . $fieldcolname . "\">" . $fieldlabel . "</option>";
                 }
             }
         }
         //end
     }
     $log->info("ReportRun :: Successfully returned getQueryColumnsList" . $reportid);
     return $shtml;
 }
Example #24
0
function dup_dependent_rec($record_id, $relatedModule, $new_record_id, $dependent_tables, $maped_relations)
{
    global $adb, $current_user;
    $invmods = getInventoryModules();
    foreach ($dependent_tables as $module => $tables) {
        if (in_array($module, $invmods)) {
            continue;
        }
        // we can't duplicate these
        if (empty($maped_relations) or isset($maped_relations[$module])) {
            require_once "modules/" . $module . "/" . $module . ".php";
            $handler = vtws_getModuleHandlerFromName($module, $current_user);
            $meta = $handler->getMeta();
            $related_field = $tables['columname'];
            $queryGenerator = new QueryGenerator($module, $current_user);
            $queryGenerator->setFields(array('id'));
            $queryGenerator->addReferenceModuleFieldCondition($relatedModule, $related_field, 'id', $record_id, 'e');
            $query = $queryGenerator->getQuery();
            $result = $adb->pquery($query, array());
            while ($r = $adb->fetch_array($result)) {
                // Duplicate dependent records
                $entity = new $module();
                $entity->mode = '';
                $entity->retrieve_entity_info($r[0], $module);
                $entity->column_fields[$related_field] = $new_record_id;
                $entity->column_fields = DataTransform::sanitizeRetrieveEntityInfo($entity->column_fields, $meta);
                $entity->save($module);
            }
        }
    }
}
Example #25
0
 /**
  * this function takes in a module name and returns the field information for it
  */
 function getInformationArray($module)
 {
     require_once 'include/utils/utils.php';
     global $adb;
     $tabid = getTabid($module);
     $result = $adb->pquery("select * from vtiger_field where tabid=?", array($tabid));
     $count = $adb->num_rows($result);
     $arr = array();
     $data = array();
     for ($i = 0; $i < $count; $i++) {
         $arr['uitype'] = $adb->query_result($result, $i, "uitype");
         $arr['fieldname'] = $adb->query_result($result, $i, "fieldname");
         $arr['columnname'] = $adb->query_result($result, $i, "columnname");
         $arr['tablename'] = $adb->query_result($result, $i, "tablename");
         $arr['fieldlabel'] = $adb->query_result($result, $i, "fieldlabel");
         $arr['typeofdata'] = $adb->query_result($result, $i, "typeofdata");
         $fieldlabel = strtolower($arr['fieldlabel']);
         $data[$fieldlabel] = $arr;
     }
     if (in_array($module, getInventoryModules())) {
         include_once 'include/fields/InventoryLineField.php';
         $ilfields = new InventoryLineField();
         $data = array_merge($data, $ilfields->getInventoryLineFieldsByLabel());
     }
     return $data;
 }
Example #26
0
 function generateAdvFilterSql($advfilterlist)
 {
     global $adb;
     $advfiltersql = "";
     foreach ($advfilterlist as $groupindex => $groupinfo) {
         $groupcondition = $groupinfo['condition'];
         $groupcolumns = $groupinfo['columns'];
         if (count($groupcolumns) > 0) {
             $advfiltergroupsql = "";
             foreach ($groupcolumns as $columnindex => $columninfo) {
                 $fieldcolname = $columninfo["columnname"];
                 $comparator = $columninfo["comparator"];
                 $value = $columninfo["value"];
                 $columncondition = $columninfo["column_condition"];
                 if ($fieldcolname != "" && $comparator != "") {
                     $selectedfields = explode(":", $fieldcolname);
                     $moduleFieldLabel = $selectedfields[2];
                     list($moduleName, $fieldLabel) = explode('_', $moduleFieldLabel, 2);
                     $fieldInfo = getFieldByReportLabel($moduleName, $fieldLabel);
                     $concatSql = getSqlForNameInDisplayFormat(array('first_name' => $selectedfields[0] . ".first_name", 'last_name' => $selectedfields[0] . ".last_name"), 'Users');
                     // Added to handle the crmentity table name for Primary module
                     if ($selectedfields[0] == "vtiger_crmentity" . $this->primarymodule) {
                         $selectedfields[0] = "vtiger_crmentity";
                     }
                     //Added to handle yes or no for checkbox field in reports advance filters. -shahul
                     if ($selectedfields[4] == 'C') {
                         if (strcasecmp(trim($value), "yes") == 0) {
                             $value = "1";
                         }
                         if (strcasecmp(trim($value), "no") == 0) {
                             $value = "0";
                         }
                     }
                     $valuearray = explode(",", trim($value));
                     $datatype = isset($selectedfields[4]) ? $selectedfields[4] : "";
                     $secondarymodules = explode(':', $this->secondarymodule);
                     array_walk($secondarymodules, function (&$val) {
                         $val = 'vtiger_users' . $val;
                     });
                     if (isset($valuearray) && count($valuearray) > 1 && $comparator != 'bw') {
                         $advcolumnsql = "";
                         for ($n = 0; $n < count($valuearray); $n++) {
                             if (($selectedfields[0] == 'vtiger_users' . $this->primarymodule || in_array($selectedfields[0], $secondarymodules)) && $selectedfields[1] == 'user_name') {
                                 $module_from_tablename = str_replace("vtiger_users", "", $selectedfields[0]);
                                 $advcolsql[] = " trim({$concatSql})" . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype) . " or vtiger_groups" . $module_from_tablename . ".groupname " . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                             } elseif ($selectedfields[1] == 'status') {
                                 //when you use comma seperated values.
                                 if ($selectedfields[2] == 'Calendar_Status') {
                                     $advcolsql[] = "(case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end)" . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                                 } elseif ($selectedfields[2] == 'HelpDesk_Status') {
                                     $advcolsql[] = "vtiger_troubletickets.status" . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                                 }
                             } elseif ($selectedfields[1] == 'description') {
                                 //when you use comma seperated values.
                                 if ($selectedfields[0] == 'vtiger_crmentity' . $this->primarymodule) {
                                     $advcolsql[] = "vtiger_crmentity.description" . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                                 } else {
                                     $advcolsql[] = $selectedfields[0] . "." . $selectedfields[1] . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                                 }
                             } elseif ($selectedfields[2] == 'Quotes_Inventory_Manager') {
                                 $advcolsql[] = "trim({$concatSql})" . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                             } else {
                                 $advcolsql[] = $selectedfields[0] . "." . $selectedfields[1] . $this->getAdvComparator($comparator, trim($valuearray[$n]), $datatype);
                             }
                         }
                         //If negative logic filter ('not equal to', 'does not contain') is used, 'and' condition should be applied instead of 'or'
                         if ($comparator == 'n' || $comparator == 'k') {
                             $advcolumnsql = implode(" and ", $advcolsql);
                         } else {
                             $advcolumnsql = implode(" or ", $advcolsql);
                         }
                         $fieldvalue = " (" . $advcolumnsql . ") ";
                     } elseif (($selectedfields[0] == 'vtiger_users' . $this->primarymodule || in_array($selectedfields[0], $secondarymodules)) && $selectedfields[1] == 'user_name') {
                         $module_from_tablename = str_replace("vtiger_users", "", $selectedfields[0]);
                         $fieldvalue = " trim(case when (" . $selectedfields[0] . ".last_name NOT LIKE '') then " . $concatSql . " else vtiger_groups" . $module_from_tablename . ".groupname end) " . $this->getAdvComparator($comparator, trim($value), $datatype);
                     } elseif ($comparator == 'bw' && count($valuearray) == 2) {
                         if ($selectedfields[0] == "vtiger_crmentity" . $this->primarymodule) {
                             $fieldvalue = "(" . "vtiger_crmentity." . $selectedfields[1] . " between '" . trim($valuearray[0]) . "' and '" . trim($valuearray[1]) . "')";
                         } else {
                             $fieldvalue = "(" . $selectedfields[0] . "." . $selectedfields[1] . " between '" . trim($valuearray[0]) . "' and '" . trim($valuearray[1]) . "')";
                         }
                     } elseif ($selectedfields[0] == "vtiger_crmentity" . $this->primarymodule) {
                         $fieldvalue = "vtiger_crmentity." . $selectedfields[1] . " " . $this->getAdvComparator($comparator, trim($value), $datatype);
                     } elseif ($selectedfields[2] == 'Quotes_Inventory_Manager') {
                         $fieldvalue = "trim({$concatSql})" . $this->getAdvComparator($comparator, trim($value), $datatype);
                     } elseif ($selectedfields[1] == 'modifiedby') {
                         $module_from_tablename = str_replace("vtiger_crmentity", "", $selectedfields[0]);
                         if ($module_from_tablename != '') {
                             $tableName = 'vtiger_lastModifiedBy' . $module_from_tablename;
                         } else {
                             $tableName = 'vtiger_lastModifiedBy' . $this->primarymodule;
                         }
                         $fieldvalue = getSqlForNameInDisplayFormat(array('last_name' => "{$tableName}.last_name", 'first_name' => "{$tableName}.first_name"), 'Users') . $this->getAdvComparator($comparator, trim($value), $datatype);
                     } elseif ($selectedfields[0] == "vtiger_activity" && $selectedfields[1] == 'status') {
                         $fieldvalue = "(case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end)" . $this->getAdvComparator($comparator, trim($value), $datatype);
                     } elseif ($comparator == 'e' && (trim($value) == "NULL" || trim($value) == '')) {
                         $fieldvalue = "(" . $selectedfields[0] . "." . $selectedfields[1] . " IS NULL OR " . $selectedfields[0] . "." . $selectedfields[1] . " = '')";
                     } elseif ($comparator == 'e' && $datatype == 'D' && (trim($value) == "--\$" || trim($value) == '$')) {
                         $fieldvalue = "(" . $selectedfields[0] . "." . $selectedfields[1] . " IS NULL OR " . $selectedfields[0] . "." . $selectedfields[1] . " = '')";
                     } elseif (substr($selectedfields[0], 0, 26) == 'vtiger_inventoryproductrel' && ($selectedfields[1] == 'productid' || $selectedfields[1] == 'serviceid' || $selectedfields[1] == 'discount')) {
                         $invmod = in_array($this->primarymodule, getInventoryModules()) ? $this->primarymodule : $this->secondarymodule;
                         if ($selectedfields[1] == 'productid') {
                             $fieldvalue = "vtiger_products{$invmod}.productname " . $this->getAdvComparator($comparator, trim($value), $datatype);
                         } else {
                             if ($selectedfields[1] == 'serviceid') {
                                 $fieldvalue = "vtiger_service{$invmod}.servicename " . $this->getAdvComparator($comparator, trim($value), $datatype);
                             } else {
                                 if ($selectedfields[1] == 'discount') {
                                     $fieldvalue = "(vtiger_inventoryproductrel{$invmod}.discount_amount " . $this->getAdvComparator($comparator, trim($value), $datatype) . "\n\t\t\t\t\t\t\t\t\tOR ROUND((vtiger_inventoryproductrel{$invmod}.listprice * vtiger_inventoryproductrel{$invmod}.quantity * (vtiger_inventoryproductrel{$invmod}.discount_percent/100)),3) " . $this->getAdvComparator($comparator, trim($value), $datatype) . ") ";
                                 }
                             }
                         }
                     } elseif ($fieldInfo['uitype'] == '10' || isReferenceUIType($fieldInfo['uitype'])) {
                         $comparatorValue = $this->getAdvComparator($comparator, trim($value), $datatype);
                         $fieldSqls = array();
                         $fieldSqlColumns = $this->getReferenceFieldColumnList($moduleName, $fieldInfo);
                         foreach ($fieldSqlColumns as $columnSql) {
                             $fieldSqls[] = $columnSql . $comparatorValue;
                         }
                         $fieldvalue = ' (' . implode(' OR ', $fieldSqls) . ') ';
                     } else {
                         $fieldvalue = $selectedfields[0] . "." . $selectedfields[1] . $this->getAdvComparator($comparator, trim($value), $datatype);
                     }
                     $advfiltergroupsql .= $fieldvalue;
                     if (!empty($columncondition)) {
                         $advfiltergroupsql .= ' ' . $columncondition . ' ';
                     }
                 }
             }
             if (trim($advfiltergroupsql) != "") {
                 $advfiltergroupsql = "( {$advfiltergroupsql} ) ";
                 if (!empty($groupcondition)) {
                     $advfiltergroupsql .= ' ' . $groupcondition . ' ';
                 }
                 $advfiltersql .= $advfiltergroupsql;
             }
         }
     }
     if (trim($advfiltersql) != "") {
         $advfiltersql = '(' . $advfiltersql . ')';
     }
     return $advfiltersql;
 }
Example #27
0
    public function process(Vtiger_Request $request)
    {
        $currentUser = Users_Record_Model::getCurrentUserModel();
        $viewer = $this->getViewer($request);
        $moduleName = $request->getModule();
        $qualifiedModuleName = $request->getModule(false);
        $recordId = $request->get('task_id');
        $workflowId = $request->get('for_workflow');
        $workflowModel = Settings_Workflows_Record_Model::getInstance($workflowId);
        $taskTypes = $workflowModel->getTaskTypes();
        if ($recordId) {
            $taskModel = Settings_Workflows_TaskRecord_Model::getInstance($recordId);
        } else {
            $taskType = $request->get('type');
            if (empty($taskType)) {
                $taskType = !empty($taskTypes[0]) ? $taskTypes[0]->getName() : 'VTEmailTask';
            }
            $taskModel = Settings_Workflows_TaskRecord_Model::getCleanInstance($workflowModel, $taskType);
        }
        $taskTypeModel = $taskModel->getTaskType();
        $viewer->assign('TASK_TYPE_MODEL', $taskTypeModel);
        $viewer->assign('TASK_TEMPLATE_PATH', $taskTypeModel->getTemplatePath());
        $recordStructureInstance = Settings_Workflows_RecordStructure_Model::getInstanceForWorkFlowModule($workflowModel, Settings_Workflows_RecordStructure_Model::RECORD_STRUCTURE_MODE_EDITTASK);
        $viewer->assign('RECORD_STRUCTURE_MODEL', $recordStructureInstance);
        $viewer->assign('RECORD_STRUCTURE', $recordStructureInstance->getStructure());
        $moduleModel = $workflowModel->getModule();
        $dateTimeFields = $moduleModel->getFieldsByType(array('date', 'datetime'));
        $taskObject = $taskModel->getTaskObject();
        $taskType = get_class($taskObject);
        if ($taskType === 'VTCreateEntityTask') {
            if ($taskObject->entity_type) {
                $relationModuleModel = Vtiger_Module_Model::getInstance($taskObject->entity_type);
                $ownerFieldModels = $relationModuleModel->getFieldsByType('owner');
                $fieldMapping = Zend_Json::decode($taskObject->field_value_mapping);
                foreach ($fieldMapping as $key => $mappingInfo) {
                    if (array_key_exists($mappingInfo['fieldname'], $ownerFieldModels)) {
                        $userRecordModel = Users_Record_Model::getInstanceByName($mappingInfo['value']);
                        if ($userRecordModel) {
                            $ownerName = $userRecordModel->getId();
                        } else {
                            $groupRecordModel = Settings_Groups_Record_Model::getInstance($mappingInfo['value']);
                            $ownerName = $groupRecordModel->getId();
                        }
                        $fieldMapping[$key]['value'] = $ownerName;
                    }
                }
                $taskObject->field_value_mapping = Zend_Json::encode($fieldMapping);
            }
        }
        if ($taskType === 'VTUpdateFieldsTask') {
            if ($moduleModel->getName() == "Documents") {
                $restrictFields = array('folderid', 'filename', 'filelocationtype');
                $viewer->assign('RESTRICTFIELDS', $restrictFields);
            }
        }
        $viewer->assign('SOURCE_MODULE', $moduleModel->getName());
        $viewer->assign('MODULE_MODEL', $moduleModel);
        $viewer->assign('TASK_ID', $recordId);
        $viewer->assign('WORKFLOW_ID', $workflowId);
        $viewer->assign('DATETIME_FIELDS', $dateTimeFields);
        $viewer->assign('WORKFLOW_MODEL', $workflowModel);
        $viewer->assign('TASK_TYPES', $taskTypes);
        $viewer->assign('TASK_MODEL', $taskModel);
        $viewer->assign('CURRENTDATE', date('Y-n-j'));
        $metaVariables = Settings_Workflows_Module_Model::getMetaVariables();
        if ($moduleModel->getName() == 'Invoice' || $moduleModel->getName() == 'Quotes') {
            $metaVariables['Portal Pdf Url'] = '(general : (__VtigerMeta__) portalpdfurl)';
        }
        // Adding option Line Item block for Individual tax mode
        $individualTaxBlockLabel = vtranslate("LBL_LINEITEM_BLOCK_GROUP", $qualifiedModuleName);
        $individualTaxBlockValue = $viewer->view('LineItemsGroupTemplate.tpl', $qualifiedModuleName, $fetch = true);
        // Adding option Line Item block for group tax mode
        $groupTaxBlockLabel = vtranslate("LBL_LINEITEM_BLOCK_INDIVIDUAL", $qualifiedModuleName);
        $groupTaxBlockValue = $viewer->view('LineItemsIndividualTemplate.tpl', $qualifiedModuleName, $fetch = true);
        $templateVariables = array($individualTaxBlockValue => $individualTaxBlockLabel, $groupTaxBlockValue => $groupTaxBlockLabel);
        $viewer->assign('META_VARIABLES', $metaVariables);
        $viewer->assign('TEMPLATE_VARIABLES', $templateVariables);
        $viewer->assign('TASK_OBJECT', $taskObject);
        $viewer->assign('FIELD_EXPRESSIONS', Settings_Workflows_Module_Model::getExpressions());
        $repeat_date = $taskModel->getTaskObject()->calendar_repeat_limit_date;
        if (!empty($repeat_date)) {
            $repeat_date = Vtiger_Date_UIType::getDisplayDateValue($repeat_date);
        }
        $viewer->assign('REPEAT_DATE', $repeat_date);
        $userModel = Users_Record_Model::getCurrentUserModel();
        $viewer->assign('dateFormat', $userModel->get('date_format'));
        $viewer->assign('timeFormat', $userModel->get('hour_format'));
        $viewer->assign('MODULE', $moduleName);
        $viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
        $emailFields = $recordStructureInstance->getAllEmailFields();
        foreach ($emailFields as $metaKey => $emailField) {
            $emailFieldoptions .= '<option value=",$' . $metaKey . '">' . $emailField->get('workflow_columnlabel') . '</option>';
        }
        $nameFields = $recordStructureInstance->getNameFields();
        $fromEmailFieldOptions = '<option value="">' . vtranslate('Optional', $qualifiedModuleName) . '</option>';
        $fromEmailFieldOptions .= '<option value="$(general : (__VtigerMeta__) supportName)<$(general : (__VtigerMeta__) supportEmailId)>"
									>' . vtranslate('LBL_HELPDESK_SUPPORT_EMAILID', $qualifiedModuleName) . '</option>';
        foreach ($emailFields as $metaKey => $emailField) {
            list($relationFieldName, $rest) = explode(' ', $metaKey);
            $value = '<$' . $metaKey . '>';
            if ($nameFields) {
                $nameFieldValues = '';
                foreach (array_keys($nameFields) as $fieldName) {
                    if (strstr($fieldName, $relationFieldName) || count(explode(' ', $metaKey)) === 1 && count(explode(' ', $fieldName)) === 1) {
                        $fieldName = '$' . $fieldName;
                        $nameFieldValues .= ' ' . $fieldName;
                    }
                }
                $value = trim($nameFieldValues) . $value;
            }
            $fromEmailFieldOptions .= '<option value="' . $value . '">' . $emailField->get('workflow_columnlabel') . '</option>';
        }
        $structure = $recordStructureInstance->getStructure();
        // for inventory modules we shouldn't show item detail fields
        if ($taskType == "VTEmailTask" && in_array($workflowModel->getModule()->name, getInventoryModules())) {
            $itemsBlock = "LBL_ITEM_DETAILS";
            unset($structure[$itemsBlock]);
        }
        foreach ($structure as $fields) {
            foreach ($fields as $field) {
                $allFieldoptions .= '<option value="$' . $field->get('workflow_columnname') . '">' . $field->get('workflow_columnlabel') . '</option>';
            }
        }
        $userList = $currentUser->getAccessibleUsers();
        $groupList = $currentUser->getAccessibleGroups();
        $assignedToValues = array();
        $assignedToValues[vtranslate('LBL_USERS', 'Vtiger')] = $userList;
        $assignedToValues[vtranslate('LBL_GROUPS', 'Vtiger')] = $groupList;
        $viewer->assign('ASSIGNED_TO', $assignedToValues);
        $viewer->assign('EMAIL_FIELD_OPTION', $emailFieldoptions);
        $viewer->assign('FROM_EMAIL_FIELD_OPTION', $fromEmailFieldOptions);
        $viewer->assign('ALL_FIELD_OPTIONS', $allFieldoptions);
        $viewer->view('EditTask.tpl', $qualifiedModuleName);
    }
Example #28
0
 public function step2(Vtiger_Request $request)
 {
     $viewer = $this->getViewer($request);
     $moduleName = $request->getModule();
     $qualifiedModuleName = $request->getModule(false);
     $recordId = $request->get('record');
     if ($recordId) {
         $workFlowModel = Settings_Workflows_Record_Model::getInstance($recordId);
         $selectedModule = $workFlowModel->getModule();
         $selectedModuleName = $selectedModule->getName();
     } else {
         $selectedModuleName = $request->get('module_name');
         $selectedModule = Vtiger_Module_Model::getInstance($selectedModuleName);
         $workFlowModel = Settings_Workflows_Record_Model::getCleanInstance($selectedModuleName);
     }
     $requestData = $request->getAll();
     foreach ($requestData as $name => $value) {
         if ($name == 'schdayofweek' || $name == 'schdayofmonth' || $name == 'schannualdates') {
             if (is_string($value)) {
                 // need to save these as json data
                 $value = array($value);
             }
         }
         if ($name == 'summary') {
             $value = htmlspecialchars($value);
         }
         $workFlowModel->set($name, $value);
     }
     //Added to support advance filters
     $recordStructureInstance = Settings_Workflows_RecordStructure_Model::getInstanceForWorkFlowModule($workFlowModel, Settings_Workflows_RecordStructure_Model::RECORD_STRUCTURE_MODE_FILTER);
     $viewer->assign('RECORD_STRUCTURE_MODEL', $recordStructureInstance);
     $recordStructure = $recordStructureInstance->getStructure();
     if (in_array($selectedModuleName, getInventoryModules())) {
         $itemsBlock = "LBL_ITEM_DETAILS";
         unset($recordStructure[$itemsBlock]);
     }
     $viewer->assign('RECORD_STRUCTURE', $recordStructure);
     $viewer->assign('WORKFLOW_MODEL', $workFlowModel);
     $viewer->assign('MODULE_MODEL', $selectedModule);
     $viewer->assign('SELECTED_MODULE_NAME', $selectedModuleName);
     $dateFilters = Vtiger_Field_Model::getDateFilterTypes();
     foreach ($dateFilters as $comparatorKey => $comparatorInfo) {
         $comparatorInfo['startdate'] = DateTimeField::convertToUserFormat($comparatorInfo['startdate']);
         $comparatorInfo['enddate'] = DateTimeField::convertToUserFormat($comparatorInfo['enddate']);
         $comparatorInfo['label'] = vtranslate($comparatorInfo['label'], $qualifiedModuleName);
         $dateFilters[$comparatorKey] = $comparatorInfo;
     }
     $viewer->assign('DATE_FILTERS', $dateFilters);
     $viewer->assign('ADVANCED_FILTER_OPTIONS', Settings_Workflows_Field_Model::getAdvancedFilterOptions());
     $viewer->assign('ADVANCED_FILTER_OPTIONS_BY_TYPE', Settings_Workflows_Field_Model::getAdvancedFilterOpsByFieldType());
     $viewer->assign('COLUMNNAME_API', 'getWorkFlowFilterColumnName');
     $viewer->assign('FIELD_EXPRESSIONS', Settings_Workflows_Module_Model::getExpressions());
     $viewer->assign('META_VARIABLES', Settings_Workflows_Module_Model::getMetaVariables());
     // Added to show filters only when saved from vtiger6
     if ($workFlowModel->isFilterSavedInNew()) {
         $viewer->assign('ADVANCE_CRITERIA', $workFlowModel->transformToAdvancedFilterCondition());
     } else {
         $viewer->assign('ADVANCE_CRITERIA', "");
     }
     $viewer->assign('IS_FILTER_SAVED_NEW', $workFlowModel->isFilterSavedInNew());
     $viewer->assign('MODULE', $moduleName);
     $viewer->assign('QUALIFIED_MODULE', $qualifiedModuleName);
     $viewer->view('Step2.tpl', $qualifiedModuleName);
 }
Example #29
0
 public static function runScheduledImport()
 {
     global $current_user;
     $scheduledImports = self::getScheduledImport();
     $vtigerMailer = new Vtiger_Mailer();
     $vtigerMailer->IsHTML(true);
     foreach ($scheduledImports as $scheduledId => $importDataController) {
         $current_user = $importDataController->user;
         $importDataController->batchImport = false;
         if (!$importDataController->initializeImport()) {
             continue;
         }
         $importDataController->importData();
         $importStatusCount = $importDataController->getImportStatusCount();
         $emailSubject = 'vtiger CRM - Scheduled Import Report for ' . $importDataController->module;
         $viewer = new Vtiger_Viewer();
         $viewer->assign('FOR_MODULE', $importDataController->module);
         $viewer->assign('INVENTORY_MODULES', getInventoryModules());
         $viewer->assign('IMPORT_RESULT', $importStatusCount);
         $importResult = $viewer->view('Import_Result_Details.tpl', 'Import', true);
         $importResult = str_replace('align="center"', '', $importResult);
         $emailData = 'vtiger CRM has just completed your import process. <br/><br/>' . $importResult . '<br/><br/>' . 'We recommend you to login to the CRM and check few records to confirm that the import has been successful.';
         $userName = getFullNameFromArray('Users', $importDataController->user->column_fields);
         $userEmail = $importDataController->user->email1;
         $vtigerMailer->to = array(array($userEmail, $userName));
         $vtigerMailer->Subject = $emailSubject;
         $vtigerMailer->Body = $emailData;
         $vtigerMailer->Send();
         $importDataController->finishImport();
     }
     Vtiger_Mailer::dispatchQueue(null);
 }
Example #30
0
 /** Function to get the columns for the reportid
  *  This function accepts the $reportid and $outputformat (optional)
  *  This function returns  $columnslist Array: $tablename:$columnname:$fieldlabel:$fieldname:$typeofdata=>$tablename.$columnname As Header value,
  *					$tablename1:$columnname1:$fieldlabel1:$fieldname1:$typeofdata1=>$tablename1.$columnname1 As Header value,
  *					|
  *					$tablenamen:$columnnamen:$fieldlabeln:$fieldnamen:$typeofdatan=>$tablenamen.$columnnamen As Header value
  */
 function getQueryColumnsList($reportid, $outputformat = '')
 {
     // Have we initialized information already?
     if ($this->_columnslist !== false) {
         return $this->_columnslist;
     }
     global $adb, $modules, $log, $current_user, $current_language;
     $ssql = "select vtiger_selectcolumn.* from vtiger_report inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid";
     $ssql .= " left join vtiger_selectcolumn on vtiger_selectcolumn.queryid = vtiger_selectquery.queryid";
     $ssql .= " where vtiger_report.reportid = ?";
     $ssql .= " order by vtiger_selectcolumn.columnindex";
     $result = $adb->pquery($ssql, array($reportid));
     $permitted_fields = array();
     while ($columnslistrow = $adb->fetch_array($result)) {
         $fieldname = '';
         $fieldcolname = decode_html($columnslistrow['columnname']);
         if (strpos($fieldcolname, ':') === false) {
             continue;
         }
         list($tablename, $colname, $module_field, $fieldname, $single) = explode(":", $fieldcolname);
         $module_field = decode_html($module_field);
         list($module, $field) = explode("_", $module_field, 2);
         $inventory_fields = array('quantity', 'listprice', 'serviceid', 'productid', 'discount', 'comment');
         $inventory_modules = getInventoryModules();
         require 'user_privileges/user_privileges_' . $current_user->id . '.php';
         if ((!isset($permitted_fields[$module]) || sizeof($permitted_fields[$module]) == 0) && $is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
             $permitted_fields[$module] = $this->getaccesfield($module);
         }
         if (in_array($module, $inventory_modules) and isset($permitted_fields[$module]) and is_array($permitted_fields[$module])) {
             $permitted_fields[$module] = array_merge($permitted_fields[$module], $inventory_fields);
         }
         $selectedfields = explode(":", $fieldcolname);
         if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && !in_array($selectedfields[3], $permitted_fields[$module])) {
             //user has no access to this field, skip it.
             continue;
         }
         $concatSql = getSqlForNameInDisplayFormat(array('first_name' => $selectedfields[0] . ".first_name", 'last_name' => $selectedfields[0] . ".last_name"), 'Users');
         $querycolumns = $this->getEscapedColumns($selectedfields);
         if (isset($module) && $module != "") {
             $mod_strings = return_module_language($current_language, $module);
         }
         $fieldlabel = trim(preg_replace("/{$module}/", " ", $selectedfields[2], 1));
         $mod_arr = explode('_', $fieldlabel);
         $fieldlabel = trim(str_replace("_", " ", $fieldlabel));
         //modified code to support i18n issue
         $fld_arr = explode(" ", $fieldlabel);
         if ($mod_arr[0] == '') {
             $mod = $module;
             $mod_lbl = getTranslatedString($module, $module);
             //module
         } else {
             $mod = $mod_arr[0];
             array_shift($fld_arr);
             $mod_lbl = getTranslatedString($fld_arr[0], $mod);
             //module
         }
         $fld_lbl_str = implode(" ", $fld_arr);
         $fld_lbl = getTranslatedString($fld_lbl_str, $module);
         //fieldlabel
         $fieldlabel = $mod_lbl . " " . $fld_lbl;
         if ($selectedfields[0] == "vtiger_usersRel1" && $selectedfields[1] == 'user_name' && $selectedfields[2] == 'Quotes_Inventory_Manager') {
             $columnslist[$fieldcolname] = "trim( {$concatSql} ) as " . $module . "_Inventory_Manager";
             continue;
         }
         if (CheckFieldPermission($fieldname, $mod) != 'true' && $colname != "crmid" && (!in_array($fieldname, $inventory_fields) && in_array($module, $inventory_modules)) || empty($fieldname)) {
             continue;
         } else {
             $header_label = $selectedfields[2];
             // Header label to be displayed in the reports table
             // To check if the field in the report is a custom field
             // and if yes, get the label of this custom field freshly from the vtiger_field as it would have been changed.
             // Asha - Reference ticket : #4906
             if ($querycolumns == '') {
                 if ($selectedfields[4] == 'C') {
                     $field_label_data = explode("_", $selectedfields[2]);
                     $module = $field_label_data[0];
                     if ($module != $this->primarymodule) {
                         $columnslist[$fieldcolname] = "case when (" . $selectedfields[0] . "." . $selectedfields[1] . "='1')then '" . getTranslatedString('LBL_YES') . "' else case when (vtiger_crmentity{$module}.crmid !='') then '" . getTranslatedString('LBL_NO') . "' else '-' end end as '{$selectedfields['2']}'";
                     } else {
                         $columnslist[$fieldcolname] = "case when (" . $selectedfields[0] . "." . $selectedfields[1] . "='1')then '" . getTranslatedString('LBL_YES') . "' else case when (vtiger_crmentity.crmid !='') then '" . getTranslatedString('LBL_NO') . "' else '-' end end as '{$selectedfields['2']}'";
                     }
                 } elseif ($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'status') {
                     $columnslist[$fieldcolname] = " case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end as Calendar_Status";
                 } elseif ($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'date_start') {
                     $columnslist[$fieldcolname] = "cast(concat(vtiger_activity.date_start,'  ',vtiger_activity.time_start) as DATETIME) as Calendar_Start_Date_and_Time";
                 } elseif (stristr($selectedfields[0], "vtiger_users") && $selectedfields[1] == 'user_name') {
                     $temp_module_from_tablename = str_replace("vtiger_users", "", $selectedfields[0]);
                     if ($module != $this->primarymodule) {
                         $condition = "and vtiger_crmentity" . $module . ".crmid!=''";
                     } else {
                         $condition = "and vtiger_crmentity.crmid!=''";
                     }
                     if ($temp_module_from_tablename == $module) {
                         $columnslist[$fieldcolname] = " case when(" . $selectedfields[0] . ".last_name NOT LIKE '' {$condition} ) THEN " . $concatSql . " else vtiger_groups" . $module . ".groupname end as '" . $module . "_{$field}'";
                     } else {
                         //Some Fields can't assigned to groups so case avoided (fields like inventory manager)
                         $columnslist[$fieldcolname] = $selectedfields[0] . ".user_name as '" . $header_label . "'";
                     }
                 } elseif (stristr($selectedfields[0], "vtiger_crmentity") && $selectedfields[1] == 'modifiedby') {
                     $concatSql = getSqlForNameInDisplayFormat(array('last_name' => 'vtiger_lastModifiedBy' . $module . '.last_name', 'first_name' => 'vtiger_lastModifiedBy' . $module . '.first_name'), 'Users');
                     $columnslist[$fieldcolname] = "trim({$concatSql}) as {$header_label}";
                 } elseif ($selectedfields[0] == "vtiger_crmentity" . $this->primarymodule) {
                     $columnslist[$fieldcolname] = "vtiger_crmentity." . $selectedfields[1] . " AS '" . $header_label . "'";
                 } elseif ($selectedfields[0] == 'vtiger_products' && $selectedfields[1] == 'unit_price') {
                     $columnslist[$fieldcolname] = "concat(" . $selectedfields[0] . ".currency_id,'::',innerProduct.actual_unit_price) as '" . $header_label . "'";
                 } elseif (in_array($selectedfields[2], $this->append_currency_symbol_to_value)) {
                     $columnslist[$fieldcolname] = "concat(" . $selectedfields[0] . ".currency_id,'::'," . $selectedfields[0] . "." . $selectedfields[1] . ") as '" . $header_label . "'";
                 } elseif ($selectedfields[0] == 'vtiger_notes' && ($selectedfields[1] == 'filelocationtype' || $selectedfields[1] == 'filesize' || $selectedfields[1] == 'folderid' || $selectedfields[1] == 'filestatus')) {
                     if ($selectedfields[1] == 'filelocationtype') {
                         $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when 'I' then 'Internal' when 'E' then 'External' else '-' end as '{$selectedfields['2']}'";
                     } else {
                         if ($selectedfields[1] == 'folderid') {
                             $columnslist[$fieldcolname] = "vtiger_attachmentsfolder.foldername as '{$selectedfields['2']}'";
                         } elseif ($selectedfields[1] == 'filestatus') {
                             $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when '1' then '" . getTranslatedString('LBL_YES') . "' when '0' then '" . getTranslatedString('LBL_NO') . "' else '-' end as '{$selectedfields['2']}'";
                         } elseif ($selectedfields[1] == 'filesize') {
                             $columnslist[$fieldcolname] = "case " . $selectedfields[0] . "." . $selectedfields[1] . " when '' then '-' else concat(" . $selectedfields[0] . "." . $selectedfields[1] . "/1024,'  ','KB') end as '{$selectedfields['2']}'";
                         }
                     }
                 } elseif ($selectedfields[0] == 'vtiger_inventoryproductrel') {
                     if ($selectedfields[1] == 'discount') {
                         $columnslist[$fieldcolname] = " case when (vtiger_inventoryproductrel{$module}.discount_amount != '') then vtiger_inventoryproductrel{$module}.discount_amount else ROUND((vtiger_inventoryproductrel{$module}.listprice * vtiger_inventoryproductrel{$module}.quantity * (vtiger_inventoryproductrel{$module}.discount_percent/100)),3) end as '" . $header_label . "'";
                     } else {
                         if ($selectedfields[1] == 'productid') {
                             $columnslist[$fieldcolname] = "vtiger_products{$module}.productname as '" . $header_label . "'";
                         } else {
                             if ($selectedfields[1] == 'serviceid') {
                                 $columnslist[$fieldcolname] = "vtiger_service{$module}.servicename as '" . $header_label . "'";
                             } else {
                                 $columnslist[$fieldcolname] = $selectedfields[0] . $module . "." . $selectedfields[1] . " as '" . $header_label . "'";
                             }
                         }
                     }
                 } elseif ($selectedfields[0] == 'vtiger_inventoryproductrel' . $module) {
                     if ($selectedfields[1] == 'discount') {
                         $columnslist[$fieldcolname] = " case when (vtiger_inventoryproductrel{$module}.discount_amount != '') then vtiger_inventoryproductrel{$module}.discount_amount else ROUND((vtiger_inventoryproductrel{$module}.listprice * vtiger_inventoryproductrel{$module}.quantity * (vtiger_inventoryproductrel{$module}.discount_percent/100)),3) end as '" . $header_label . "'";
                     } else {
                         if ($selectedfields[1] == 'productid') {
                             $columnslist[$fieldcolname] = "vtiger_products{$module}.productname as '" . $header_label . "'";
                         } else {
                             if ($selectedfields[1] == 'serviceid') {
                                 $columnslist[$fieldcolname] = "vtiger_service{$module}.servicename as '" . $header_label . "'";
                             } else {
                                 $columnslist[$fieldcolname] = $selectedfields[0] . "." . $selectedfields[1] . " as '" . $header_label . "'";
                             }
                         }
                     }
                 } elseif (stristr($selectedfields[1], 'cf_') == true && stripos($selectedfields[1], 'cf_') == 0) {
                     $columnslist[$fieldcolname] = $selectedfields[0] . "." . $selectedfields[1] . " AS '" . $adb->sql_escape_string(decode_html($header_label)) . "'";
                 } else {
                     $columnslist[$fieldcolname] = $selectedfields[0] . "." . $selectedfields[1] . " AS '" . $header_label . "'";
                 }
             } else {
                 $columnslist[$fieldcolname] = $querycolumns;
             }
         }
     }
     $columnslist['vtiger_crmentity:crmid:LBL_ACTION:crmid:I'] = 'vtiger_crmentity.crmid AS "LBL_ACTION"';
     // Save the information
     $this->_columnslist = $columnslist;
     $log->info("ReportRun :: Successfully returned getQueryColumnsList" . $reportid);
     return $columnslist;
 }