/** * Method to be used for my MyEndpoint/GetExample endpoint */ public function GetReportData($api, $args) { global $current_user, $db; require_once 'modules/asol_Reports/include_basic/generateReportsFunctions.php'; require_once 'modules/asol_Reports/include_basic/reportsUtils.php'; $displayReportDashlet = true; $reportId = $args['reportId']; $dashletId = create_guid(); $fixedDashletId = str_replace("-", "", $dashletId); //**************************// //***Is Domains Installed***// //**************************// if (asol_ReportsUtils::isDomainsInstalled()) { $reportDomainQuery = $db->query("SELECT asol_reports.asol_domain_id as domain_id, asol_domains.name as domain_name FROM asol_reports LEFT JOIN asol_domains ON asol_reports.asol_domain_id=asol_domains.id WHERE asol_reports.id='" . $reportId . "'"); $reportDomainRow = $db->fetchByAssoc($reportDomainQuery); $displayReportDashlet = empty($reportId) || asol_ReportsGenerationFunctions::manageReportDomain($reportId, $current_user->asol_default_domain, $reportDomainRow['domain_id']); } //**************************// //***Is Domains Installed***// //**************************// if ($displayReportDashlet) { if (!empty($reportId)) { $getLibraries = $_REQUEST['getLibraries'] === 'true' ? true : false; $reportHtml = ($getLibraries ? asol_ReportsGenerationFunctions::generateDashletLibraries($reportId) : '') . '<script>' . asol_ReportsGenerationFunctions::getReloadCurrentDashletScriptFunction($reportId, true, $dashletId, false, null, null, $current_user->id, false) . '</script>' . '<div id="externalHtmlReport' . $dashletId . '"> <img id="loadingGIF' . $dashletId . '" src="themes/default/images/img_loading.gif"><span id="loadingTEXT' . $dashletId . '">' . translate("LBL_REPORT_LOADING", "asol_Reports") . '</span> </div> <script> loadCurrentDashletReport' . $fixedDashletId . '(); </script>'; } else { $reportHtml = '<div align="center">No Report Selected</div>'; } } else { $reportHtml = '<div align="center"></div>'; } $reportHtml = str_replace(chr(13), "", str_replace(chr(10), "", $reportHtml)); return json_decode(json_encode(array('dashletId' => $dashletId, 'html' => $reportHtml))); }
$time1 = explode(",", $values[3]); $values[3] = date("H,i", @mktime($time1[0], $time1[1], 0, date("m"), date("d"), date("Y")) + $hourOffset); $tasks[$key] = implode(":", $values); } $localMachineOffSet = date("Z"); $focus->report_tasks = empty($tasks) ? '${GMT}' : implode("|", $tasks) . $localMachineOffSet / 3600; $focus->email_list = $_REQUEST['email_list']; } else { $focus->id = $_REQUEST['record']; $focus->deleted = 1; } $reportId = $focus->save(); //*************************// //***Publication Domains***// //*************************// if (asol_ReportsUtils::isDomainsInstalled()) { require_once "modules/asol_Domains/AlineaSolDomainsFunctions.php"; asol_manageDomains::managePublicationDomainRequest('asol_domain_published_mode', 'asol_domain_child_share_depth', 'asol_multi_create_domain', 'asol_published_domain'); } //*************************// //***Publication Domains***// //*************************// //Redireccionar a la pantalla 'search.php' if (isset($_POST['return_module']) && $_POST['return_module'] != "") { $return_module = $_POST['return_module']; } else { $return_module = "asol_Reports"; } if (isset($_POST['return_action']) && $_POST['return_action'] != "") { $return_action = $_POST['return_action']; } else {
public function display() { global $current_user, $db; require_once('modules/asol_Reports/include_basic/generateReportsFunctions.php'); $displayReportDashlet = true; $reportId = (isset($this->which_chart[0])) ? $this->which_chart[0] : null; $dashletId = $this->id; //**************************// //***Is Domains Installed***// //**************************// if (asol_ReportsUtils::isDomainsInstalled()) { $reportDomainQuery = $db->query("SELECT asol_reports.asol_domain_id as domain_id, asol_domains.name as domain_name FROM asol_reports LEFT JOIN asol_domains ON asol_reports.asol_domain_id=asol_domains.id WHERE asol_reports.id='".$reportId."'"); $reportDomainRow = $db->fetchByAssoc($reportDomainQuery); $displayReportDashlet = ((empty($reportId)) || (asol_ReportsGenerationFunctions::manageReportDomain($reportId, $current_user->asol_default_domain, $reportDomainRow['domain_id']))); } //**************************// //***Is Domains Installed***// //**************************// if ($displayReportDashlet) { if (!empty($reportId)) { return asol_ReportsGenerationFunctions::generateDashletReport($reportId, $dashletId, $this->processAutoRefresh()); } else { return '<div align="center"></div>'.$this->processAutoRefresh(); } } else { return '<script> $(document).ready(function() { $("li[id=\'dashlet_'.$dashletId.'\']").hide(); }); </script>'; } }
function displayReport($reportId, $vardefFilters, $sort_field, $sort_direction, $sort_index, $page_number = '', $isDashlet = false, $dashletId = '', $getLibraries = true, $returnHtml = false, $override_entries = null, $avoidAjaxRequest = false, $contextDomainId = null) { global $current_user, $timedate, $mod_strings, $app_strings, $theme, $db, $app_list_strings, $beanList, $beanFiles, $current_language, $sugar_config; require_once 'modules/asol_Reports/include_basic/reportsUtils.php'; require_once 'modules/asol_Reports/include_basic/ReportChart.php'; require_once 'modules/asol_Reports/ReportsDashletChart.php'; require_once 'modules/asol_Reports/include_basic/generateReportsFunctions.php'; //****************************// //****Instance Report Bean****// //****************************// $focus = BeanFactory::getBean('asol_Reports', $reportId); //****************************// //****Variables Definition****// //****************************// $hasVardefFilter = !empty($vardefFilters); $hasCurlRequestEnabled = isset($sugar_config["asolReportsCurlRequestUrl"]) ? true : false; $hasNoPagination = isset($sugar_config["asolReportsAvoidReportsPagination"]) && $sugar_config["asolReportsAvoidReportsPagination"] == true; $dispatcherMaxRequests = isset($sugar_config['asolReportsDispatcherMaxRequests']) ? $sugar_config['asolReportsDispatcherMaxRequests'] : 0; $dashletExportButtons = isset($sugar_config['asolReportsDashletExportButtons']) ? $sugar_config['asolReportsDashletExportButtons'] : true; $isHttpReportRequest = isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "httpReportRequest"; $isReloadReport = isset($_REQUEST['entryPoint']) && $_REQUEST['entryPoint'] == 'reloadReport'; $isWsExecution = isset($_REQUEST['asolReportsWebServiceExecution']) && $_REQUEST['asolReportsWebServiceExecution']; $entryPointExecuted = isset($_REQUEST['entryPoint']) && in_array($_REQUEST['entryPoint'], array('reloadReport', 'viewReport')); $executeReportDirectly = !$hasCurlRequestEnabled || $avoidAjaxRequest; $reorderDetailGroups = true; //*********************************// //***Unserialize Report Elements***// //*********************************// $storedSelectedFields = unserialize(base64_decode($focus->report_fields)); $storedSelectedFilters = unserialize(base64_decode($focus->report_filters)); $storedSelectedCharts = unserialize(base64_decode($focus->report_charts_detail)); $storedSelectedDescription = unserialize(base64_decode($focus->description)); //***********************// //***AlineaSol Premium***// //***********************// $predefinedTemplatesResult = asol_ReportsUtils::managePremiumFeature("templatesReports", "reportFunctions.php", "getPredefinedTemplates", array('json_encode' => false, 'currentModule' => null)); $predefinedTemplates = $predefinedTemplatesResult !== false ? $predefinedTemplatesResult : null; //***********************// //***AlineaSol Premium***// //***********************// //***********************// //***AlineaSol Premium***// //***********************// $currentReportCss = asol_ReportsUtils::managePremiumFeature("cssPerReport", "reportFunctions.php", "getCurrentReportCss", array('reportTemplates' => $storedSelectedFields['tables'][0]['templates'], 'selectedValue' => $storedSelectedFields['tables'][0]['css'], 'jsonCssTemplates' => $predefinedTemplates['css'], 'dashletId' => $dashletId)); //***********************// //***AlineaSol Premium***// //***********************// //****************************// //*****module Strings FIX*****// //****************************// $mod_strings['MSG_REPORT_SEND_EMAIL_ALERT'] = str_replace("'", "\\'", str_replace("'", "\\'", translate('MSG_REPORT_SEND_EMAIL_ALERT', 'asol_Reports'))); //****************************************// //****Check if External App is defined****// //****************************************// $reportScheduledTypeArray = explode('${dollar}', $focus->report_scheduled_type); $reportScheduledAppArray = explode('${pipe}', $reportScheduledTypeArray[1]); $hasExternalApp = !empty($reportScheduledAppArray[1]); //****************************************// //********Get External Parameters*********// //****************************************// $externalParams = asol_ReportsGenerationFunctions::getExternalRequestParams(); $current_language = $externalParams["current_language"]; $mod_strings = $externalParams["mod_strings"]; $current_user = $externalParams["current_user"]; //****************************************// //****Clean DataBase Report Dispatcher****// //****************************************// if (empty($vardefFilters)) { asol_ReportsGenerationFunctions::cleanDataBaseReportDispatcher(); } $reportTypeSplitted = explode(':', $focus->report_type); $reportType = $reportTypeSplitted[0]; //report_type if ($reportType === 'webservice_remote' && $entryPointExecuted) { //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('reportId' => $reportId, 'vardefFilters' => $vardefFilters, 'sort_field' => $sort_field, 'sort_direction' => $sort_direction, 'sort_index' => $sort_index, 'page_number' => $page_number, 'isDashlet' => $isDashlet, 'dashletId' => $dashletId, 'getLibraries' => $getLibraries); $executedWebServiceReport = asol_ReportsUtils::managePremiumFeature("webServiceReport", "reportFunctions.php", "executeWebServiceReport", $extraParams); $executedWebServiceReportHtml = $executedWebServiceReport !== false ? $executedWebServiceReport : null; //***********************// //***AlineaSol Premium***// //***********************// $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/"; $httpHtmlFile = $_REQUEST['httpHtmlFile']; $justDisplay = !$isHttpReportRequest; if (isset($justDisplay) && $justDisplay) { if ($returnHtml) { return $executedWebServiceReportHtml; } else { echo $executedWebServiceReportHtml; } } else { $exportHttpFile = fopen($tmpFilesDir . $httpHtmlFile, "w"); fwrite($exportHttpFile, $executedWebServiceReportHtml); fclose($exportHttpFile); if ($returnHtml) { return false; } } } else { if ($reportType === 'stored' && $_REQUEST['entryPoint'] != 'viewReport') { // Stored Report! //****************************************// //*********Get Stored Report Data*********// //****************************************// $reportType = explode(':', $focus->report_type); echo asol_ReportsGenerationFunctions::getStoredReportData($reportType[1], $reportId, $isDashlet, $dashletId, $focus->report_charts); } else { // Anything else Report! if ($entryPointExecuted || $executeReportDirectly) { //*********************************// //****Check Access To Reports******// //*********************************// if (!ACLController::checkAccess('asol_Reports', 'view', true) && !$hasVardefFilter) { die("<font color='red'>" . $app_strings["LBL_EMAIL_DELETE_ERROR_DESC"] . "</font>"); } //*************************************************// //******Requiring FilesGet External Parameters*****// //*************************************************// require_once "include/SugarPHPMailer.php"; require_once 'modules/asol_Reports/include_basic/ReportExcel.php'; require_once 'modules/asol_Reports/include_basic/ReportFile.php'; require_once 'modules/asol_Reports/include_basic/ReportChart.php'; require_once 'modules/asol_Reports/include_basic/manageReportsFunctions.php'; require_once 'modules/asol_Reports/include_basic/generateQuery.php'; //*****************************// //****Variable Definition******// //*****************************// $fixedReportId = str_replace("-", "", $focus->id); $return_action = isset($_REQUEST['return_action']) ? $_REQUEST['return_action'] : ""; //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('isDynamic' => $focus->dynamic_tables == '1', 'dynamicTableValue' => $focus->dynamic_sql, 'usedDb' => $focus->alternative_database >= 0 ? $focus->alternative_database : false); $matchTablesResult = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "getMatchTablesResult", $extraParams); $reportUsedModules = $matchTablesResult !== false ? $matchTablesResult : array($focus->report_module); $multiModuleReport = $matchTablesResult !== false && count($matchTablesResult) > 1; $hasNoPagination = $multiModuleReport ? true : $hasNoPagination; $externalDbSimpleName = $matchTablesResult !== false ? true : false; //***********************// //***AlineaSol Premium***// //***********************// $report_data['record'] = $focus->id; $report_data['report_name'] = $focus->name; $report_data['audited_report'] = $focus->audited_report; $report_data['description'] = $focus->description; $report_data['assigned_user_id'] = $focus->assigned_user_id; $report_data['created_by'] = $focus->created_by; $report_data['report_attachment_format'] = $focus->report_attachment_format; $report_data['report_charts'] = $focus->report_charts; $report_data['report_charts_engine'] = $focus->report_charts_engine; $report_data['scheduled_images'] = $focus->scheduled_images; $report_data['row_index_display'] = $focus->row_index_display; $report_data['results_limit'] = $focus->results_limit; $report_data['table_config'] = asol_ReportsGenerationFunctions::getTableConfiguration($focus->report_fields, 0); $audited_report = $report_data['audited_report'] == '1' ? true : false; $availableReport = true; $oversizedReport = false; $detailMultiQuery = isset($report_data['table_config']['multiQuery']) && $report_data['table_config']['multiQuery']; $displayTotals = !isset($report_data['table_config']['totals']['visible']) || $report_data['table_config']['totals']['visible']; $displaySubtotals = !isset($report_data['table_config']['subtotals']['visible']) || $report_data['table_config']['subtotals']['visible']; $displayPagination = isset($report_data['table_config']['pagination']['visible']) ? $report_data['table_config']['pagination']['visible'] : 'all'; $displayTotals = false; $displaySubtotals = false; $allowExportGeneratedFile = !isset($vardefFilters) || $isWsExecution; $externalCall = false; $schedulerCall = false; $userTZ = null; $searchCriteria = isset($_REQUEST['search_criteria']); $currentUserId = $_REQUEST['currentUserId']; //****************************************// //****External Dispatcher Management******// //****************************************// if (!$hasVardefFilter && isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "external") { asol_ReportsGenerationFunctions::manageReportExternalDispatcher($dispatcherMaxRequests); asol_ReportsUtils::reports_log('asol', 'Executing Report with Id [' . $reportId . ']' . (asol_ReportsUtils::isDomainsInstalled() ? ' Domain [' . $contextDomainId . ']' : ''), __FILE__, __METHOD__, __LINE__); } if (isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "external" || isset($_REQUEST['schedulerCall']) && $_REQUEST['schedulerCall'] == "true") { //**********************************************************// //********Manage External Execution Report Variables********// //**********************************************************// $externalCall = true; $overridedExternalVariables = asol_ReportsGenerationFunctions::overrideExternalReportVariables($report_data['created_by']); $theUser = $overridedExternalVariables["theUser"]; $current_user = $overridedExternalVariables["current_user"]; $allowExportGeneratedFile = $overridedExternalVariables["allowExportGeneratedFile"]; $schedulerCall = $overridedExternalVariables["schedulerCall"]; $externalUserDateFormat = $overridedExternalVariables["externalUserDateFormat"]; $externalUserDateTimeFormat = $overridedExternalVariables["externalUserDateTimeFormat"]; } //*************************************// //********Manage Report Domain*********// //*************************************// if (asol_ReportsUtils::isDomainsInstalled()) { $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain; if ($focus->report_type !== 'external') { $manageReportDomain = asol_ReportsGenerationFunctions::manageReportDomain($reportId, $reportDomain, $focus->asol_domain_id); if (!$manageReportDomain) { $availableReport = false; if ($returnHtml) { return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; } else { include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; exit; } } } } //*********************************************************// //********Reset Global Format & UserPrefs Variables********// //*********************************************************// $userDateFormat = $externalCall ? $externalUserDateFormat : $current_user->getPreference('datef'); $userDateTimeFormat = $externalCall ? $externalUserDateTimeFormat : $current_user->getPreference('datef') . ' ' . $current_user->getPreference('timef'); $gmtZone = $externalCall ? $theUser->getUserDateTimePreferences() : $current_user->getUserDateTimePreferences(); $userTZlabel = $externalCall ? $theUser->getPreference("timezone") . " " . $gmtZone["userGmt"] : $current_user->getPreference("timezone") . " " . $gmtZone["userGmt"]; $userTZ = $externalCall ? $theUser->getPreference("timezone") : $current_user->getPreference("timezone"); date_default_timezone_set($userTZ); $phpDateTime = new DateTime(null, new DateTimeZone($userTZ)); $hourOffset = $phpDateTime->getOffset() * -1; //****************************************// //*****Get Current User Configuration*****// //****************************************// $currentUserAsolConfig = asol_ReportsGenerationFunctions::getCurrentUserAsolConfig($current_user->id); $quarter_month = $currentUserAsolConfig["quarter_month"]; $entriesPerPage = $currentUserAsolConfig["entriesPerPage"]; $pdf_orientation = $currentUserAsolConfig["pdf_orientation"]; $week_start = $currentUserAsolConfig["week_start"]; $pdf_img_scaling_factor = $currentUserAsolConfig["pdf_img_scaling_factor"]; $scheduled_files_ttl = $currentUserAsolConfig["scheduled_files_ttl"]; $host_name = $currentUserAsolConfig["host_name"]; //**************************************// //****Override Pagination Parameters****// //**************************************// if ($externalCall || $hasNoPagination) { $entriesPerPage = 1000000; } //***********************// //***AlineaSol Premium***// //***********************// if ($hasVardefFilter) { $extraParams = array('overrideEntries' => $override_entries); $paginationEntries = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getReportFieldsManagementPaginationEntries", $extraParams); if ($paginationEntries !== false) { $hasNoPagination = false; $entriesPerPage = $paginationEntries; } } //***********************// //***AlineaSol Premium***// //***********************// //*****************************// //*****Variable Definition*****// //*****************************// $rs_user_name = asol_Report::getSelectionResults("SELECT user_name FROM users WHERE id = '" . $focus->assigned_user_id . "'", null, false); $report_data['assigned_user_name'] = $rs_user_name[0]['user_name']; $reportType = explode(':', $focus->report_type); $report_data['report_type'] = $reportType[0]; $report_data['report_type_stored_data'] = $reportType[1]; $isStoredReport = $report_data['report_type'] == 'stored' ? true : false; $report_data['email_list'] = $focus->email_list; $report_name = $focus->name; $report_filters = $focus->report_filters; $report_charts = $report_data['report_charts']; $report_charts_engine = $report_data['report_charts_engine']; //********************************************// //*****Resultation Arrays Initialization******// //********************************************// $rs = array(); $rsTotals = array(); $subGroups = array(); $subTotals = array(); $subTotalsC = array(); foreach ($reportUsedModules as $moduleIteration => $currentUsedModule) { $lastModuleIteration = $moduleIteration === count($reportUsedModules) - 1; //******************************// //***Get Back Report Elements***// //******************************// $selectedFields = $storedSelectedFields; $selectedFilters = $storedSelectedFilters; $selectedCharts = $storedSelectedCharts; $selectedDescription = $storedSelectedDescription; //*********************************************// //**Execute report with default filter values**// //*********************************************// $initialExecution = $selectedFilters['config']['initialExecution']; if (isset($initialExecution) && $initialExecution) { $searchCriteria = true; } //*****************************// //*****Variable Definition*****// //*****************************// $publicDescription = $selectedDescription['public']; $report_module = $report_data['report_module'] = $focus->report_module = $currentUsedModule; //********************************************// //*****Managing External Database Queries*****// //********************************************// $alternativeDb = $focus->alternative_database >= 0 ? $focus->alternative_database : false; $externalDataBaseQueryParams = asol_ReportsGenerationFunctions::manageExternalDatabaseQueries($alternativeDb, $report_module, $externalDbSimpleName); $useExternalDbConnection = true; $useAlternativeDbConnection = $externalDataBaseQueryParams["useAlternativeDbConnection"]; $domainField = $externalDataBaseQueryParams["domainField"]; $gmtDates = $externalDataBaseQueryParams["gmtDates"]; $report_module = $externalDataBaseQueryParams["report_module"]; $report_table = $externalDataBaseQueryParams["report_table"]; $report_table_primary_key = $externalDataBaseQueryParams["report_table_primary_key"]; //*****************************// //*******Temporal Fixes********// //*****************************// asol_ReportsGenerationFunctions::doTemporalFixes($report_table, $selectedFields, $selectedFilters); //*************************************// //******Generate Chart Info Array******// //*************************************// $urlChart = array(); $chartSubGroupsValues = array(); $chartInfoParams = asol_ReportsGenerationFunctions::getChartInfoParams($selectedCharts, $audited_report, $report_table); $hasStackChart = $chartInfoParams["hasStackChart"]; $chartInfo = $chartInfoParams["chartInfo"]; $chartConfig = $chartInfoParams["chartConfig"]; //***********************************************// //*******Manage Filters & External Filters*******// //***********************************************// $extFilters = asol_ReportsGenerationFunctions::buildExternalFilters($_REQUEST["external_filters"], $vardefFilters, $userDateFormat); $filteringParams = asol_ReportsGenerationFunctions::getFilteringParams($selectedFilters, $extFilters, $report_module, $predefinedTemplates, $dashletId, $userDateFormat, $audited_report); $filterValuesData = $filteringParams["filterValues"]["data"]; $filtersPanel = $filteringParams["filtersPanel"]; $filtersHiddenInputs = $filteringParams["filtersHiddenInputs"]; if ($filtersHiddenInputs == false || $searchCriteria == true) { //************************************// //*******Prepare SQL SubClauses*******// //************************************// foreach ($selectedFields['tables'][0]['data'] as $index => &$currentValues) { //***********************// //***AlineaSol Premium***// //***********************// $currentSql = asol_ReportsUtils::managePremiumFeature("predefinedTemplates", "reportFunctions.php", "getSqlTemplateValue", array('currentSQL' => $currentValues['sql'], 'template' => $currentValues['templates']['sql'], 'sqlTemplates' => $predefinedTemplates['sql'])); $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql']; asol_ReportsGenerateQuery::validateSqlRemovedFields($currentValues['sql'], $alternativeDb, $report_table); if (empty($currentValues['sql']) && !empty($currentValues["subQuery"]["module"])) { $externalDataBaseQueryParams = asol_ReportsGenerationFunctions::manageExternalDatabaseQueries($alternativeDb, $currentValues["subQuery"]['module'], true); $domainSubField = $externalDataBaseQueryParams["domainField"]; $currentSql = asol_ReportsUtils::managePremiumFeature("subReports", "reportFunctions.php", "getSqlFromSubReport", array('alternativeDb' => $alternativeDb, 'subQuery' => $currentValues["subQuery"], 'index' => $index, 'hourOffset' => $hourOffset, 'quarterMonth' => $quarter_month, 'weekStart' => $week_start, 'currentUser' => $current_user, 'schedulerCall' => $schedulerCall, 'reportDomain' => $reportDomain, 'domainField' => $domainSubField, 'sqlTemplates' => $predefinedTemplates['sql'])); $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql']; } //***********************// //***AlineaSol Premium***// //***********************// } //*********************************// //*******Get Queries [Joins]*******// //*********************************// $fieldsByRef = array(); $joinQueryArray = asol_ReportsGenerateQuery::getSqlJoinQuery($selectedFields, $filterValuesData, $report_data['results_limit'], $report_module, $report_table, $audited_report, $alternativeDb, $fieldsByRef, '', $domainField); $moduleCustomJoined = $joinQueryArray["moduleCustomJoined"]; $moduleCountCustomJoined = $joinQueryArray["moduleCountCustomJoined"]; $aliasIndexTable = $joinQueryArray["aliasIndexTable"]; $sqlJoin = $joinQueryArray["querys"]["Join"]; $sqlCountJoin = $joinQueryArray["querys"]["CountJoin"]; foreach ($selectedFields['tables'][0]['data'] as $index => &$currentValues) { //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('currentSql' => $currentValues['sql'], 'fieldsByRef' => $fieldsByRef, 'suppressChars' => true); $currentSql = asol_ReportsUtils::managePremiumFeature("sqlWithReferences", "reportFunctions.php", "replaceSqlReferenceByValue", $extraParams); $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql']; //***********************// //***AlineaSol Premium***// //***********************// } //**********************************// //*******Get Queries [Select]*******// //**********************************// $filtersByRef = array(); asol_ReportsGenerateQuery::generateSqlWhere($selectedFields, $filterValuesData, $report_table, $hourOffset, $quarter_month, $week_start, $fieldsByRef, $filtersByRef); $selectQueryArray = asol_ReportsGenerateQuery::getSqlSelectQuery($selectedFields, $chartInfo, $predefinedTemplates, $alternativeDb, $report_table, $hourOffset, $quarter_month, $week_start, $audited_report, $displayTotals, $displaySubtotals, $fieldsByRef, $filtersByRef, $aliasIndexTable, ''); $referenceAlias = $selectQueryArray["referenceAlias"]; $columns = $selectQueryArray["columns"]; $types = $selectQueryArray["types"]; $columnsU = $selectQueryArray["columnsU"]; //Untranslated Alias $columnsO = $selectQueryArray["columnsO"]; //Original Field with Join Alias $columnsN = $selectQueryArray["columnsN"]; //Not Modified Field $columnsI = $selectQueryArray["columnsI"]; //Field Index $isGroupedReport = $selectQueryArray["hasGrouped"]; $hasGroupedFunctionWithSQL = $isGroupedReport && $selectQueryArray["hasFunctionWithSQL"]; $groupSubTotalField = $selectQueryArray["groupSubTotalField"]; $groupSubTotalFieldAscSort = $selectQueryArray["groupSubTotalFieldAscSort"]; $totals = $selectQueryArray["totals"]; $resulset_fields = $selectQueryArray["resultsetFields"]; $sqlTotalsC = $selectQueryArray["querys"]["Charts"]; //***AlineaSol Premium***// $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlTotalsC)); if ($fieldSqlFilterReference !== false) { $sqlTotalsC = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlTotalsC; } //***AlineaSol Premium***// $sqlSelect = $selectQueryArray["querys"]["Select"]; //***AlineaSol Premium***// $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlSelect)); if ($fieldSqlFilterReference !== false) { $sqlSelect = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlSelect; } //***AlineaSol Premium***// $sqlTotals = $selectQueryArray["querys"]["Totals"]; //***AlineaSol Premium***// $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlTotals)); if ($fieldSqlFilterReference !== false) { $sqlTotals = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlTotals; } //***AlineaSol Premium***// //********************************// //*******Get Queries [From]*******// //********************************// $sqlFrom = asol_ReportsGenerateQuery::getSqlFromQuery($report_table, $audited_report, ''); //*********************************// //*******Get Queries [Where]*******// //*********************************// asol_ReportsGenerateQuery::replaceFiltersWithNamedFieldAlias($selectedFields, $filtersByRef); $sqlWhere = asol_ReportsGenerateQuery::getSqlWhereQuery($filtersByRef, $report_table, $useAlternativeDbConnection, ''); //***AlineaSol Premium***// $extraParams = array('currentSql' => $sqlWhere, 'fieldsByRef' => $fieldsByRef, 'suppressChars' => true); $currentSql = asol_ReportsUtils::managePremiumFeature("sqlWithReferences", "reportFunctions.php", "replaceSqlReferenceByValue", $extraParams); $sqlWhere = $currentSql !== false ? $currentSql : $sqlWhere; //***AlineaSol Premium***// if (asol_ReportsUtils::isDomainsInstalled()) { asol_ReportsGenerateQuery::modifySqlWhereForAsolDomainsQuery($sqlWhere, $report_table, $current_user, $schedulerCall, $reportDomain, $domainField, ''); } //***********************// //****Get Email Alert****// //***********************// $sendEmailquestion = asol_ReportsGenerationFunctions::getSendEmailAlert($focus->email_list, $reportDomain); //***********************************// //*******Get Queries [GroupBy]*******// //***********************************// $groupQueryArray = asol_ReportsGenerateQuery::getSqlGroupByQuery($selectedFields, $report_table, $filtersByRef); $sqlGroup = $groupQueryArray["querys"]["Group"]; $sqlChartGroup = $groupQueryArray["querys"]["ChartGroup"]; $details = $groupQueryArray["details"]; $groups = $groupQueryArray["groups"]; $isDetailedReport = $groupQueryArray["hasDetail"]; $isGroupedReport = $groupQueryArray["hasGrouped"]; $hasFunctionField = $groupQueryArray["hasFunctionField"]; $massiveData = $groupQueryArray["massiveData"]; //***********************************// //****Manage Query Autoprotection****// //***********************************// $totalEntries = asol_ReportsGenerationFunctions::getReportTotalEntries($sqlFrom, $sqlCountJoin, $sqlWhere, $sqlGroup, $details, $groups, $useExternalDbConnection, $alternativeDb); $checkMaxAllowedResults = isset($sugar_config['asolReportsMaxAllowedResults']) ? true : false; $checkMaxAllowedNotIndexedOrderBy = isset($sugar_config['asolReportsMaxAllowedNotIndexedOrderBy']) ? true : false; $checkMaxAllowedDisplayed = isset($sugar_config['asolReportsMaxAllowedDisplayed']) ? true : false; $checkMaxAllowedParseMultiTable = isset($sugar_config['asolReportsMaxAllowedParseMultiTable']) ? true : false; $maxAllowedResults = false; $maxAllowedNotIndexedOrderBy = false; if ($checkMaxAllowedResults || $checkMaxAllowedNotIndexedOrderBy || $checkMaxAllowedDisplayed || $checkMaxAllowedParseMultiTable) { $maxAllowedResultsQuery = "EXPLAIN " . $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlLimit; $maxAllowedResultsRow = asol_Report::getSelectionResults($maxAllowedResultsQuery, null, $useExternalDbConnection, $alternativeDb, null, null, true); $productResults = 1; foreach ($maxAllowedResultsRow as $maxAllowedResult) { if ($maxAllowedResult['select_type'] == 'PRIMARY') { $productResults *= $maxAllowedResult['rows']; } } $maxAllowedResults = $checkMaxAllowedResults && $sugar_config['asolReportsMaxAllowedResults'] < $productResults; $maxAllowedNotIndexedOrderBy = $checkMaxAllowedNotIndexedOrderBy && $sugar_config['asolReportsMaxAllowedNotIndexedOrderBy'] < $totalEntries; $entriesPhpProcessed = $hasNoPagination || $allowExportGeneratedFile ? $totalEntries : $entriesPerPage; $maxAllowedDisplayed = $checkMaxAllowedDisplayed && $sugar_config['asolReportsMaxAllowedDisplayed'] < $entriesPhpProcessed; $maxAllowedParseMultiTable = $checkMaxAllowedParseMultiTable && $multiModuleReport && $sugar_config['asolReportsMaxAllowedParseMultiTable'] < $entriesPhpProcessed; if ($maxAllowedResults) { asol_Report::manageMaxAllowedResultsReached($schedulerCall, $productResults, $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlLimit); } if ($maxAllowedDisplayed || $maxAllowedParseMultiTable) { $oversizedReport = true; } } if (!$oversizedReport) { //***********************************// //*******Get Queries [OrderBy]*******// //***********************************// $initialSortDirection = $sort_direction; $orderQueryArray = asol_ReportsGenerateQuery::getSqlOrderByQuery($selectedFields, $report_table, $alternativeDb, $maxAllowedNotIndexedOrderBy, $sort_field, $sort_direction, $sort_index); $hasDeletedNotIndexedOrderBy = $orderQueryArray['hasDeletedNotIndexedOrderBy']; $sqlOrder = $orderQueryArray["query"]; $sort_direction = $orderQueryArray["sortDirection"]; $sort_type = $orderQueryArray["sortType"]; //***********************************// //*******Pagination Management*******// //***********************************// if ($hasNoPagination) { $sqlLimit = ""; $sqlLimitExport = ""; $total_entries_basic = $totalEntries; } else { //*********************************// //*******Get Queries [Limit]*******// //*********************************// $orderQueryArray = asol_ReportsGenerateQuery::getSqlLimitQuery($report_data['results_limit'], $entriesPerPage, $page_number, $totalEntries, $externalCall); $sqlLimit = $orderQueryArray["querys"]["Limit"]; $sqlLimitExport = $orderQueryArray["querys"]["LimitExport"]; $total_entries_basic = $orderQueryArray["totalEntriesBasic"]; } //******************************************// //*****Correct Fields for Empty Reports*****// //******************************************// $correctedEmptyReport = asol_ReportsGenerationFunctions::correctEmptyReport($sqlSelect, $sqlTotals); $columns[0] = $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : $columns[0]; $sqlSelect .= $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : ""; $sqlOrder .= $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : ""; $sqlTotals .= $correctedEmptyReport["totals"]["sql"] !== null ? $correctedEmptyReport["totals"]["sql"] : ""; $totals[0]['alias'] = $correctedEmptyReport["totals"]["column"] !== null ? $correctedEmptyReport["totals"]["column"] : $totals[0]['alias']; //*******************************************************// //*****Get Extended Where Clause for Limited Reports*****// //*******************************************************// $sqlLimitSubSet = asol_ReportsGenerateQuery::getSqlSubSetLimitQuery($focus->alternative_database, $report_data['results_limit'], $totalEntries, $entriesPerPage, $page_number, $report_table, $report_table_primary_key, $sqlFrom, $sqlJoin, $sqlWhere, $sqlGroup); if ($audited_report) { //************************************// //********Manage Audited Field********// //************************************// $auditedFieldTypeArray = asol_Report::getFieldInfoFromVardefs($report_module, $filterValuesData[0]['parameters']['first'][0]); $auditedFieldType = $auditedFieldTypeArray["values"]; $auditedAppliedFields = array($report_table . "_audit.before_value_string", $report_table . "_audit.after_value_string", $report_table . "_audit.before_value_text", $report_table . "_audit.after_value_text"); } //************************************************************// //********Override Chart Names If Http Request Enabled********// //************************************************************// $chartsHttpQueryUrls = !isset($_REQUEST['chartsHttpQueryUrls']) ? array() : explode('${pipe}', $_REQUEST['chartsHttpQueryUrls']); //*************************// //******DETAIL REPORT******// //*************************// if ($isDetailedReport) { asol_ReportsUtils::reports_log('debug', 'Detailed Report', __FILE__, __METHOD__, __LINE__); //***************************************// //******Initialize Detail Variables******// //***************************************// $currentSubGroups = array(); $currentSubTotals = array(); $currentSubTotalsC = array(); $i = 0; $detailFieldInfo = $details[$i]; switch ($detailFieldInfo['grouping']) { case "Detail": //***********************************************// //*****Calculate Detail Pagination Variables*****// //***********************************************// $orderPaginationDetailVars = asol_ReportsGenerationFunctions::getOrderPaginationSingleDetailVars($detailFieldInfo, $detailMultiQuery, $report_data['results_limit'], $sqlFrom, $sqlJoin, $sqlWhere, $sqlGroup, $useExternalDbConnection, $alternativeDb); $rsGroups = $orderPaginationDetailVars["rsGroups"]; $sizes = $orderPaginationDetailVars["sizes"]; $fullSizes = $orderPaginationDetailVars["fullSizes"]; break; case "Minute Detail": case "Quarter Hour Detail": case "Hour Detail": case "Day Detail": case "DoW Detail": case "WoY Detail": case "Month Detail": case "Natural Quarter Detail": case "Fiscal Quarter Detail": case "Natural Year Detail": case "Fiscal Year Detail": //*************************************************************// //*****Calculate Day/DoW/Month Detail Pagination Variables*****// //*************************************************************// $orderPaginationMonthDayDetailVars = asol_ReportsGenerationFunctions::getOrderPaginationDateDetailVars($detailFieldInfo, $detailMultiQuery, $report_data['results_limit'], $sqlFrom, $sqlJoin, $sqlWhere, $useExternalDbConnection, $alternativeDb, $week_start); $rsGroups = $orderPaginationMonthDayDetailVars["rsGroups"]; $sizes = $orderPaginationMonthDayDetailVars["sizes"]; $fullSizes = $orderPaginationMonthDayDetailVars["fullSizes"]; $reorderDetailGroups = false; break; } //*************************************// //*****Manage Pagination Variables*****// //*************************************// $paginationMainVariables = asol_ReportsGenerationFunctions::getPaginationMainVariables($page_number, $entriesPerPage, $sizes); $init_group = $paginationMainVariables["init_group"]; $end_group = $paginationMainVariables["end_group"]; $current_entries = $paginationMainVariables["current_entries"]; $first_entry = $paginationMainVariables["first_entry"]; $groupField = array(); $subGroup = array(); if ($report_charts != "Char" || $hasStackChart && (count($groups) != 0 && strtolower($groups[0]['display']) == 'yes') || $report_data['results_limit'] != 'all') { $subGroupsExport = array(); $subTotalsExport = array(); $subTotalsExportNoFormat = array(); $groupField = array(); $subGroup = array(); if ($detailMultiQuery) { foreach ($rsGroups as $index => $currentGroup) { if ($report_data['results_limit'] == "all" && !$allowExportGeneratedFile && ($index < $init_group || $index > $end_group)) { continue; } //********************************************// //******Limit Clause For Detail Grouping******// //********************************************// $detailWhereGrouping = asol_ReportsGenerateQuery::getDetailWhereGrouping($sqlWhere, $currentGroup['group'], $detailFieldInfo); $subGroup = $detailWhereGrouping["subGroup"]; $sqlDetailWhere = $detailWhereGrouping["sqlDetailWhere"]; $sqlLimit = asol_ReportsGenerateQuery::getSqlDetailLimitQuery($report_data['results_limit'], $fullSizes[$index]); $sqlDetailQuery = $sqlSelect . $sqlFrom . $sqlJoin . $sqlDetailWhere . $sqlGroup . $sqlOrder . $sqlLimit; $rsDetail = asol_Report::getSelectionResults($sqlDetailQuery, null, $useExternalDbConnection, $alternativeDb); //***************************// //******Format SubGroup******// //***************************// if ($detailFieldInfo['function'] == '0') { $subGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $subGroup, $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates); } if (empty($subGroup) && $subGroup !== "0") { continue; } foreach ($rsDetail as $currentDetail) { if ($index >= $init_group && $index <= $end_group) { $currentSubGroups[$subGroup][] = $currentDetail; } $subGroupsExport[$subGroup][] = $currentDetail; } //***********************************************// //*******Subtotals Query for Current Group*******// //***********************************************// if ($displaySubtotals) { $limitedGroupTotals = array(); if ($report_data['results_limit'] == "all" && !$hasGroupedFunctionWithSQL) { $sqlSubQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlDetailWhere; $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb); } else { if (!$isGroupedReport) { $limitedIds = array(); $limitIds = asol_Report::getSelectionResults("SELECT " . $report_table . "." . $report_table_primary_key . " " . $sqlFrom . $sqlCountJoin . $sqlDetailWhere . $sqlOrder . $sqlLimit, null, $useExternalDbConnection, $alternativeDb); foreach ($limitIds as $limitId) { $limitedIds[] = $limitId[$report_table_primary_key]; } $sqlLimitWhere = " AND " . $report_table . "." . $report_table_primary_key . " IN ('" . implode("','", $limitedIds) . "')"; $sqlSubQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlDetailWhere . $sqlLimitWhere; $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb); } else { //**************************************// //******Generate SubTotals Manually*****// //**************************************// $limitedGroupTotals = $limitedGroupTotalsExport = asol_ReportsGenerateQuery::generateManuallySubTotals($rsDetail, $totals, $report_data['results_limit']); } } $rsSubTotalsExport = $rsSubTotals; if (!empty($limitedGroupTotalsExport[0])) { if ($index >= $init_group && $index <= $end_group) { $rsSubTotals[0] = $limitedGroupTotals[0]; } $rsSubTotalsExport[0] = $limitedGroupTotalsExport[0]; } //Obtenemos el resultado de la query de los SubTotales para el subgrupo actual $subTotalsLimit[] = $rsSubTotalsExport[0]; $subTotalsExportNoFormat[$subGroup] = $rsSubTotalsExport[0]; //**********************************// //******Apply Displaying Format*****// //**********************************// $rsSubTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsSubTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType); $rsSubTotalsExport = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsSubTotalsExport, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType); $currentSubTotals[$subGroup] = $rsSubTotals[0]; $subTotalsExport[$subGroup] = $rsSubTotalsExport[0]; } } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentSubGroups' => $currentSubGroups, 'subGroups' => $subGroups, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration); $returnedSubGroups = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailResultsets", $extraParams); $subGroups = $subGroupsExport = $returnedSubGroups !== false ? $returnedSubGroups : $currentSubGroups; //***********************// //***AlineaSol Premium***// //***********************// //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('currentSubTotals' => $currentSubTotals, 'subTotals' => $subTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => false); $returnedSubTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams); $subTotals = $returnedSubTotals !== false ? $returnedSubTotals : $currentSubTotals; //***********************// //***AlineaSol Premium***// //***********************// if ($hasNoPagination) { $subTotalsExport = $subTotals; } } else { $formatInfo = array('reportId' => $reportId, 'dashletId' => $dashletId, 'userDateFormat' => $userDateFormat, 'userTZ' => $userTZ, 'currencyId' => $focus->currency_id, 'gmtDates' => $gmtDates); $sqlDetailGroupBy = !empty($sqlGroup) ? $sqlGroup . ', ' . $detailFieldInfo['field'] : ''; $sqlDetailQuery = $sqlSelect . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlJoin . $sqlWhere . $sqlDetailGroupBy . $sqlOrder; $rsDetail = asol_Report::getSelectionResults($sqlDetailQuery, null, $useExternalDbConnection, $alternativeDb, $detailFieldInfo, $formatInfo, false); if ($hasNoPagination) { if ($report_data['results_limit'] !== "all") { foreach ($rsDetail as $subGroup => $currentDetail) { $res_limit = explode('${dp}', $report_data['results_limit']); if ($res_limit[1] == 'first') { $currentDetail = array_slice($currentDetail, 0, $res_limit[2]); } else { if ($res_limit[1] == 'last') { $currentDetail = array_slice($currentDetail, -$res_limit[2]); } } $currentSubGroups[$subGroup] = $currentDetail; } } else { $currentSubGroups = $rsDetail; } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentSubGroups' => $currentSubGroups, 'subGroups' => $subGroups, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration); $returnedSubGroups = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailResultsets", $extraParams); $subGroups = $subGroupsExport = $returnedSubGroups !== false ? $returnedSubGroups : $currentSubGroups; //***********************// //***AlineaSol Premium***// //***********************// } else { $index = 0; foreach ($rsDetail as $subGroup => $currentDetail) { if ($report_data['results_limit'] !== "all") { $res_limit = explode('${dp}', $report_data['results_limit']); if ($res_limit[1] == 'first') { $currentDetail = array_slice($currentDetail, 0, $res_limit[2]); } else { if ($res_limit[1] == 'last') { $currentDetail = array_slice($currentDetail, -$res_limit[2]); } } } if ($index >= $init_group && $index <= $end_group) { $currentSubGroups[$subGroup] = $currentDetail; } if ($allowExportGeneratedFile || $report_data['report_charts'] != 'Tabl') { $subGroupsExport[$subGroup] = $currentDetail; } $index++; } $subGroups = $currentSubGroups; } if ($displaySubtotals) { $limitedGroupTotals = array(); if ($report_data['results_limit'] == "all" && !$hasGroupedFunctionWithSQL) { $sqlDetailGroupBy = ' GROUP BY ' . $detailFieldInfo['field']; $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy; $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false); } else { if (!$isGroupedReport) { $sqlDetailGroupBy = ' GROUP BY ' . $report_table . "." . $report_table_primary_key; $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy; $sqlSubQueryTotals .= $report_data['results_limit'] == "all" ? '' : $sqlOrder; $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false); //**************************************// //******Generate SubTotals Manually*****// //**************************************// $rsSubTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsSubTotals, $totals, $report_data['results_limit'], true); } else { $sqlDetailGroupBy = !empty($sqlGroup) ? $sqlGroup . ', ' . $detailFieldInfo['field'] : ''; $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy; $sqlSubQueryTotals .= $report_data['results_limit'] == "all" ? '' : $sqlOrder; $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false); //**************************************// //******Generate SubTotals Manually*****// //**************************************// $rsSubTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsSubTotals, $totals, $report_data['results_limit'], true); } } foreach ($rsSubTotals as $rsSubTotal) { //**********************************// //******Apply Displaying Format*****// //**********************************// $theGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $rsSubTotal['asol_grouping_field'], $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates); $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup; $currentSubTotals[$theGroup] = $rsSubTotal; } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('currentSubTotals' => $currentSubTotals, 'subTotals' => $subTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => false); $returnedSubTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams); $subTotals = $returnedSubTotals !== false ? $returnedSubTotals : $currentSubTotals; //***********************// //***AlineaSol Premium***// //***********************// if ($lastModuleIteration) { foreach ($subTotals as &$subTotal) { //**********************************// //******Apply Displaying Format*****// //**********************************// unset($subTotal['asol_grouping_field']); $subTotal = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, array($subTotal), $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType); $subTotal = $subTotal[0]; } } $subTotalsExport = $subTotals; } } //Order resultset for grouped totals if ($reorderDetailGroups) { if ($details[0]['order'] == 'DESC') { krsort($subGroups); krsort($subGroupsExport); } else { if ($details[0]['order'] == 'ASC') { ksort($subGroups); ksort($subGroupsExport); } } } } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('subGroups' => $subGroups, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias); $returnedPhpSubGroups = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpDetailResultSet", $extraParams); $subGroups = $returnedPhpSubGroups !== false ? $returnedPhpSubGroups : $subGroups; //***********************// //***AlineaSol Premium***// //***********************// if ($report_data['results_limit'] != "all" || $allowExportGeneratedFile) { //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('subGroups' => $subGroupsExport, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias); $returnedPhpSubGroups = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpDetailResultSet", $extraParams); $subGroupsExport = $returnedPhpSubGroups !== false ? $returnedPhpSubGroups : $subGroupsExport; //***********************// //***AlineaSol Premium***// //***********************// } //**********************************************// //******Generate Values for Chart Totals********// //**********************************************// if ($report_charts != "Tabl" && count($chartInfo) > 0 && strlen($sqlTotalsC) > 7) { if ($report_data['results_limit'] != 'all') { $currentSubTotalsC = $subTotalsExportNoFormat; } else { switch ($detailFieldInfo['grouping']) { case "Detail": $rsSubTotalsC = asol_Report::getSelectionResults($sqlTotalsC . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlChartGroup, null, $useExternalDbConnection, $alternativeDb); foreach ($rsSubTotalsC as $rsSubTotalC) { $theGroup = $rsSubTotalC['asol_grouping_field']; unset($rsSubTotalC['asol_grouping_field']); $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup; $theGroup = asol_ReportsGenerateQuery::formatSubGroup($reportId, $dashletId, $theGroup, $detailFieldInfo, $userTZ, $currency_id, $gmtDates); if (!$massiveData) { $currentSubTotalsC[$theGroup] = $rsSubTotalC; } else { $currentSubTotalsC[$theGroup][] = $rsSubTotalC; } } break; case "Minute Detail": case "Quarter Hour Detail": case "Hour Detail": case "Day Detail": case "DoW Detail": case "WoY Detail": case "Month Detail": case "Natural Quarter Detail": case "Fiscal Quarter Detail": case "Natural Year Detail": case "Fiscal Year Detail": foreach ($rsGroups as $currentGroup) { $monthDayDetailGroupWhereExtensionQuery = asol_ReportsGenerationFunctions::getDateDetailGroupWhereExtensionQuery($sqlWhere, $detailFieldInfo['field'], $detailFieldInfo['grouping'], $currentGroup['group']); $subGroupC = $monthDayDetailGroupWhereExtensionQuery['subGroup']; $sqlDetailWhereC = $monthDayDetailGroupWhereExtensionQuery['sqlDetailWhere']; //***************************// //******Format SubGroup******// //***************************// if ($detailFieldInfo['function'] == '0') { $subGroupC = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $subGroupC, $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates); } //Obtenemos el resultado de la query de los SubTotales para el subgrupo actual $sqlSubQueryTotalsC = $sqlTotalsC . $sqlFrom . $sqlCountJoin . $sqlDetailWhereC; $rsSubTotalsC = asol_Report::getSelectionResults($sqlSubQueryTotalsC, null, $useExternalDbConnection, $alternativeDb); $currentSubTotalsC[$subGroupC] = $massiveData ? $rsSubTotalsC : $rsSubTotalsC[0]; } break; } } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('currentSubTotals' => $currentSubTotalsC, 'subTotals' => $subTotalsC, 'resulsetTotals' => $chartInfo, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => true); $returnedSubTotalsC = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams); $subTotalsC = $returnedSubTotalsC !== false ? $returnedSubTotalsC : $currentSubTotalsC; //***********************// //***AlineaSol Premium***// //***********************// if ($lastModuleIteration) { //********************************// //***Data For Charts Generation***// //********************************// $dataForChartsGeneration = asol_ReportsCharts::getDataForChartsGeneration($chartInfo, $chartConfig, $selectedFields, $subTotalsC, $subGroupsExport, $massiveData, true, $isGroupedReport, $hasFunctionField, $groups, $groupExport, $userDateFormat); $subGroupsChart = $dataForChartsGeneration['subGroupsChart']; $chartValues = $dataForChartsGeneration['chartValues']; $chartConfigs = $dataForChartsGeneration['chartConfigs']; $chartYAxisLabels = $dataForChartsGeneration['chartYAxisLabels']; //********************************// //***Data For Charts Generation***// //********************************// //**************************************// //***Generate Chart Files & ExtraData***// //**************************************// $chartFilesWithExtraData = asol_ReportsCharts::getChartFilesWithExtraData($focus->report_charts_engine, true, $massiveData, $chartInfo, $chartConfigs, $chartYAxisLabels, $chartValues, $subGroupsChart, $reportId, $report_module, $chartsHttpQueryUrls, $isGroupedReport, $isStoredReport); $urlChart = $chartFilesWithExtraData['urlChart']; $chartSubGroupsValues = $chartFilesWithExtraData['chartSubGroupsValues']; //**************************************// //***Generate Chart Files & ExtraData***// //**************************************// } } //**********************************// //******Apply Displaying Format*****// //**********************************// if ($lastModuleIteration) { $subGroups = asol_ReportsGenerateQuery::formatDetailResultSet($reportId, $dashletId, $subGroups, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias); $subGroups = asol_ReportsGenerateQuery::formatDetailGroupedFields($subGroups, $resulset_fields, $userDateFormat); } //Order resultsetExport for grouped totals $subGroupsExport = empty($subGroupsExport) ? array() : $subGroupsExport; if (($report_data['results_limit'] != "all" || $allowExportGeneratedFile) && $lastModuleIteration) { $subGroupsExport = asol_ReportsGenerateQuery::formatDetailResultSet($reportId, $dashletId, $subGroupsExport, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias); $subGroupsExport = asol_ReportsGenerateQuery::formatDetailGroupedFields($subGroupsExport, $resulset_fields, $userDateFormat); } //Obtenemos los valores relaciones con el paginado if ($report_data['results_limit'] != "all") { $total_entries_basic = 0; foreach ($subGroupsExport as $subExp) { $total_entries_basic += count($subExp); } $data['total_entries'] = $total_entries_basic; } else { $data['total_entries'] = $totalEntries; } $data['first_entry'] = $first_entry; $data['current_entries'] = !empty($current_entries_limit) ? $current_entries_limit : $current_entries; $data['page_number'] = $page_number; //Calcular numero de paginas en funciones de array sizes $parcial = 0; $num_pages = 0; foreach ($sizes as $currentSize) { $parcial += $currentSize; if ($parcial >= $entriesPerPage) { $num_pages++; $parcial = 0; } } $data['num_pages'] = $parcial == 0 ? $num_pages - 1 : $num_pages; //*************************// //******SIMPLE REPORT******// //*************************// } else { asol_ReportsUtils::reports_log('debug', 'Simple Report', __FILE__, __METHOD__, __LINE__); $sqlLimit = !empty($sqlLimitSubSet) ? $sqlLimitSubSet : $sqlLimit; //Obtenemos el resultado de la Query generada $sqlQuery = $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlOrder . $sqlLimit; $currentRs = asol_Report::getSelectionResults($sqlQuery, null, $useExternalDbConnection, $alternativeDb); //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentRs' => $currentRs, 'rs' => $rs, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration); $returnedRs = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeSingleResultsets", $extraParams); $rs = $returnedRs !== false ? $returnedRs : $currentRs; $extraParams = array('rs' => $rs, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias); $returnedPhpRs = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpResultSet", $extraParams); $rs = $returnedPhpRs !== false ? $returnedPhpRs : $rs; //***********************// //***AlineaSol Premium***// //***********************// if ($multiModuleReport && $lastModuleIteration) { asol_ReportsGenerationFunctions::sortAssocArray($rs, $sort_field, $initialSortDirection === 'ASC', in_array($sort_type, array('int', 'bigint', 'decimal', 'double', 'currency'))); } if ($allowExportGeneratedFile || $report_data['report_charts'] != 'Tabl') { if ($hasNoPagination) { $rsExport = $rs; } else { $sqlQueryExport = $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlOrder . $sqlLimitExport; $rsExport = asol_Report::getSelectionResults($sqlQueryExport, null, $useExternalDbConnection, $alternativeDb); //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('rs' => $rsExport, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias); $returnedPhpRs = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpResultSet", $extraParams); $rsExport = $returnedPhpRs !== false ? $returnedPhpRs : $rsExport; //***********************// //***AlineaSol Premium***// //***********************// if ($multiModuleReport && $lastModuleIteration) { asol_ReportsGenerationFunctions::sortAssocArray($rsExport, $sort_field, $initialSortDirection === 'ASC', in_array($sort_type, array('int', 'bigint', 'decimal', 'double', 'currency'))); } } } //********************************************// //********** SINGLE REPORTS CHARTS ***********// //********************************************// if ($isGroupedReport) { //********************************// //***Data For Charts Generation***// //********************************// $dataForChartsGeneration = asol_ReportsCharts::getDataForChartsGeneration($chartInfo, $chartConfig, $selectedFields, $rsExport, null, null, false, true, $hasFunctionField, $groups, null, $userDateFormat); $subGroupsChart = $dataForChartsGeneration['subGroupsChart']; $chartValues = $dataForChartsGeneration['chartValues']; $chartConfigs = $dataForChartsGeneration['chartConfigs']; $chartYAxisLabels = $dataForChartsGeneration['chartYAxisLabels']; //********************************// //***Data For Charts Generation***// //********************************// //**************************************// //***Generate Chart Files & ExtraData***// //**************************************// $chartFilesWithExtraData = asol_ReportsCharts::getChartFilesWithExtraData($focus->report_charts_engine, false, false, $chartInfo, $chartConfigs, $chartYAxisLabels, $chartValues, $subGroupsChart, $reportId, $report_module, $chartsHttpQueryUrls, false, $isStoredReport); $urlChart = $chartFilesWithExtraData['urlChart']; $chartSubGroupsValues = $chartFilesWithExtraData['chartSubGroupsValues']; //**************************************// //***Generate Chart Files & ExtraData***// //**************************************// } //********************************************// //********** SINGLE REPORTS CHARTS ***********// //********************************************// // Totals beginning if ($displayTotals) { if ($isGroupedReport && ($report_data['results_limit'] != 'all' || $multiModuleReport) || $hasGroupedFunctionWithSQL) { //**************************************// //******Generate SubTotals Manually*****// //**************************************// $limitedTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsExport, $totals, $report_data['results_limit'], false, $subTotalsLimit); } } // Totals end //***********************************// //********ResultSet Formatting*******// //***********************************// if ($lastModuleIteration) { $rs = asol_ReportsGenerateQuery::formatResultSet($reportId, $dashletId, $rs, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias); $rs = asol_ReportsGenerateQuery::formatGroupedFields($rs, $resulset_fields, $userDateFormat); } //***********************************// //********ResultSet Formatting*******// //***********************************// //***********************************// //***Exported ResultSet Formatting***// //***********************************// if ($lastModuleIteration && $allowExportGeneratedFile) { $rsExport = asol_ReportsGenerateQuery::formatResultSet($reportId, $dashletId, $rsExport, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias); $rsExport = asol_ReportsGenerateQuery::formatGroupedFields($rsExport, $resulset_fields, $userDateFormat); } //***********************************// //***Exported ResultSet Formatting***// //***********************************// $data['total_entries'] = $total_entries_basic; $data['entriesPerPage'] = $entriesPerPage; $data['current_entries'] = count($rs); $data['page_number'] = $page_number; $data['num_pages'] = $data['total_entries'] % $entriesPerPage != 0 ? floor($data['total_entries'] / $entriesPerPage) : floor($data['total_entries'] / $entriesPerPage) - 1; } $hasDisplayedCharts = count($urlChart) > 0 && $report_data['report_charts'] != 'Tabl'; $data['page_number_label'] = $data['page_number'] + 1; $data['num_pages_label'] = $data['num_pages'] + 1; // Totals beginning if ($displayTotals) { $sqlQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlWhere; $currentRsTotals = asol_Report::getSelectionResults($sqlQueryTotals, null, $useExternalDbConnection, $alternativeDb); //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('currentRsTotals' => $currentRsTotals, 'rsTotals' => $rsTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration); $returnedRsTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeTotalsResultsets", $extraParams); $rsTotals = $returnedRsTotals !== false ? $returnedRsTotals : $currentRsTotals; //**********************************// //******Apply Displaying Format*****// //**********************************// if ($lastModuleIteration) { $rsTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType); if ($report_data['results_limit'] != "all" || $allowExportGeneratedFile) { $limitedTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $limitedTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType); } $rsTotals = !empty($limitedTotals) ? $limitedTotals : $rsTotals; } } // Totals end } } } if (!$oversizedReport) { $columnsDataTypes = array(); $columnsDataVisible = array(); foreach ($resulset_fields as $currentField) { $currentType = !empty($currentField['format']['type']) ? $currentField['format']['type'] : $currentField['type']; $currentVisible = $currentField['visible']; $parenthesesPosition = strpos($currentType, '('); if ($parenthesesPosition != false) { $currentType = substr($currentType, 0, $parenthesesPosition); } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('dataType' => $currentType, 'dataFormat' => $currentField['format']); $buttonTypeResult = asol_ReportsUtils::managePremiumFeature("reportButtonFormat", "reportFunctions.php", "getButtonTypeClass", $extraParams); $buttonTypeClass = $buttonTypeResult['class']; $delimiterToken = empty($buttonTypeResult['delimiter']) ? $delimiterToken : $buttonTypeResult['delimiter']; //***********************// //***AlineaSol Premium***// //***********************// $columnsDataTypes[$currentField['alias']] = $buttonTypeClass !== false ? $buttonTypeClass : $currentType; $columnsDataVisible[$currentField['alias']] = $currentVisible; } //**************************************// //****Save Report Data into Txt File****// //**************************************// if ($allowExportGeneratedFile) { $exportedReport = array(); $exportedReport['id'] = $reportId; $exportedReport['reportName'] = $report_name; $exportedReport['report_type'] = $report_data['report_type']; $exportedReport['report_type_stored_data'] = $report_data['report_type_stored_data']; $exportedReport['module'] = $app_list_strings["moduleList"][$report_module]; $exportedReport['description'] = $report_data['description']; $exportedReport['report_charts'] = $report_data['report_charts']; $exportedReport['report_charts_engine'] = $report_data['report_charts_engine']; $exportedReport['report_attachment_format'] = $report_data['report_attachment_format']; $exportedReport['row_index_display'] = $report_data['row_index_display']; $exportedReport['results_limit'] = $report_data['results_limit']; $exportedReport['email_list'] = $focus->email_list; $exportedReport['created_by'] = $focus->created_by; if (asol_ReportsUtils::isDomainsInstalled()) { $exportedReport['asol_domain_id'] = $focus->asol_domain_id; $exportedReport['asol_domain_external'] = BeanFactory::getBean('asol_Domains', $focus->asol_domain_id)->external_id; } $exportedReport['pdf_orientation'] = $pdf_orientation; $exportedReport['pdf_img_scaling_factor'] = $pdf_img_scaling_factor; $exportedReport['totals'] = $rsTotals; $exportedReport['headers'] = $columns; $exportedReport['types'] = $types; $exportedReport['headersTotals'] = $totals; $exportedReport['current_user_id'] = $current_user->id; $exportedReport['context_domain_id'] = $reportDomain; $exportedReport['isDetailedReport'] = $isDetailedReport; $exportedReport['hasDisplayedCharts'] = $hasDisplayedCharts; $exportedReport['reportScheduledType'] = $focus->report_scheduled_type; if ($isDetailedReport) { $exportedReport['resultset'] = $subGroupsExport; $exportedReport['subTotals'] = $subTotalsExport; } else { $exportedReport['resultset'] = $rsExport; } $exportedReport['columnsDataTypes'] = $columnsDataTypes; $exportedReport['columnsDataVisible'] = $columnsDataVisible; $exportedReport['currentReportCss'] = $currentReportCss; //Guardamos el fichero en disco por si surge un export $exportedReportName = preg_replace('/[^a-zA-Z0-9]/', '', $report_data['report_name']); $reportNameNoSpaces = strtolower(str_replace(":", "", str_replace(" ", "_", $exportedReportName))); $exportedReportFile = $reportNameNoSpaces . "_" . dechex(time()) . dechex(rand(0, 999999)) . ".txt"; $exportFolder = "modules/asol_Reports/tmpReportFiles/"; $storedReportsSubFolder = "storedReports/"; //If Scheduled-Stored Report, save report in StoredReports subfolder & update Report with reportFileName if ($report_data['report_type'] == 'stored') { $storedReportData = empty($exportedReport['report_type_stored_data']) ? array() : unserialize(base64_decode($exportedReport['report_type_stored_data'])); $chartFiles = array(); foreach ($chartInfo as $key => $info) { if (!empty($urlChart[$key])) { $chartFiles[] = array('file' => $urlChart[$key], 'type' => $info["type"], 'subGroups' => $info["subgroups"]); } } $accessKey = asol_ReportsUtils::isDomainsInstalled() ? $reportDomain : 'base'; $storedReportData[$accessKey] = array('infoTxt' => $storedReportsSubFolder . $exportedReportFile, 'chartFiles' => $chartFiles); $updatedSerializedStoredData = base64_encode(serialize($storedReportData)); $setStoredReportFile = "UPDATE asol_reports SET report_type = 'stored:" . $updatedSerializedStoredData . "' WHERE id = '" . $reportId . "' LIMIT 1"; $db->query($setStoredReportFile); $exportFolder .= $storedReportsSubFolder; } $exportFile = fopen($exportFolder . $exportedReportFile, "w"); fwrite($exportFile, serialize($exportedReport)); fclose($exportFile); } //********************************************// //****Do Final Action for Executed Reports****// //********************************************// if (!isset($_REQUEST['return_action']) && !$hasVardefFilter) { asol_ReportsGenerationFunctions::doFinalExecuteReportActions($reportId, $dispatcherMaxRequests); } } if (!$externalCall && empty($vardefFilters)) { echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"> <script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script> <script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>'; } $externalCssUsage = isset($_REQUEST['useExternalCss']) && $_REQUEST['useExternalCss'] == 'true'; if ($focus->report_type === 'external' && $externalCssUsage) { echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/external.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">'; } if (!$externalCall && $getLibraries) { if ($report_data['report_charts'] != "Tabl") { echo asol_ReportsCharts::getChartEngineLibraries($focus->report_charts_engine, $isDashlet); } if (empty($vardefFilters)) { echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"> <script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script> ' . asol_ReportsManagementFunctions::getLoadJqueryScript(true, true) . ' <script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>'; } //***********************// //***AlineaSol Premium***// //***********************// $extendedFunctionsScript = asol_ReportsUtils::managePremiumFeature("ExtendedJavascriptFunctions", "reportFunctions.php", "getExtendedJavaScriptFunctions", null); if ($extendedFunctionsScript !== false && empty($vardefFilters)) { echo $extendedFunctionsScript; } //***********************// //***AlineaSol Premium***// //***********************// } //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('overrideParam' => !isset($vardefFilters) ? null : $vardefFilters); $vardefFilters = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getVardefFilterRequest", $extraParams); //***********************// //***AlineaSol Premium***// //***********************// ?> <script type="text/javascript"><?php echo asol_ReportsGenerationFunctions::getReloadCurrentDashletScriptFunction($reportId, $isDashlet, $dashletId, $getLibraries, $vardefFilters, $override_entries, $current_user->id, true); ?> </script><?php if (!empty($chartInfo)) { require_once "modules/asol_Reports/include_basic/manageReportsFunctions.php"; switch ($focus->report_charts_engine) { case "flash": $flashArray = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, false, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet); $chartScript .= $flashArray["chartHtml"]; break; case "html5": $html5Array = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, true, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet); $chartScript .= $html5Array["chartHtml"]; $html5Chart = $html5Array["returnedCharts"]; break; case "nvd3": $nvd3Array = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, true, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet); $chartScript .= $nvd3Array["chartHtml"]; $nvd3Chart = $nvd3Array["returnedCharts"]; break; default: break; } $returnedChartScript = "\r\n\t\t\t\t<script>\r\n\t\t\t\tfunction setUpCharts_" . $fixedReportId . "() {\r\n\t\t\t\t\t" . $chartScript . "\r\n\t\t\t\t}\r\n\t\t\t\t</script>\r\n\t\t\t\t"; $returnedChartScript .= asol_ReportsManagementFunctions::getLoadJqueryScript(true, false, 'setUpCharts_' . $fixedReportId); } //Asignamos los valores para el ordenado $report_data['sort_field'] = $sort_field; $report_data['sort_direction'] = $sort_direction; $report_data['sort_index'] = $sort_index; if (!empty($limitedTotals)) { $rsTotals = $limitedTotals; } if (empty($rsTotals)) { $rsTotals = array(); } $reportFields = $isDetailedReport ? $subGroups : $rs; if ($isHttpReportRequest) { if (isset($_REQUEST['schedulerCall']) && $_REQUEST['schedulerCall'] == 'true') { //Scheduled Reports if ($report_data['report_type'] == "scheduled") { $reportScheduledTypeArray = explode('${dollar}', $focus->report_scheduled_type); $reportScheduledType = empty($reportScheduledTypeArray[0]) ? 'email' : $reportScheduledTypeArray[0]; if ($reportScheduledType == 'email') { //Send Email //$exportedReportFile $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/"; $descriptionArray = unserialize(base64_decode($report_data['description'])); //************************// //****Get Email Arrays****// //************************// $emailReportInfo = asol_ReportsGenerationFunctions::getEmailInfo($focus->email_list); $emailFrom = $emailReportInfo['emailFrom']; $emailArrays = $emailReportInfo['emailArrays']; $users_to = $emailArrays["users_to"]; $users_cc = $emailArrays["users_cc"]; $users_bcc = $emailArrays["users_bcc"]; $roles_to = $emailArrays["roles_to"]; $roles_cc = $emailArrays["roles_cc"]; $roles_bcc = $emailArrays["roles_bcc"]; $emails_to = $emailArrays["emails_to"]; $emails_cc = $emailArrays["emails_cc"]; $emails_bcc = $emailArrays["emails_bcc"]; //Generar array con emails a enviar Report $mail = new SugarPHPMailer(); $mail->setMailerForSystem(); $user = new User(); //created by $mail_config = $user->getEmailInfo($report_data['created_by']); $mail->From = !empty($emailFrom) ? $emailFrom : (isset($sugar_config["asolReportsEmailsFrom"]) ? $sugar_config["asolReportsEmailsFrom"] : $mail_config['email']); $mail->FromName = isset($sugar_config["asolReportsEmailsFromName"]) ? $sugar_config["asolReportsEmailsFromName"] : $mail_config['name']; //Timeout del envio de correo $mail->Timeout = 30; $mail->CharSet = "UTF-8"; asol_ReportsGenerationFunctions::setSendEmailAddresses($mail, $emailArrays, $reportDomain); if ($report_data['scheduled_images'] == "1") { $chartFiles = array(); foreach ($chartInfo as $key => $info) { if (!empty($urlChart[$key])) { $chartFiles[] = array('file' => $urlChart[$key], 'type' => $info["type"], 'subGroups' => $info["subgroups"]); } } $accessKey = 'base'; $storedReportData[$accessKey] = array('infoTxt' => $exportedReportFile, 'chartFiles' => $chartFiles); $serializedStoredData = base64_encode(serialize($storedReportData)); $uri = !empty($host_name) ? $host_name : $sugar_config['site_url']; $uri .= "/index.php"; $uri .= "?entryPoint=scheduledEmailReport&module=asol_Reports&storedReportInfo=" . $serializedStoredData; asol_ReportsUtils::reports_log('asol', 'scheduledImages is enabled - URI Rebuild: ' . $uri, __FILE__, __METHOD__, __LINE__); //Generamos la url para reconstruir el report en un entryPoint } //Datos del email en si if (asol_ReportsUtils::isDomainsInstalled()) { $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain; $mail->Subject = "[" . BeanFactory::getBean('asol_Domains', $reportDomain)->name . "] " . $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_data['report_name']; } else { $mail->Subject = $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_data['report_name']; } $mail->Body = "<b>" . $mod_strings['LBL_REPORT_NAME'] . ": </b>" . $report_data['report_name'] . "<br>"; $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_MODULE'] . ": </b>" . $app_list_strings["moduleList"][$report_data['report_module']] . "<br>"; $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_DESCRIPTION'] . ": </b>" . $descriptionArray['public']; if ($report_data['scheduled_images'] == "1") { $mail->Body .= "<br><br>"; $mail->Body .= "<a href='" . $uri . "'>" . $mod_strings['LBL_REPORT_EMAIL_TTL_TEXT_1'] . "</a> " . $mod_strings['LBL_REPORT_EMAIL_TTL_TEXT_2'] . "<br><br>"; $mail->Body .= "<i>" . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_1'] . " " . $scheduled_files_ttl . " " . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_2'] . "</i>"; } //Mensaje en caso de que el destinatario no admita emails en formato html $mail->AltBody = $mod_strings['LBL_REPORT_NAME'] . ": " . $report_data['report_name'] . "\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_MODULE'] . ": " . $app_list_strings["moduleList"][$report_data['report_module']] . "\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_DESCRIPTION'] . ": " . $descriptionArray['public']; if ($scheduled_images == "1") { $mail->AltBody .= "\n\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_ALT_EMAIL_TTL_TEXT'] . ": " . $uri . "\n\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_1'] . " " . $scheduled_files_ttl . " " . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_2']; } if (!$isDetailedReport) { $rsExport = $rs; $subTotalsExport = ""; } else { $rsExport = $subGroups; $subTotalsExport = $subTotals; } if ($report_data['report_charts'] != 'Char') { //If only charts Report, do not attach a generated file $descriptionArray = unserialize(base64_decode($report_data["description"])); $description = $descriptionArray['public']; switch ($report_data['report_attachment_format']) { case "PDF": $adjunto = generateFile($focus->report_charts_engine, $report_data['report_name'], $app_list_strings["moduleList"][$report_data['report_module']], $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, array(), array(), false, true, 100, time(), $userTZlabel, $report_data['row_index_display'], $report_data['report_charts'], $columnsDataTypes, $columnsDataVisible, $currentReportCss, $reportDomain); break; case "HTML": $adjunto = generateFile($focus->report_charts_engine, $report_data['report_name'], $app_list_strings["moduleList"][$report_data['report_module']], $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, array(), array(), true, true, 100, time(), $userTZlabel, $report_data['row_index_display'], $report_data['report_charts'], $columnsDataTypes, $columnsDataVisible, $currentReportCss, $reportDomain); break; case "CSV": $adjunto = generateCsv($report_data['report_name'], $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display']); break; case "CSVC": $adjunto = generateCsv($report_data['report_name'], $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display'], true, true, false, true, true); break; case "XLS": $adjunto = generateXls($report_data['report_name'], $columns, null, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display']); break; case "XLSC": $adjunto = generateXls($report_data['report_name'], $columns, null, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display'], true, true, false, true, true); break; } //Añadimos el Report como fichero adjunto del e-mail $mail->AddAttachment(getcwd() . "/" . $tmpFilesDir . $adjunto, $adjunto); } $success = $mail->Send(); $tries = 1; while (!$success && $tries < 5) { sleep(5); $success = $mail->Send(); $tries++; } if ($report_data['report_charts'] != 'Char') { unlink(getcwd() . "/" . $tmpFilesDir . $adjunto); } } else { // Send Application //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('reportScheduledType' => $focus->report_scheduled_type, 'cvsData' => array('reportName' => $report_data['report_name'], 'resultset' => $rsExport, 'subtotals' => $subTotalsExport, 'isDetailed' => $isDetailedReport, 'rowIndexDisplay' => $report_data['row_index_display'])); asol_ReportsUtils::managePremiumFeature("externalApplicationReports", "reportFunctions.php", "sendReportToExternalApplication", $extraParams); //***********************// //***AlineaSol Premium***// //***********************// } } } else { $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/"; $httpHtmlFile = $_REQUEST['httpHtmlFile']; $noDataReport = empty($urlChart) && asol_ReportsGenerationFunctions::isEmptyResultSet($reportFields); $reportedError = asol_Report::$reported_error; if ($returnHtml) { return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; } else { include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; } } } else { $justDisplay = true; $noDataReport = empty($urlChart) && asol_ReportsGenerationFunctions::isEmptyResultSet($reportFields); $reportedError = asol_Report::$reported_error; if ($returnHtml) { return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; } else { include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; exit; } } } else { require_once 'modules/asol_Reports/include_basic/ReportChart.php'; require_once 'modules/asol_Reports/include_basic/generateQuery.php'; require_once 'modules/asol_Reports/include_basic/generateReportsFunctions.php'; require_once 'modules/asol_Reports/include_basic/manageReportsFunctions.php'; asol_ReportsUtils::reports_log('debug', 'HttpRequest REPORT!!', __FILE__, __METHOD__, __LINE__); $hasSearchCriteria = !isset($_REQUEST['search_criteria']) ? false : true; $pageNumber = empty($_REQUEST['page_number']) ? "" : "&page_number=" . $_REQUEST['page_number']; $sortingField = empty($_REQUEST['sort_field']) ? "" : "&sort_field=" . $_REQUEST['sort_field'] . "&sort_direction=" . $_REQUEST['sort_direction'] . "&sort_index=" . $_REQUEST['sort_index']; $externalFilters = !isset($_REQUEST['external_filters']) ? "" : "&external_filters=" . html_entity_decode($_REQUEST['external_filters']); //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('overrideParam' => !isset($vardefFilters) ? null : $vardefFilters); $vardefFilters = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getVardefFilterRequest", $extraParams); //***********************// //***AlineaSol Premium***// //***********************// $overrideEntries = empty($override_entries) ? "" : "&overrideEntries=" . $override_entries; $searchCriteria = !isset($_REQUEST['search_criteria']) ? "" : "&search_criteria=1"; $filtersHiddenInputs = empty($_REQUEST['filters_hidden_inputs']) ? "" : "&filters_hidden_inputs=" . $_REQUEST['filters_hidden_inputs']; $currentUserId = isset($_REQUEST['currentUserId']) ? "¤tUserId=" . $_REQUEST['currentUserId'] : "¤tUserId=" . $current_user->id; $contextDomain = isset($contextDomainId) ? "&contextDomainId=" . $contextDomainId : ""; $returnHtmlParam = isset($returnHtml) && $returnHtml ? "&returnHtml=true" : ""; $isDashletQuery = !empty($isDashlet) ? "&dashlet=true" : ""; $isDashletQuery .= !empty($dashletId) ? "&dashletId=" . $dashletId : ""; $focus = BeanFactory::getBean('asol_Reports', $reportId); //*************************************// //********Manage Report Domain*********// //*************************************// if (asol_ReportsUtils::isDomainsInstalled()) { $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain; if (!asol_ReportsGenerationFunctions::manageReportDomain($reportId, $reportDomain, $focus->asol_domain_id)) { $availableReport = false; include "modules/asol_Reports/include_basic/DetailViewHttpSave.php"; exit; } } //Ver si hay charts para pasar los nombres $rsHttp = asol_Report::getSelectionResults("SELECT * FROM asol_reports WHERE id = '" . $reportId . "' LIMIT 1", null, false); $chartsUrls = array(); $chartsInfo = array(); $filtersArray = unserialize(base64_decode($rsHttp[0]['report_filters'])); //Check if there is some user_input fiter to show $hasUserInputsFilters = false; foreach ($filtersArray['data'] as $currentFilter) { if ($currentFilter['behavior'] == 'user_input') { $hasUserInputsFilters = true; break; } } //Check if there is some user_inut fiter to show // Execute report with default filter values if (isset($filtersArray['config']['initialExecution']) && $filtersArray['config']['initialExecution']) { $hasSearchCriteria = true; $searchCriteria = "&search_criteria=1"; } // Execute report with default filter values //Guardamos el fichero en disco por si surge un export $exportedReportName = preg_replace('/[^a-zA-Z0-9]/', '', $rsHttp[0]['name']); $reportNameNoSpaces = strtolower(str_replace(":", "", str_replace(" ", "_", $exportedReportName))); $httpHtmlFile = $reportNameNoSpaces . "_" . dechex(time()) . dechex(rand(0, 999999)) . ".html"; $selectedCharts = unserialize(base64_decode($rsHttp[0]['report_charts_detail'])); $chartsUrls = asol_ReportsGenerationFunctions::generateChartFileNames($focus->report_charts_engine, $selectedCharts); $chartsQueryUrls = empty($chartsUrls) ? "" : "&chartsHttpQueryUrls=" . implode('${pipe}', $chartsUrls); if (empty($vardefFilters)) { echo '<script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script> ' . asol_ReportsManagementFunctions::getLoadJqueryScript(true); } if ($getLibraries) { if ($report_data['report_charts'] != "Tabl") { echo asol_ReportsCharts::getChartEngineLibraries($focus->report_charts_engine, $isDashlet); } echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">'; echo ' <script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script> ' . asol_ReportsManagementFunctions::getLoadJqueryScript(true) . ' <script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>'; //***********************// //***AlineaSol Premium***// //***********************// $extendedFunctionsScript = asol_ReportsUtils::managePremiumFeature("ExtendedJavascriptFunctions", "reportFunctions.php", "getExtendedJavaScriptFunctions", null); if ($extendedFunctionsScript !== false) { echo $extendedFunctionsScript; } //***********************// //***AlineaSol Premium***// //***********************// } //***********************// //***AlineaSol Premium***// //***********************// if ($currentReportCss !== false) { echo $currentReportCss; } //***********************// //***AlineaSol Premium***// //***********************// $setUpInputCalendarsScript = asol_ReportsGenerationFunctions::getSetUpInputCalendarsScriptFunction($reportId, $filtersArray['data']); if (isset($setUpInputCalendarsScript)) { echo '<script>' . $setUpInputCalendarsScript . '</script>'; } $waitForReport = false; $reportRequestId = ""; $asolUrlQuery = $pageNumber . $sortingField . $overrideEntries . $externalFilters . $vardefFilters . $searchCriteria . $filtersHiddenInputs . $currentUserId . $contextDomain . $returnHtmlParam . $isDashletQuery; $baseRequestedUrl = isset($sugar_config["asolReportsCurlRequestUrl"]) ? $sugar_config["asolReportsCurlRequestUrl"] : $sugar_config["site_url"]; $curlRequestedUrl = $baseRequestedUrl . '/index.php?entryPoint=viewReport&record=' . $reportId . '&language=' . $current_language . '&sourceCall=httpReportRequest' . $chartsQueryUrls . $asolUrlQuery . '&httpHtmlFile=' . $httpHtmlFile . $reportRequestId; //REPORTS DISPATCHER $hasVardefFilter = !empty($vardefFilters); $manageDispatcher = $dispatcherMaxRequests > 0 && (!$hasUserInputsFilters || $hasUserInputsFilters && isset($_REQUEST['external_filters'])) && !$hasVardefFilter; if ($manageDispatcher) { $requestId = create_guid(); $currentGMTTime = time(); $currentGMTDate = date('Y-m-d H:i:s', $currentGMTTime); asol_ReportsUtils::reports_log('debug', 'Init GMDate(): ' . $currentGMTDate, __FILE__, __METHOD__, __LINE__); $reportRequestId = "&reportRequestId=" . $requestId; $initRequestTimeStamp = "&initRequestDateTimeStamp=" . $currentGMTTime; $curlRequestedUrl .= $reportRequestId . $initRequestTimeStamp; asol_ReportsUtils::reports_log('debug', 'Reporting Queue Feature Enabled.', __FILE__, __METHOD__, __LINE__); $reportsDispatcherSql = "SELECT COUNT(id) as 'reportsThreads' FROM asol_reports_dispatcher WHERE status = 'executing'"; $reportsDispatcherRs = $db->query($reportsDispatcherSql); $reportsDispatcherRow = $db->fetchByAssoc($reportsDispatcherRs); $currentReportsRunningThreads = $reportsDispatcherRow["reportsThreads"]; $waitForReport = $currentReportsRunningThreads >= $dispatcherMaxRequests; $dispatcherReportSql = "INSERT INTO asol_reports_dispatcher VALUES ('" . $requestId . "', '" . $reportId . "', '" . $curlRequestedUrl . "', '" . ($waitForReport ? 'waiting' : 'executing') . "', '" . $currentGMTDate . "', '" . $currentGMTDate . "', 'manual', '" . $current_user->id . "')"; $db->query($dispatcherReportSql); } //REPORTS DISPATCHER if (!$waitForReport) { //Execute report if not is waiting in queue $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $curlRequestedUrl); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); curl_exec($ch); curl_close($ch); } $checkHttpFileTimeout = isset($sugar_config["asolReportsCheckHttpFileTimeout"]) ? $sugar_config["asolReportsCheckHttpFileTimeout"] : "1000"; echo ' <script>'; if (!isset($_REQUEST['entryPoint'])) { echo asol_ReportsGenerationFunctions::getSendAjaxRequestScriptFunction($reportId, $dashletId, $checkHttpFileTimeout, $httpHtmlFile, $reportRequestId, $initRequestTimeStamp, $hasCalendarInputs); echo asol_ReportsGenerationFunctions::getInitialAjaxRequest2GenerateReportScript($reportId); } echo asol_ReportsGenerationFunctions::getReloadCurrentDashletScriptFunction($reportId, $isDashlet, $dashletId, $getLibraries, $vardefFilters, $override_entries, $current_user->id, true); echo ' </script>'; if (!$isDashlet) { echo asol_ReportsGenerationFunctions::getStandByReportHtml('', false); } } } } }
public static function processDownloadRequest($report, $userTZ, $fileTime, $fileType, $somePngs, $someLegends) { global $mod_strings, $sugar_config; require_once "include/SugarPHPMailer.php"; require_once "modules/asol_Reports/include_basic/ReportFile.php"; require_once "modules/asol_Reports/include_basic/ReportExcel.php"; require_once "modules/asol_Reports/include_basic/generateReportsFunctions.php"; $fileContent = null; $exportFolder = "modules/asol_Reports/tmpReportFiles/"; $currentDir = getcwd() . "/"; $fileName = $exportFolder . $fileName; //Volcamos el contenido del report exportado en variables $report_name = $report["reportName"]; $report_module = $report["module"]; $descriptionArray = unserialize(base64_decode($report["description"])); $description = $descriptionArray['public']; $isDetailedReport = $report["isDetailedReport"]; $reportScheduledType = $report["reportScheduledType"]; $hasDisplayedCharts = $report["hasDisplayedCharts"]; $pdf_orientation = $report["pdf_orientation"]; $pdf_img_scaling_factor = $report["pdf_img_scaling_factor"]; //Only if AlineaSolDomains installed $reportDomainId = isset($report["asol_domain_id"]) ? $report["asol_domain_id"] : null; //Only if AlineaSolDomains installed $report_charts = $report["report_charts"]; $report_charts_engine = $report["report_charts_engine"]; $report_attachment_format = $report["report_attachment_format"]; $row_index_display = $report["row_index_display"]; $email_list = $report["email_list"]; $created_by = $report["created_by"]; $columns = $report["headers"]; $types = $report["types"]; $totals = $report["headersTotals"]; $rsTotals = $report["totals"]; $rs = $report["resultset"]; $subGroups = $report["resultset"]; $subTotals = $report["subTotals"]; $columnsDataTypes = $report['columnsDataTypes']; $columnsDataVisible = $report['columnsDataVisible']; $currentReportCss = $report['currentReportCss']; //Only if AlineaSolDomains installed $contextDomainId = $report["context_domain_id"]; //Only if AlineaSolDomains installed $rsExport = $isDetailedReport ? $subGroups : $rs; $subTotalsExport = $isDetailedReport ? $subTotals : ""; if ($fileType == 'email') { //Generar array con emails a enviar Report $mail = new SugarPHPMailer(); //************************// //****Get Email Arrays****// //************************// $emailReportInfo = asol_ReportsGenerationFunctions::getEmailInfo($email_list); $emailFrom = $emailReportInfo['emailFrom']; $emailArrays = $emailReportInfo['emailArrays']; $users_to = $emailArrays['users_to']; $users_cc = $emailArrays['users_cc']; $users_bcc = $emailArrays['users_bcc']; $roles_to = $emailArrays['roles_to']; $roles_cc = $emailArrays['roles_cc']; $roles_bcc = $emailArrays['roles_bcc']; $emails_to = $emailArrays['emails_to']; $emails_cc = $emailArrays['emails_cc']; $emails_bcc = $emailArrays['emails_bcc']; $mail->setMailerForSystem(); $user = new User(); //created by $mail_config = $user->getEmailInfo($created_by); if (!empty($emailFrom)) { $mail->From = $emailFrom; } else { $mail->From = isset($sugar_config["asolReportsEmailsFrom"]) ? $sugar_config["asolReportsEmailsFrom"] : $mail_config['email']; } $mail->FromName = isset($sugar_config["asolReportsEmailsFromName"]) ? $sugar_config["asolReportsEmailsFromName"] : $mail_config['name']; //Timeout del envio de correo $mail->Timeout = 30; $mail->CharSet = "UTF-8"; asol_ReportsGenerationFunctions::setSendEmailAddresses($mail, $emailArrays, $contextDomainId); //Datos del email en si if (asol_ReportsUtils::isDomainsInstalled()) { $mail->Subject = "[" . BeanFactory::getBean('asol_Domains', $contextDomainId)->name . "] " . $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_name; } else { $mail->Subject = $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_name; } $mail->Body = "<b>" . $mod_strings['LBL_REPORT_NAME'] . ": </b>" . $report_name . "<br>"; $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_MODULE'] . ": </b>" . $report_module . "<br>"; $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_DESCRIPTION'] . ": </b>" . $description; //Mensaje en caso de que el destinatario no admita emails en formato html $mail->AltBody = $mod_strings['LBL_REPORT_NAME'] . ": " . $report_name . "\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_MODULE'] . ": " . $report_module . "\n"; $mail->AltBody .= $mod_strings['LBL_REPORT_DESCRIPTION'] . ": " . $description; $pngSrcs = array(); $legends = array(); if (!$hasDisplayedCharts) { $rsExport = $rs; $subTotalsExport = ""; } else { $rsExport = $subGroups; $subTotalsExport = $subTotals; if ($report_attachment_format != "CSV") { if (in_array($report_charts, array("Char", "Both", "Htob"))) { //Generamos las imagenes $pngs = explode("%pngSeparator", $somePngs); foreach ($pngs as $key => $png) { $pngSrcs[$key] = $png; } $legends = explode("%legendSeparator", $someLegends); } } } switch ($report_attachment_format) { case "HTML": if ($report_charts == "Char") { $columns = array(); $rsExport = array(); $rsTotals = array(); } $adjunto = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngs, $legends, true, true, 100, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId); break; case "PDF": if ($report_charts == "Char") { $columns = array(); $rsExport = array(); $rsTotals = array(); } $adjunto = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, false, true, $pdf_img_scaling_factor, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId); break; case "CSV": $adjunto = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display); break; case "CSVC": $adjunto = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true); break; case "XLS": $adjunto = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display); break; case "XLSC": $adjunto = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true); break; } //Añadimos el Report como fichero adjunto del e-mail $mail->AddAttachment($currentDir . $exportFolder . $adjunto, $adjunto); //Exito sera true si el email se envio satisfactoriamente, false en caso comtrario $success = $mail->Send(); $tries = 1; while (!$success && $tries < 5) { sleep(5); $success = $mail->Send(); $tries++; } unlink($currentDir . $exportFolder . $adjunto); } else { if ($fileType == 'app') { //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('reportScheduledType' => $reportScheduledType, 'cvsData' => array('reportName' => $report_data['report_name'], 'resultset' => $rsExport, 'subtotals' => $subTotalsExport, 'isDetailed' => $isDetailedReport, 'rowIndexDisplay' => $report_data['row_index_display'])); asol_ReportsUtils::managePremiumFeature("externalApplicationReports", "reportFunctions.php", "sendReportToExternalApplication", $extraParams); //***********************// //***AlineaSol Premium***// //***********************// } else { if ($fileType == 'csv') { $filePath = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display); } else { if ($fileType == 'csvc') { $filePath = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true); } else { if ($fileType == 'xls') { $filePath = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display); } else { if ($fileType == 'xlsc') { $filePath = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true); } else { if ($fileType == 'html') { $pngSrcs = $hasDisplayedCharts && in_array($report_charts, array("Char", "Both", "Htob")) ? explode("%pngSeparator", $_REQUEST['pngs']) : array(); $legends = $hasDisplayedCharts && in_array($report_charts, array("Char", "Both", "Htob")) ? explode("%legendSeparator", $_REQUEST['legends']) : array(); $rsExport = $report_charts == "Char" ? array() : $rsExport; $rsTotals = $report_charts == "Char" ? array() : $rsTotals; $filePath = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, true, true, 100, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId); } else { if ($fileType == 'pdf') { $pngSrcs = array(); $legends = array(); if ($hasDisplayedCharts) { if (in_array($report_charts, array("Char", "Both", "Htob"))) { //Generamos las imagenes $pngs = explode("%pngSeparator", rawurldecode($somePngs)); foreach ($pngs as $key => $png) { $pngSrcs[$key] = $png; } $legends = explode("%legendSeparator", $someLegends); } } $columns = $report_charts == "Char" ? array() : $columns; $rsExport = $report_charts == "Char" ? array() : $rsExport; $rsTotals = $report_charts == "Char" ? array() : $rsTotals; $filePath = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, false, true, $pdf_img_scaling_factor, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId); } } } } } } $fileContent = file_get_contents($currentDir . $exportFolder . $filePath); } } return array('fileName' => $filePath, 'fileContent' => $fileContent); }
$availableReport = false; $isDashlet = isset($_REQUEST['dashlet']) ? true : false; $dashletId = isset($_REQUEST['dashletId']) ? $_REQUEST['dashletId'] : ""; if (asol_ReportsUtils::isDomainsInstalled()) { $reportCssfile = is_file("modules/asol_Reports/include_basic/css/" . $current_user->asol_default_domain . ".css") ? $current_user->asol_default_domain . ".css" : 'reports.css'; } else { $reportCssfile = 'reports.css'; } //Is Domains Installed $storedReportInfo = $_REQUEST['storedReportInfo']; if ($storedReportInfo === 'false') { $availableReport = false; } else { $tmpReportFilesPath = 'modules/asol_Reports/tmpReportFiles/'; $storedReportData = unserialize(base64_decode($storedReportInfo)); $accessKey = asol_ReportsUtils::isDomainsInstalled() && isset($current_user->asol_default_domain) ? $current_user->asol_default_domain : 'base'; $exportedReportFile = $storedReportData[$accessKey]['infoTxt']; $reportCharts = $storedReportData[$accessKey]['chartFiles']; if (empty($exportedReportFile) || !is_file($tmpReportFilesPath . $exportedReportFile)) { $availableReport = false; } else { $descriptor = @fopen($tmpReportFilesPath . $exportedReportFile, "r"); $serializedReport = fread($descriptor, filesize($tmpReportFilesPath . $exportedReportFile)); $report = unserialize($serializedReport); fclose($descriptor); $availableReport = true; $report_data['record'] = $report['id']; $report_name = $report['reportName']; $report_data['report_charts'] = $report['report_charts']; $report_charts_engine = $report_data['report_charts_engine'] = $report['report_charts_engine']; $report_data['report_attachment_format'] = $report['report_attachment_format'];
public static function getReportScopeSelect($reportScope, $isDisabled = false) { global $mod_strings, $db, $current_user; $explodedScope = explode('${dp}', $reportScope); $usedScope = empty($reportScope) ? 'private' : $explodedScope[0]; $values = array('private', 'public', 'role'); $labels = array('LBL_REPORT_PRIVATE', 'LBL_REPORT_PUBLIC', 'LBL_REPORT_ROLE'); $returnedHtml = '<select style="vertical-align: top;" name="report_scope" class="reportScope" onChange="$(this).closest(\'td\').find(\'.scopeRole\').css(\'visibility\', (this.value != \'public\' ? \'inherit\' : \'hidden\'));" ' . ($isDisabled ? 'disabled' : '') . '>'; foreach ($values as $key => $value) { $returnedHtml .= $usedScope == $value ? '<option value="' . $value . '" selected>' . $mod_strings[$labels[$key]] . '</option>' : '<option value="' . $value . '">' . $mod_strings[$labels[$key]] . '</option>'; } $returnedHtml .= '</select>'; $roles = array(); $return_action = isset($_REQUEST['return_action']) ? $_REQUEST['return_action'] : null; if (asol_ReportsUtils::isDomainsInstalled() && !empty($current_user->asol_default_domain)) { $queryRoles = $db->query("SELECT acl_roles.id, acl_roles.name FROM acl_roles LEFT JOIN asol_domains_aclroles ON acl_roles.id=asol_domains_aclroles.aclrole_id WHERE asol_domains_aclroles.asol_domain_id = '" . $current_user->asol_default_domain . "' ORDER BY name ASC"); } else { $queryRoles = $db->query("SELECT id, name FROM acl_roles ORDER BY name ASC"); } while ($queryRow = $db->fetchByAssoc($queryRoles)) { $roles[] = array('id' => $queryRow['id'], 'name' => $queryRow['name']); } $returnedHtml .= "<select class='scopeRole' style='visibility: " . ($usedScope === 'public' ? 'hidden' : 'inherit') . "; vertical-align: middle;' id='report_scope_role' name='report_scope_role[]' multiple size='3' " . ($isDisabled ? 'disabled' : '') . ">"; foreach ($roles as $role) { $selectedRole = strstr($explodedScope[1], $role["id"]); if ($return_action == "duplicate") { $returnedHtml .= '<option value="' . $role["id"] . '" ' . ($selectedRole && $current_user->is_admin ? 'selected' : '') . '>' . $role["name"] . '</option>'; } else { $returnedHtml .= '<option value="' . $role["id"] . '" ' . ($selectedRole ? 'selected' : '') . '>' . $role["name"] . '</option>'; } } $returnedHtml .= "</select>"; return $returnedHtml; }
public static function getSqlJoinQuery(&$fieldValues, &$filterValues, $resultsLimit, $reportModule, $reportTable, $auditedReport, $alternativeDb, &$fieldsByRef, $aliasSuffix = '', &$domainField = null) { global $current_user, $sugar_config; $bean = BeanFactory::newBean($reportModule); $joinVariables = array(); $processedJoinsFromSqlKeys = array(); $isNonCrmDatabase = $alternativeDb !== false ? true : false; $tableModulesAssociation = asol_ReportsUtils::getTableModulesAssociation($current_user->id); //****************************************// //***Get Indexes From Report Main Table***// //****************************************// $dbKey = $alternativeDb === false ? 'crm' : 'ext' . $alternativeDb; if (!isset($_SESSION['asolReportsTableIndexes'][$dbKey][$reportTable])) { foreach (asol_Report::getSelectionResults("SHOW INDEX FROM " . $reportTable, null, false, $alternativeDb) as $tableCurrentIndex) { $_SESSION['asolReportsTableIndexes'][$dbKey][$reportTable][$tableCurrentIndex['Column_name']] = true; } } //****************************************// //***Get Indexes From Report Main Table***// //****************************************// foreach ($fieldValues['tables'][0]['data'] as $index => &$currentValues) { //****************************************// //*****Variable Definition Iteration******// //****************************************// $fieldExploded = explode('.', $currentValues['field']); $keyExploded = explode(';', $currentValues['key']); $tableExploded = explode('::', $fieldExploded[0]); $mainKey = null; $mainFieldKey = null; //**************************************// //*****Control Variable Definition******// //**************************************// $fieldIsVisible = in_array(strtolower($currentValues['visible']), array("yes", "html")) ? true : false; $fieldOrderedWithLimit = self::fieldOrderedWithLimit($currentValues, $resultsLimit); $fieldHasFilter = self::fieldHasFilter($filterValues, $currentValues); $fieldSqlVarsInFilters = self::fieldSqlVarsInFilters($fieldValues, $filterValues, $currentValues); $fieldSqlRefsInFilters = self::fieldSqlRefsInFilters($fieldValues, $filterValues, $currentValues); $fieldHasDetailGrouped = $currentValues['grouping'] != "0" ? true : false; $fieldHasFunction = !in_array($currentValues['function'], array("0", "undefined")) ? true : false; $domainUsage = self::isDomainUsage($domainField, $currentValues); $auditRequiredJoin = self::isAuditRequiredJoin($auditedReport, $reportTable, $currentValues); $reportTableHasCustom = empty($currentValues['key']) && substr($fieldExploded[0], -strlen('_cstm')) === '_cstm'; $reportTableCustomJoin = $reportTableCustomJoin || $reportTableHasCustom; $reportTableAlreadyCustomJoined = false; $commonDoJoin = $fieldHasFilter || $fieldSqlRefsInFilters || $fieldHasDetailGrouped || $domainUsage || $auditRequiredJoin; $currentDoJoin = $commonDoJoin || ($fieldIsVisible || $fieldSqlVarsInFilters); $currentDoCountJoin = $commonDoJoin || ($fieldIsVisible && $fieldHasFunction || $fieldOrderedWithLimit); //*****************************// //*****Init Key Iteration******// //*****************************// $lastTableName = null; foreach ($keyExploded as $keyDepth => $currentLink) { if (!$currentValues['isRelated']) { break; } if ($isNonCrmDatabase) { $parentLinkExploded = explode(' ', $keyExploded[$keyDepth - 1]); $linkExploded = explode(' ', $currentLink); $mainLinkKey = $linkExploded[0]; $relatedLinkKey = $linkExploded[1]; $mainFieldKey = empty($mainFieldKey) ? $mainLinkKey : $mainFieldKey; $mainTable = $keyDepth >= 1 ? $tableExploded[$keyDepth - 1] : $reportTable; $mainKey = $mainLinkKey; $relatedTable = $tableExploded[$keyDepth]; $relatedKey = $relatedLinkKey; $parentKey = $keyDepth >= 1 ? $parentLinkExploded[0] : null; $joinTable = null; $isMainCustom = false; $isRelatedCustom = false; $storedKey = $mainKey . '.' . $relatedTable; } else { $parentLinkExploded = explode(' ', $keyExploded[$keyDepth - 1]); $linkExploded = explode(' ', $currentLink); $currentLinkKey = $linkExploded[0]; $tableUnderScoreExploded = explode("_", $tableExploded[$keyDepth]); $isCustomTable = end($tableUnderScoreExploded) == 'cstm' ? true : false; $tableName = $isCustomTable ? substr($tableExploded[$keyDepth], 0, -5) : $tableExploded[$keyDepth]; if ($currentLinkKey === 'id') { //Relationship $mainTableUnderScoreExploded = explode("_", $tableExploded[0]); $isMainCustomTable = end($mainTableUnderScoreExploded) == 'cstm' ? true : false; $mainTableName = $isMainCustomTable ? substr($tableExploded[0], 0, -5) : $tableExploded[0]; $mainKeyExploded = explode(' ', $keyExploded[0]); $mainFieldKey = $mainKeyExploded[0]; $relationshipName = $linkExploded[1]; $mainTableName = $keyDepth >= 1 ? $tableExploded[$keyDepth - 1] : $reportTable; $relatedTableName = substr($tableExploded[$keyDepth], -strlen('_cstm')) === '_cstm' ? substr($tableExploded[$keyDepth], 0, -strlen('_cstm')) : $tableExploded[$keyDepth]; $availableRelationShips = self::getAvailableRelationShips($mainTableName, $relatedTableName, $currentLinkKey); if (!empty($availableRelationShips)) { //**********************************// //******Both Sides Relationship*****// //**********************************// $currentRelationShip = self::getCurrentRelationShip($availableRelationShips, $relationshipName); $relationShipDirection = $currentRelationShip['asolRelationShipDirection']; $mainTable = $relationShipDirection == 'L2R' ? $currentRelationShip['lhs_table'] : $currentRelationShip['rhs_table']; $mainKey = $relationShipDirection == 'L2R' ? $currentRelationShip['lhs_key'] : $currentRelationShip['rhs_key']; $relatedTable = $relationShipDirection == 'L2R' ? $currentRelationShip['rhs_table'] : $currentRelationShip['lhs_table']; $relatedKey = $relationShipDirection == 'L2R' ? $currentRelationShip['rhs_key'] : $currentRelationShip['lhs_key']; $parentKey = $keyDepth >= 1 ? $parentLinkExploded[0] : null; $joinTable = array('table' => $currentRelationShip['join_table'], 'lhsKey' => $relationShipDirection == 'L2R' ? $currentRelationShip['join_key_lhs'] : $currentRelationShip['join_key_rhs'], 'rhsKey' => $relationShipDirection == 'L2R' ? $currentRelationShip['join_key_rhs'] : $currentRelationShip['join_key_lhs']); $isMainCustom = false; $isRelatedCustom = $isCustomTable; $storedKey = $mainKey . '.' . $currentRelationShip['relationship_name']; } else { //*************************************// //******Fields MetaData Searching******// //*************************************// $availableFieldsMetadata = self::getAvailableFieldsMetadata($reportModule); $currentRelationShip = self::getCurrentRelationShip($availableFieldsMetadata, $relationshipName); $mainTable = $keyDepth >= 1 ? $tableExploded[$keyDepth - 1] : $reportTable; $mainKey = $currentRelationShip['ext3']; $relatedTable = strtolower($currentRelationShip['ext2']); $relatedKey = 'id'; $parentKey = $keyDepth >= 1 ? $parentLinkExploded[0] : null; $joinTable = null; $isMainCustom = true; $isRelatedCustom = $isCustomTable; $storedKey = $mainKey . '.' . $relatedTable; } } else { //Relate Field //***********************// //***AlineaSol Premium***// //***********************// $extraParams = array('database' => '-1', 'restricted' => false); $definedAvailableRelates = asol_ReportsUtils::managePremiumFeature("reportRelatesManagement", "reportFunctions.php", "getReportDefinedAvailableRelates", $extraParams); $theModule = $keyDepth >= 1 ? $tableModulesAssociation[$lastTableName] : $reportModule; $isVirtualLink = $definedAvailableRelates !== false ? isset($definedAvailableRelates[$theModule][$currentLink]) ? true : false : false; //***********************// //***AlineaSol Premium***// //***********************// if ($isVirtualLink) { $relatedInfo = null; $relatedModule = $definedAvailableRelates[$theModule][$currentLink]['relationModule']; $relatedTable = $keyDepth >= 1 ? $tableName : strtolower($relatedModule); $relatedKey = $definedAvailableRelates[$theModule][$currentLink]['relationField']; } else { $relatedInfo = asol_Report::getReportsRelatedFields($bean, $currentLink); $relatedModule = $relatedInfo['module']; $relatedTable = $keyDepth >= 1 ? $tableName : strtolower($relatedModule); $relatedKey = 'id'; } $mainKeyExploded = explode(' ', $keyExploded[0]); $mainFieldKey = $mainKeyExploded[0]; $mainTable = $keyDepth >= 1 ? $tableExploded[$keyDepth - 1] : ($auditedReport ? $reportTable . '_audit' : $reportTable); $mainKey = $currentLink; $parentKey = $keyDepth >= 1 ? $parentLinkExploded[0] : null; $joinTable = null; $isMainCustom = isset($relatedInfo['custom_module']); $isRelatedCustom = $isCustomTable; $storedKey = $mainKey . '.' . $relatedTable; } } $hasRelatedCustom = $joinVariables[$mainFieldKey][$keyDepth][$storedKey]['isRelatedCustom']; $didCountJoin = $joinVariables[$mainFieldKey][$keyDepth][$storedKey]['doCountJoin']; if (isset($didCountJoin) && !$didCountJoin && $currentDoCountJoin) { $joinVariables[$mainFieldKey][$keyDepth][$storedKey]['doCountJoin'] = true; } if (!empty($mainKey) && $hasRelatedCustom !== true) { $currentDoJoin = $currentDoJoin || $joinVariables[$mainFieldKey][$keyDepth][$storedKey]['doJoin']; $currentDoCountJoin = $currentDoCountJoin || $joinVariables[$mainFieldKey][$keyDepth][$storedKey]['doCountJoin']; $joinVariables[$mainFieldKey][$keyDepth][$storedKey] = array('mainTable' => $mainTable, 'mainKey' => $mainKey, 'relatedTable' => $relatedTable, 'relatedKey' => $relatedKey, 'parentKey' => $parentKey, 'joinTable' => $joinTable['table'] == null && $joinTable['lhsKey'] == null && $joinTable['rhsKey'] == null ? null : $joinTable, 'isMainCustom' => $isMainCustom, 'isRelatedCustom' => $isRelatedCustom, 'avoidAlias' => $keyDepth >= 1 ? false : ($auditedReport ? true : false), 'doJoin' => $currentDoJoin, 'doCountJoin' => $currentDoCountJoin); } $lastTableName = $tableName; //********************************************// //***Get Indexes From Report Related Tables***// //********************************************// if (!isset($_SESSION['asolReportsTableIndexes'][$dbKey][$relatedTable])) { foreach (asol_Report::getSelectionResults("SHOW INDEX FROM " . $relatedTable, null, false, $alternativeDb) as $tableCurrentIndex) { $_SESSION['asolReportsTableIndexes'][$dbKey][$relatedTable][$tableCurrentIndex['Column_name']] = true; } } //********************************************// //***Get Indexes From Report Related Tables***// //********************************************// } //****************************************// //******Generate SQL Variable Joins*******// //****************************************// if (!empty($currentValues['sql'])) { self::getJoinsFromSqlVariables($currentValues['sql'], $currentDoJoin, $currentDoCountJoin, $alternativeDb, $reportModule, $reportTable, $joinVariables, $reportTableCustomJoin, $processedJoinsFromSqlKeys); } } $sqlJoin = ''; $sqlCountJoin = ''; $aliasIndexTable = array(); $varJoinIndex = 0; foreach ($joinVariables as $initKey => $mainJoinFields) { foreach ($mainJoinFields as $mainJoinIndex => $secondJoinFields) { $secondJoinIndex = 0; foreach ($secondJoinFields as $joinKey => $joinVar) { //***************************// //****Variable Definition****// //***************************// $parentKey = $joinVar['parentKey']; $mainTable = $joinVar['mainTable']; $mainKey = $joinVar['mainKey']; $relatedTable = $joinVar['relatedTable']; $relatedKey = $joinVar['relatedKey']; $joinTable = $joinVar['joinTable']; $isMainCustom = $joinVar['isMainCustom']; $isRelatedCustom = $joinVar['isRelatedCustom']; $avoidAlias = $joinVar['avoidAlias']; $doJoin = $joinVar['doJoin']; $doCountJoin = $joinVar['doCountJoin']; //***********************// //***AlineaSol Premium***// //***********************// $joinType = asol_ReportsUtils::managePremiumFeature("multiJoinReport", "reportFunctions.php", "getJoinType", array('joinsTable' => $fieldValues['tables'][0]['joins'], 'relatedTable' => $relatedTable)); $joinType = $joinType !== false ? $joinType : 'LEFT'; //***********************// //***AlineaSol Premium***// //***********************// //************************// //****Index Generation****// //************************// $parentAliasIndex = $mainJoinIndex > 0 ? $aliasIndexTable[$initKey][$mainJoinIndex - 1][$parentKey][$mainTable] . $aliasSuffix : $aliasSuffix; $currentAliasIndex = $avoidAlias ? $aliasSuffix : $varJoinIndex . $mainJoinIndex . $mainJoinIndex . $secondJoinIndex . $aliasSuffix; //**********************// //****SQL Generation****// //**********************// $sqlCurrentJoinQuery = ''; if ($isMainCustom && ($keyDepth >= 1 || !$reportTableAlreadyCustomJoined)) { $sqlCurrentJoinQuery .= ' LEFT JOIN ' . $mainTable . '_cstm ' . $mainTable . '_cstm' . ($keyDepth >= 1 ? $currentAliasIndex : '') . ' ON (' . $mainTable . $parentAliasIndex . '.id=' . $mainTable . '_cstm' . ($keyDepth >= 1 ? $currentAliasIndex : '') . '.id_c)'; $reportTableAlreadyCustomJoined = $reportTableAlreadyCustomJoined || $keyDepth === 0; } if ($joinTable === null) { $sqlCurrentJoinQuery .= ' ' . $joinType . ' JOIN ' . $relatedTable . ' ' . $relatedTable . $currentAliasIndex . ' ON (' . $mainTable . ($isMainCustom ? '_cstm' . ($keyDepth >= 1 ? $currentAliasIndex : '') : $parentAliasIndex) . '.' . $mainKey . '=' . $relatedTable . $currentAliasIndex . '.' . $relatedKey . ($isNonCrmDatabase ? '' : ' AND ' . $relatedTable . $currentAliasIndex . '.deleted=0') . ')'; } else { $sqlCurrentJoinQuery .= ' ' . $joinType . ' JOIN ' . $joinTable['table'] . ' ' . $joinTable['table'] . $currentAliasIndex . ' ON (' . $mainTable . ($isMainCustom ? '_cstm' . ($keyDepth >= 1 ? $currentAliasIndex : '') : $parentAliasIndex) . '.' . $mainKey . '=' . $joinTable['table'] . $currentAliasIndex . '.' . $joinTable['lhsKey'] . ' AND ' . $joinTable['table'] . $currentAliasIndex . '.deleted=0)'; $sqlCurrentJoinQuery .= ' ' . $joinType . ' JOIN ' . $relatedTable . ' ' . $relatedTable . $currentAliasIndex . ' ON (' . $joinTable['table'] . $currentAliasIndex . '.' . $joinTable['rhsKey'] . '=' . $relatedTable . $currentAliasIndex . '.' . $relatedKey . ($isNonCrmDatabase ? '' : ' AND ' . $relatedTable . $currentAliasIndex . '.deleted=0') . ')'; } if ($isRelatedCustom) { $sqlCurrentJoinQuery .= ' LEFT JOIN ' . $relatedTable . '_cstm ' . $relatedTable . '_cstm' . $currentAliasIndex . ' ON (' . $relatedTable . $currentAliasIndex . '.id=' . $relatedTable . '_cstm' . $currentAliasIndex . '.id_c)'; } //*************************************// //****Apply Query to SqlJoin String****// //*************************************// if ($doJoin) { $sqlJoin .= $sqlCurrentJoinQuery; } if ($doCountJoin) { $sqlCountJoin .= $sqlCurrentJoinQuery; } $aliasIndexTable[$initKey][$mainJoinIndex][$mainKey][$relatedTable] = $currentAliasIndex; $secondJoinIndex++; } } $varJoinIndex++; } //*******************************************************// //*****Generate Report Table Custom Join when Needed*****// //*******************************************************// if ($reportTableCustomJoin && !$reportTableAlreadyCustomJoined) { $sqlCurrentJoinQuery = ' LEFT JOIN ' . $reportTable . '_cstm ON (' . $reportTable . '.id=' . $reportTable . '_cstm.id_c)'; $sqlJoin .= $sqlCurrentJoinQuery; $sqlCountJoin .= $sqlCurrentJoinQuery; } //******************************************************// //******Override Fields & Filters with Table Alias******// //******************************************************// self::resetValuesWithJoinAlias($fieldValues['tables'][0]['data'], $aliasIndexTable, $reportTable, $auditedReport, $fieldsByRef, $aliasSuffix); self::resetValuesWithJoinAlias($filterValues, $aliasIndexTable, $reportTable, $auditedReport, $fieldsByRef, $aliasSuffix, false); //*******************************// //***Relation Domain Left Join***// //*******************************// if (asol_ReportsUtils::isDomainsInstalled()) { if ($domainField !== null) { if ($domainField != "") { if (isset($domainField["domainRelation"])) { $domainRelation = $domainField["domainRelation"]; $initKey = $domainRelation["linkField"]; $mainJoinIndex = 0; $mainKey = $initKey; $relatedTable = $domainRelation["relatedTable"]; $processedRelation = isset($aliasIndexTable[$initKey][$mainJoinIndex][$mainKey][$relatedTable]); $domainIndex = $aliasIndexTable[$initKey][$mainJoinIndex][$mainKey][$relatedTable]; if (!$processedRelation) { $domainIndex = count($fieldValues['tables'][0]['data']); $domainRelationTableAlias = $domainRelation["relatedTable"] . $domainIndex; $extendedJoin = " LEFT JOIN " . $domainRelation["relatedTable"] . " " . $domainRelationTableAlias . " ON (" . $reportTable . "." . $domainRelation["linkField"] . "=" . $domainRelationTableAlias . "." . $domainRelation["relatedKey"] . ") "; $sqlJoin .= $extendedJoin; $sqlCountJoin .= $extendedJoin; } else { $domainRelationTableAlias = $domainRelation["relatedTable"] . $domainIndex; } $domainField["domainRelation"]["relatedTable"] = $domainRelationTableAlias; } } } } //********************************// //***Relation Audited Left Join***// //********************************// if ($auditedReport) { $domainRelation = $domainField["domainRelation"]; $initKey = 'parent_id'; $mainJoinIndex = 0; $mainKey = $initKey; $relatedTable = $reportTable; $processedRelation = isset($aliasIndexTable[$initKey][$mainJoinIndex][$mainKey][$relatedTable]); $domainIndex = $aliasIndexTable[$initKey][$mainJoinIndex][$mainKey][$relatedTable]; if (!$processedRelation) { $domainIndex = count($fieldValues['tables'][0]['data']); $domainRelationTableAlias = $domainRelation["relatedTable"] . $domainIndex; $extendedJoin = " LEFT JOIN " . $relatedTable . " " . $relatedTable . " ON (" . $relatedTable . "_audit." . $mainKey . "=" . $relatedTable . ".id) "; $sqlJoin .= $extendedJoin; $sqlCountJoin .= $extendedJoin; } } //**************************************// //****Define Returned Function Array****// //**************************************// $returnedJoinArray = array("moduleCustomJoined" => false, "moduleCountCustomJoined" => false, "aliasIndexTable" => $aliasIndexTable, "querys" => array("Join" => $sqlJoin, "CountJoin" => $sqlCountJoin)); return $returnedJoinArray; }
} else { asol_ReportsUtils::reports_log('asol', 'Scheduled Reports with Id [' . $scheduledReport['id'] . '] has user_input filters', __FILE__, __METHOD__, __LINE__); } } } else { $scheduled_reports = unserialize(base64_decode($_REQUEST['scheduledReports'])); } //********************************// //****Current Report Execution****// //********************************// $currentScheduledReport = $scheduled_reports[0]; $record = $currentScheduledReport['id']; $currentUserId = $currentScheduledReport['created_by']; $reportType = explode(':', $currentScheduledReport['report_type']); $storeReport = $reportType[0] == 'stored' ? '&storedReport=true' : ''; $contextDomainId = asol_ReportsUtils::isDomainsInstalled() ? '&contextDomainId=' . $currentScheduledReport['domain_id'] : ''; $ch = curl_init(); $curlRequestUrl = isset($sugar_config["asolReportsCurlRequestUrl"]) ? $sugar_config["asolReportsCurlRequestUrl"] : $sugar_config["site_url"]; $requestedUrl = $curlRequestUrl . '/index.php?entryPoint=viewReport&record=' . $record . '&language=' . $current_language . '&sourceCall=httpReportRequest¤tUserId=' . $currentUserId . "&schedulerCall=true" . $storeReport . $contextDomainId; curl_setopt($ch, CURLOPT_URL, $requestedUrl); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_exec($ch); curl_close($ch); //********************************// //****Current Report Execution****// //********************************// //*****************************// //****Next Report Execution****// //*****************************// if (!empty($scheduled_reports[0])) {
$selectStatement .= ' OR id="' . $selectedReportIds[$i] . '"'; } } asol_ReportsUtils::reports_log('debug', 'Obtaning checked reports data [' . $selectStatement . ']', __FILE__, __METHOD__, __LINE__); $selectedReports = asol_Report::getSelectionResults($selectStatement, null, false); if (empty($selectedReports)) { asol_ReportsUtils::reports_log('error', 'No deletable reports were found', __FILE__, __METHOD__, __LINE__); header("Location: ./index.php?module=asol_Reports&action=index"); exit; } // checkings $deletableReportsIds = array(); foreach ($selectedReports as $currentReport) { $user_modifiable = asol_ReportsManagementFunctions::userCanModifyReport($currentReport['created_by'], $currentReport['assigned_user_id']); $role_modifiable = asol_ReportsManagementFunctions::roleCanModifyReport($idsRoles); $domain_modifiable = asol_ReportsUtils::isDomainsInstalled() ? asol_ReportsManagementFunctions::domainCanModifyReport($currentReport['asol_domain_id']) : true; if (($user_modifiable || ${$role_modifiable}) && $domain_modifiable && $REPORTS_ACL_DELETE) { asol_ReportsUtils::reports_log('debug', 'Report deletable [' . $currentReport['id'] . ']', __FILE__, __METHOD__, __LINE__); $deletableReportsIds[] = $currentReport['id']; } else { asol_ReportsUtils::reports_log('debug', 'Report undeletable [' . $currentReport['id'] . ']', __FILE__, __METHOD__, __LINE__); } } if (empty($deletableReportsIds)) { asol_ReportsUtils::reports_log('error', 'Unauthorized to remove all these reports', __FILE__, __METHOD__, __LINE__); header("Location: ./index.php?module=asol_Reports&action=index"); exit; } asol_ReportsUtils::reports_log('info', 'Found ' . count($deletableReportsIds) . ' reports to be deleted [' . implode(', ', $deletableReportsIds) . ']', __FILE__, __METHOD__, __LINE__); $deleteStatement = 'UPDATE asol_reports SET date_modified="' . gmdate("Y-m-d H:i:s") . '", modified_user_id="' . $current_user->id . '", deleted=1 WHERE'; for ($i = 0; $i < count($deletableReportsIds); $i++) {
public static function migrateReportTypeToSerialized($reportType) { global $current_user, $db; $storedReportType = explode('${dp}', $reportType); if (count($storedReportType) == 1) { return $reportType; } else { $storedKey = !asol_ReportsUtils::isDomainsInstalled() ? 'base' : $current_user->asol_default_domain; $txtFile = null; $xmlFiles = null; $subGroups = null; $types = null; $storedReportTypeUrl = explode('&', $storedReportType[1]); foreach ($storedReportTypeUrl as $storedReportTypeUrlParam) { $storedReportTypeUrlParamValues = explode('=', $storedReportTypeUrlParam); if ($storedReportTypeUrlParamValues[0] == 'txtFile') { $txtFile = $storedReportTypeUrlParamValues[1]; } else { if ($storedReportTypeUrlParamValues[0] == 'xmlFiles') { $xmlFiles = explode('|', $storedReportTypeUrlParamValues[1]); } else { if ($storedReportTypeUrlParamValues[0] == 'subGroups') { $subGroups = explode('|', $storedReportTypeUrlParamValues[1]); } else { if ($storedReportTypeUrlParamValues[0] == 'types') { $types = explode('|', $storedReportTypeUrlParamValues[1]); } } } } } $chartFiles = array(); foreach ($xmlFiles as $chartKey => $xmlFile) { if (!empty($xmlFile)) { $chartFiles[] = array('file' => $xmlFile, 'type' => $types[$chartKey], 'subGroups' => $subGroups[$chartKey]); } } $reportTypeArray[$storedKey] = array('infoTxt' => $txtFile, 'chartFiles' => $chartFiles); $storedReportTypeSerialized = base64_encode(serialize($reportTypeArray)); return $storedReportTypeSerialized; } }