コード例 #1
0
ファイル: save.php プロジェクト: jeffcao/fzglsys_v5
} 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 {
    $return_action = "index";
}
if (isset($_POST['return_id']) && $_POST['return_id'] != "") {
    $return_id = $_POST['return_id'];
}
asol_ReportsUtils::reports_log('asol', 'Saved record with id of ' . $reportId, __FILE__, __METHOD__, __LINE__);
header("Location: index.php?action=" . $return_action . "&module=" . $return_module);
コード例 #2
0
ファイル: generateReport.php プロジェクト: jeffcao/fzglsys_v5
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("&#039", "\\&#039", str_replace("'", "\\&#039", 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']) ? "&currentUserId=" . $_REQUEST['currentUserId'] : "&currentUserId=" . $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);
                }
            }
        }
    }
}
コード例 #3
0
                    //********//
                    //**Curl**//
                    //********//
                    $sqlExecutingStatus = "UPDATE asol_reports_dispatcher SET status = 'executing' WHERE id='" . $_REQUEST["reportRequestId"] . "' AND status = 'waiting' LIMIT 1";
                    $db->query($sqlExecutingStatus);
                    $returnedString = "exec";
                }
            }
        }
        $recallGMTTime = time();
        $recallGMTDate = date('Y-m-d H:i:s', $recallGMTTime);
        $initGMTDateTimeStamp = $_REQUEST["initRequestDateTimeStamp"];
        $recallGMTDateTimeStamp = $recallGMTDate;
        //Check Max Report Execution time
        $runningTimeSeconds = $recallGMTDateTimeStamp - $initGMTDateTimeStamp;
        asol_ReportsUtils::reports_log('debug', 'Running Time: ' . $runningTimeSeconds, __FILE__, __METHOD__, __LINE__);
        if (isset($sugar_config['asolReportsMaxExecutionTime']) && $sugar_config['asolReportsMaxExecutionTime'] > 0) {
            if ($runningTimeSeconds > $sugar_config['asolReportsMaxExecutionTime']) {
                $returnedString = "timeout";
            }
        }
        $sqlLastRecall = "UPDATE asol_reports_dispatcher SET last_recall='" . $recallGMTDate . "' WHERE id='" . $_REQUEST["reportRequestId"] . "' LIMIT 1";
        $db->query($sqlLastRecall);
    }
    echo $returnedString;
} else {
    $importHttpFile = fopen($tmpFilesDir . $httpHtmlFile, "r");
    $HttpContent = fread($importHttpFile, filesize($tmpFilesDir . $httpHtmlFile));
    fclose($importHttpFile);
    echo $HttpContent;
}
コード例 #4
0
ファイル: reportDownload.php プロジェクト: jeffcao/fzglsys_v5
<?php

require_once "modules/asol_Reports/include_basic/reportsUtils.php";
global $sugar_config;
asol_ReportsUtils::reports_log('asol', 'Getting File ' . $_REQUEST['fileName'], __FILE__, __METHOD__, __LINE__);
$tmpFilesDir = "modules/asol_Reports/tmpReportFiles/";
$op = isset($_REQUEST['op']) ? $_REQUEST['op'] : "";
setcookie("fileDownloadToken", "token");
// blockUI
if ($op != "css") {
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=\"" . trim($_REQUEST['fileName']) . "\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($tmpFilesDir . trim($_REQUEST['fileName'])));
    readfile($tmpFilesDir . trim($_REQUEST['fileName']));
} else {
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=\"" . trim($_REQUEST['fileName']) . "\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize("modules/asol_Reports/include_basic/css/" . trim($_REQUEST['fileName'])));
    readfile("modules/asol_Reports/include_basic/css/" . trim($_REQUEST['fileName']));
}
コード例 #5
0
 public static function doFinalExecuteReportActions($reportId, $dispatcherMaxRequests = null)
 {
     global $db;
     if (isset($dispatcherMaxRequests)) {
         if ($dispatcherMaxRequests > 0 && isset($_REQUEST["reportRequestId"])) {
             //Only if dispatcher is activated
             $db->query("UPDATE asol_reports_dispatcher SET status = 'terminated', last_recall = '" . date("Y-m-d H:i:s", time()) . "' WHERE id = '" . $_REQUEST["reportRequestId"] . "' LIMIT 1");
         }
     }
     $db->query("UPDATE asol_reports SET last_run = '" . gmdate("Y-m-d H:i:s") . "' WHERE id = '" . $reportId . "' LIMIT 1");
     asol_ReportsUtils::reports_log('asol', 'Updated last_run for Report with Id [' . $reportId . ']', __FILE__, __METHOD__, __LINE__);
 }
コード例 #6
0
ファイル: reportPopup.php プロジェクト: jeffcao/fzglsys_v5
<?php

if (!defined('sugarEntry') || !sugarEntry) {
    die('Not A Valid Entry Point');
}
require_once "modules/asol_Reports/include_basic/reportsUtils.php";
error_reporting(1);
//E_ERROR
global $mod_strings, $sugar_config;
asol_ReportsUtils::reports_log('asol', 'Entering reportPopup.php', __FILE__, __METHOD__, __LINE__);
echo "<html>";
echo "<head>";
echo "<link rel='shortcut icon' href='themes/default/images/sugar_icon.ico'>";
echo "<script language='javascript'>";
if (!empty($_REQUEST['domainId']) && is_file("modules/asol_Reports/include_basic/css/" . $_REQUEST['domainId'] . ".css")) {
    $customCssFile = $_REQUEST['domainId'] . ".css";
} else {
    $customCssFile = "reports.css";
}
echo '

function getHTTPObject(){
	var http;
	/*@cc_on
	@if(@_jscript_version>=5)
		try{
			http=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				http=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e2){
コード例 #7
0
ファイル: scheduledTask.php プロジェクト: jeffcao/fzglsys_v5
                                $scheduled_reports[] = array('id' => $scheduledReports[$key]['id'], 'created_by' => $scheduledReports[$key]['created_by'], 'report_type' => $scheduledReports[$key]['report_type'], 'domain_id' => $reportDomainId);
                                asol_ReportsUtils::reports_log('asol', 'Scheduled Report Id: ' . $scheduledReports[$key]['id'] . ' Domain: ' . $reportDomainId . ' ', __FILE__, __METHOD__, __LINE__);
                            }
                        } else {
                            $scheduled_reports[] = array('id' => $scheduledReports[$key]['id'], 'created_by' => $scheduledReports[$key]['created_by'], 'report_type' => $scheduledReports[$key]['report_type'], 'domain_id' => null);
                            asol_ReportsUtils::reports_log('asol', 'Scheduled Report Id: ' . $scheduledReport['id'], __FILE__, __METHOD__, __LINE__);
                        }
                        //Se rompe el bucle foreach una vez se haya comprobado que hay que realizar una tarea
                        break;
                    }
                    //Fin de la condicion de que se cumpla la fecha y hora
                }
                //Fin de la condicion de que la tarea actual este activa
            }
        } 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();
コード例 #8
0
ファイル: index.php プロジェクト: jeffcao/fzglsys_v5
                    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++) {
                $currentReportId = $deletableReportsIds[$i];
                if ($i == 0) {
                    $deleteStatement .= ' id="' . $currentReportId . '"';
                } else {
                    $deleteStatement .= ' OR id="' . $currentReportId . '"';
                }
            }
            asol_ReportsUtils::reports_log('debug', 'Deleting deletable reports [' . $deleteStatement . ']', __FILE__, __METHOD__, __LINE__);
            if ($db->query($deleteStatement)) {
                asol_ReportsUtils::reports_log('info', 'Deleted ' . count($deletableReportsIds) . ' reports from database', __FILE__, __METHOD__, __LINE__);
            } else {
                asol_ReportsUtils::reports_log('error', 'Error deleting ' . count($deletableReportsIds) . ' reports from database', __FILE__, __METHOD__, __LINE__);
            }
            header("Location: ./index.php?module=asol_Reports&action=index");
        }
    }
}
コード例 #9
0
ファイル: asol_Report.php プロジェクト: jeffcao/fzglsys_v5
 public static function getSelectionResults($query, $columnAsKey = null, $useAlternativeDb = true, $notCrmExternalDb = false, $detailColumn = null, $formatInfo = null, $avoidLogging = false)
 {
     global $sugar_config, $db, $current_user, $mod_strings;
     self::$reported_error = self::$reported_error === null ? null : self::$reported_error;
     $query = html_entity_decode($query);
     $retArray = array();
     if (!$avoidLogging) {
         asol_ReportsUtils::reports_log('debug', 'ASOL_Reports query ----> [ ' . $query . ' ]', __FILE__, __METHOD__, __LINE__);
     }
     if ((!isset($sugar_config["asolReportsDbAddress"]) || !$useAlternativeDb) && $notCrmExternalDb === false) {
         $queryResults = $db->query($query);
         while ($queryRow = $db->fetchByAssoc($queryResults)) {
             if (isset($detailColumn)) {
                 $theGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($formatInfo['reportId'], $formatInfo['dashletId'], $queryRow['asol_grouping_field'], $detailColumn, $formatInfo['userDateFormat'], $formatInfo['userTZ'], $formatInfo['currencyId'], $formatInfo['gmtDates']);
                 unset($queryRow['asol_grouping_field']);
                 $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup;
                 $retArray[$theGroup][] = $queryRow;
             } else {
                 if (isset($columnAsKey)) {
                     $retArray[$queryRow[$columnAsKey]] = $queryRow;
                 } else {
                     $retArray[] = $queryRow;
                 }
             }
         }
     } else {
         $mysqli = self::getMySqlConnection($notCrmExternalDb);
         if ($mysqli === false) {
             return;
         }
         $queryResults = $mysqli->query($query);
         if (!$queryResults) {
             if (!$avoidLogging) {
                 self::$reported_error = mysqli_error($mysqli);
                 asol_ReportsUtils::reports_log('fatal', 'ASOL_Reports ErrorQuery ----> [ ' . mysqli_error($mysqli) . ' ]', __FILE__, __METHOD__, __LINE__);
             }
         } else {
             while ($queryRow = $queryResults->fetch_assoc()) {
                 if (isset($detailColumn)) {
                     $theGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($formatInfo['reportId'], $formatInfo['dashletId'], $queryRow['asol_grouping_field'], $detailColumn, $formatInfo['userDateFormat'], $formatInfo['userTZ'], $formatInfo['currencyId'], $formatInfo['gmtDates']);
                     unset($queryRow['asol_grouping_field']);
                     $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup;
                     $retArray[$theGroup][] = $queryRow;
                 } else {
                     if (isset($columnAsKey)) {
                         $retArray[$queryRow[$columnAsKey]] = $queryRow;
                     } else {
                         $retArray[] = $queryRow;
                     }
                 }
             }
         }
         if ($queryResults) {
             $queryResults->close();
         }
         mysqli_close($mysqli);
     }
     //checkReportsMaxExecutionTime();
     if (isset($sugar_config['asolReportsMaxExecutionTime']) && $sugar_config['asolReportsMaxExecutionTime'] > 0 && isset($_REQUEST["reportRequestId"]) && isset($_REQUEST["initRequestDateTimeStamp"])) {
         $initGmtDateTimeStamp = $_REQUEST["initRequestDateTimeStamp"];
         $currentGmtTimeStamp = time();
         $runningTimeSeconds = $currentGmtTimeStamp - $initGmtDateTimeStamp;
         if (!$avoidLogging) {
             asol_ReportsUtils::reports_log('debug', 'ASOL_Reports checkReportsMaxExecutionTime ----> [ ' . $runningTimeSeconds . ' Seconds ]', __FILE__, __METHOD__, __LINE__);
         }
         if ($runningTimeSeconds > $sugar_config['asolReportsMaxExecutionTime']) {
             if (!$avoidLogging) {
                 asol_ReportsUtils::reports_log('fatal', 'Report with Request_Id [' . $_REQUEST["reportRequestId"] . '] has TimedOut!!', __FILE__, __METHOD__, __LINE__);
             }
             $sqlExecutingStatus = "UPDATE asol_reports_dispatcher SET status = 'timeout' WHERE id='" . $_REQUEST["reportRequestId"] . "' LIMIT 1";
             $db->query($sqlExecutingStatus);
             echo translate('LBL_REPORT_TIMEOUT', 'asol_Reports');
             if (!$avoidLogging) {
                 asol_ReportsUtils::reports_log('fatal', 'ASOL_Reports Execution TimedOut ----> [ ' . $sugar_config['asolReportsMaxExecutionTime'] . ' Seconds for asolReportsMaxExecutionTime]', __FILE__, __METHOD__, __LINE__);
             }
             exit;
         }
     }
     return $retArray;
 }
コード例 #10
-20
ファイル: ReportFile.php プロジェクト: jeffcao/fzglsys_v5
function generateFile($chartEngine, $reportName, $module, $description, $headers, $resultset, $headersTotals, $totals, $subTotals, $isDetailedReport, $pdf_orientation, $pngs, $legendChart, $isHTML, $store, $pdf_img_scaling_factor, $reportDate, $userTZ, $rowIndex = 0, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $domainId = "")
{
    //$pdf_img_scaling_factor solo usada para Exports & Emails
    global $sugar_config, $mod_strings, $current_language;
    $asolDefaultLanguage = isset($sugar_config["asolReportsDefaultExportedLanguage"]) ? $sugar_config["asolReportsDefaultExportedLanguage"] : "en_us";
    $current_language = empty($current_language) ? $asolDefaultLanguage : $current_language;
    $mod_strings = return_module_language($current_language, "asol_Reports");
    $tableClass = $isHTML ? 'htmlTable' : 'pdfTable';
    asol_ReportsUtils::reports_log('asol', 'Entering at ReportPDF', __FILE__, __METHOD__, __LINE__);
    $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/";
    $currentDir = getcwd() . "/";
    $idFile = preg_replace('/[^a-zA-Z0-9]/', '', $reportName) . "_" . date("Ymd") . "T" . date("His");
    asol_ReportsUtils::reports_log('asol', 'Generating PDF: ' . $idFile, __FILE__, __METHOD__, __LINE__);
    //GENERAMOS EL HTML
    $html = '';
    //Get the required css
    $cssURL = is_file("modules/asol_Reports/include_basic/css/" . $domainId . ".css") ? "modules/asol_Reports/include_basic/css/" . $domainId . ".css" : "modules/asol_Reports/include_basic/css/reports.css";
    //Get the required company logo
    if (is_file("modules/asol_Domains/logos/" . $domainId . ".png")) {
        $logoURL = "modules/asol_Domains/logos/" . $domainId . ".png";
    } else {
        $logoURL = is_file("custom/themes/default/images/company_logo.png") ? "custom/themes/default/images/company_logo.png" : "themes/default/images/company_logo.png";
    }
    //Get CSS file content
    ob_start();
    include $cssURL;
    $cssContent = ob_get_contents();
    ob_end_clean();
    $htmlCss = '<style>' . $cssContent . '</style>';
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    if ($currentReportCss !== false) {
        $htmlCss .= $currentReportCss;
    }
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    if ($isHTML) {
        $moduleHeader = !empty($module) ? ' - ' . $mod_strings['LBL_REPORT_MODULE_HEADER_LABEL'] . ' ' . $module : '';
        $logoBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($logoURL));
        $html .= '<table class="header-title ' . $tableClass . '"><tr><td rowspan="3"><img src="' . $logoBase64 . '"></td><td>' . $reportName . $moduleHeader . '</td></tr><tr><td>' . $description . '</td></tr><tr><td>' . date("Y-m-d H:i:s", $reportDate) . ' - ' . $userTZ . '</td></tr></table>';
    }
    $htmlChart = '';
    $pdfChart = array();
    if (count($pngs) > 0) {
        $today = dechex(time()) . dechex(rand(0, 999999));
        if (count($resultset) > 0 && $report_charts == 'Both') {
            $htmlChart .= '<div style="page-break-after: always;">&nbsp;</div>';
        }
        foreach ($pngs as $key => $png) {
            if ($isHTML) {
                $htmlChart .= '<br>';
            }
            switch ($chartEngine) {
                case "flash":
                case "html5":
                    if ($isHTML) {
                        $imgData = strpos($png, "data:image/png;base64,") !== false ? $png : "data:image/png;base64," . $png;
                    } else {
                        $somecontent = base64_decode(str_replace("data:image/png;base64,", "", $png));
                        $filename = $key . "_" . $today . '.png';
                        if ($handle = fopen($tmpFilesDir . $filename, 'w+')) {
                            if (!fwrite($handle, $somecontent) === FALSE) {
                                fclose($handle);
                            }
                        }
                        $pdfChart[] = $imgData = $tmpFilesDir . $filename;
                    }
                    $htmlChart .= '<table class="' . $tableClass . '"><tbody><tr><td><img class="chart-img" src="' . $imgData . '"></td></tr></tbody></table>';
                    if (!empty($legendChart)) {
                        $htmlChart .= '<table class="' . $tableClass . '"><tbody><tr><td><div class="legend">' . urldecode($legendChart[$key]) . '</div></td></tr></tbody></table>';
                    }
                    break;
                case "nvd3":
                    if (!$isHTML) {
                        if (isset($sugar_config["asolReportsPhantomJsFilePath"]) && is_file($sugar_config["asolReportsPhantomJsFilePath"])) {
                            $svgData = '<html><body>' . $htmlCss . str_replace("'", "\"", urldecode($png)) . '</body></html>';
                            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                                $fileSVGname = $key . "_" . $today . '.svg.html';
                                if ($handle = fopen($tmpFilesDir . $fileSVGname, 'w')) {
                                    if (!fwrite($handle, $svgData) === FALSE) {
                                        fclose($handle);
                                    }
                                }
                                $svgImgFile = $tmpFilesDir . $fileSVGname;
                                $somecontent = base64_decode(shell_exec($sugar_config["asolReportsPhantomJsFilePath"] . ' modules/asol_Reports/include_basic/js/phantomjs/rasterizeBase64.js ' . $svgImgFile));
                                unlink($svgImgFile);
                            } else {
                                $somecontent = base64_decode(shell_exec($sugar_config["asolReportsPhantomJsFilePath"] . ' modules/asol_Reports/include_basic/js/phantomjs/renderSVGtags.js \'' . $svgData . '\''));
                            }
                            $filename = $key . "_" . $today . '.png';
                            if ($handle = fopen($tmpFilesDir . $filename, 'w')) {
                                if (!fwrite($handle, $somecontent) === FALSE) {
                                    fclose($handle);
                                }
                            }
                            $pdfChart[] = $imgData = $tmpFilesDir . $filename;
                            $htmlChart .= '<table class="' . $tableClass . '"><tbody><tr><td>' . urldecode($legendChart[$key]) . '</td></tr><tr><td><img class="chart-img" src="' . $imgData . '"></td></tr></tbody></table>';
                        } else {
                            $htmlChart .= '<table class="' . $tableClass . '"><tbody><tr><td>Download <a href="http://phantomjs.org/">phantomJS</a> to render SVG images with TCPDF</td></tr></tbody></table>';
                        }
                    } else {
                        $htmlChart .= '<table class="' . $tableClass . '"><tbody><tr><td>' . urldecode($legendChart[$key]) . '</td></tr><tr><td>' . urldecode($png) . '</td></tr></tbody></table>';
                    }
                    break;
                default:
                    break;
            }
            if ($key < count($pngs) - 1 || $report_charts == 'Htob') {
                $htmlChart .= '<div style="page-break-after: always;">&nbsp;</div>';
            }
        }
    }
    if (in_array($report_charts, array('Htob', 'Char'))) {
        $html .= $htmlChart;
    }
    if ($report_charts != 'Char') {
        $html .= '<table class="' . $tableClass . '"><tbody>';
        $html .= '<tr><td class="header">' . $mod_strings['LBL_REPORT_RESULTS'] . '</td></tr></tbody></table>';
    } else {
        $rowIndex = 0;
        $headers = array();
        $resultset = array();
    }
    if (!$isDetailedReport) {
        $html .= '<table class="' . $tableClass . '"><tbody>';
        $columns = '<tr>';
        if ($rowIndex == 1) {
            $dataType = 'index';
            $cellClasses = 'data_header data_cell report_header report_cell data_header_' . $dataType . ' data_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
            $columns .= '<th class="' . $cellClasses . '">N&deg;</th>';
        }
        foreach ($headers as $column) {
            $dataType = $columnsDataTypes[$column];
            $dataVisible = $columnsDataVisible[$column];
            $cellClasses = 'data_header data_cell report_header report_cell data_header_' . $dataType . ' data_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
            $cellClasses .= $dataVisible == 'html' ? ' headerCellHidden' : '';
            $columns .= '<th class="' . $cellClasses . '">' . $column . '</th>';
        }
        $columns .= '</tr>';
        $html .= $columns;
        $cont = 0;
        if (count($resultset) == 0) {
            $resultset = array();
        }
        foreach ($resultset as $row) {
            $rowSet = '<tr>';
            if ($rowIndex == 1) {
                $dataType = 'index';
                $cellClasses = 'data_value data_cell report_value report_cell data_value_' . $dataType . ' data_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                $cellClasses .= $cont % 2 != 0 ? ' row-uneven' : ' row-even';
                $rowSet .= '<td class="' . $cellClasses . '">' . ($cont + 1) . '</td>';
            }
            foreach ($row as $key => $value) {
                $dataType = $columnsDataTypes[$key];
                $dataVisible = $columnsDataVisible[$key];
                $cellClasses = 'data_value data_cell report_value report_cell data_value_' . $dataType . ' data_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                $cellClasses .= $dataVisible == 'html' ? ' dataCellHidden' : '';
                $cellClasses .= $cont % 2 != 0 ? ' row-uneven' : ' row-even';
                $rowSet .= '<td class="' . $cellClasses . '">' . $value . '</td>';
            }
            $html .= $rowSet . '</tr>';
            $cont++;
        }
        $html .= '</tbody></table><br>';
    } else {
        $visibleHeaders = 0;
        foreach ($headers as $column) {
            $visibleHeaders += $columnsDataVisible[$column] == 'html' ? 0 : 1;
        }
        foreach ($resultset as $key => $subGroup) {
            $html .= '<table class="' . $tableClass . '"><tbody>';
            $html .= '<tr><td class="header-group" colspan="' . ($visibleHeaders + $rowIndex) . '">' . strtoupper($key) . '</td></tr>';
            $columns = '<tr>';
            if ($rowIndex == 1) {
                $dataType = 'index';
                $cellClasses = 'data_header data_cell report_header report_cell data_header_' . $dataType . ' data_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
                $columns .= '<th class="' . $cellClasses . '">N&deg;</th>';
            }
            foreach ($headers as $column) {
                $dataType = $columnsDataTypes[$column];
                $dataVisible = $columnsDataVisible[$column];
                $cellClasses = 'data_header data_cell report_header report_cell data_header_' . $dataType . ' data_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
                $cellClasses .= $dataVisible == 'html' ? ' headerCellHidden' : '';
                $columns .= '<th class="' . $cellClasses . '">' . $column . '</th>';
            }
            $columns .= '</tr>';
            $html .= $columns;
            $cont = 0;
            foreach ($subGroup as $row) {
                $rowSet = '<tr>';
                if ($rowIndex == 1) {
                    $dataType = 'index';
                    $cellClasses = 'data_value data_cell report_value report_cell data_value_' . $dataType . ' data_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                    $cellClasses .= $cont % 2 != 0 ? ' row-uneven' : ' row-even';
                    $rowSet .= '<td class="' . $cellClasses . '">' . ($cont + 1) . '</td>';
                }
                foreach ($row as $key2 => $value) {
                    $dataType = $columnsDataTypes[$key2];
                    $dataVisible = $columnsDataVisible[$key2];
                    $cellClasses = 'data_value data_cell report_value report_cell data_value_' . $dataType . ' data_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                    $cellClasses .= $dataVisible == 'html' ? ' dataCellHidden' : '';
                    $cellClasses .= $cont % 2 != 0 ? ' row-uneven' : ' row-even';
                    $rowSet .= '<td class="' . $cellClasses . '">' . $value . '</td>';
                }
                $html .= $rowSet . '</tr>';
                $cont++;
            }
            $html .= '</tbody></table>';
            // Subtotals beginning
            if (!empty($subTotals)) {
                $html .= '<table class="' . $tableClass . '"><tbody>';
                $html .= '<tr><td class="header-subtotal" rowspan="2" style="width: 20%;">' . $key . ' ' . $mod_strings['LBL_REPORT_SUBTOTALS'] . '</td>';
                $columnsTotals = '';
                foreach ($headersTotals as $columnTotal) {
                    $dataType = $columnsDataTypes[$key4];
                    $dataVisible = $columnsDataVisible[$key4];
                    $cellClasses = 'subtotal_header subtotal_cell report_header report_cell subtotal_header_' . $dataType . ' subtotal_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
                    $cellClasses .= $dataVisible == 'html' ? ' subHeaderCellHidden' : '';
                    $columnsTotals .= '<td class="' . $cellClasses . '" style="width: ' . 80 / count($headersTotals) . '%">' . $columnTotal["alias"] . '</td>';
                }
                $html .= $columnsTotals . '</tr>';
                $rowTotals = '<tr>';
                if (empty($subTotals[$key])) {
                    $subTotals[$key] = array();
                }
                foreach ($subTotals[$key] as $key5 => $value) {
                    $dataType = $columnsDataTypes[$key5];
                    $dataVisible = $columnsDataVisible[$key5];
                    $cellClasses = 'subtotal_value subtotal_cell report_value report_cell subtotal_value_' . $dataType . ' subtotal_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                    $cellClasses .= $dataVisible == 'html' ? ' subtotalCellHidden' : '';
                    $rowTotals .= '<td class="' . $cellClasses . '">' . $value . '</td>';
                }
                $html .= $rowTotals . '</tr>';
                $html .= '</tbody></table>';
            }
            // Subtotals end
            $html .= '<br />';
        }
    }
    // Totals beginning
    if (!empty($totals)) {
        $html .= '<br><table class="' . $tableClass . '"><tbody>';
        $html .= '<tr><td class="header">' . $mod_strings['LBL_REPORT_TOTALS'] . '</td></tr></tbody></table>';
        $html .= '<table class="' . $tableClass . '"><tbody>';
        $columnsTotals = '<tr>';
        foreach ($headersTotals as $totalColumn) {
            $dataType = $columnsDataTypes[$totalColumn['alias']];
            $dataVisible = $columnsDataVisible[$totalColumn['alias']];
            $cellClasses = 'total_header total_cell report_header report_cell total_header_' . $dataType . ' total_cell_' . $dataType . ' report_header_' . $dataType . ' report_cell_' . $dataType;
            $cellClasses .= $dataVisible == 'html' ? ' totalHeaderCellHidden' : '';
            $columnsTotals .= '<th class="' . $cellClasses . '">' . $totalColumn["alias"] . '</th>';
        }
        $columnsTotals .= '</tr>';
        if (count($totals) > 0) {
            $html .= $columnsTotals;
        }
        $rowTotals = '<tr>';
        foreach ($totals as $total) {
            foreach ($total as $key => $value) {
                $dataType = $columnsDataTypes[$key];
                $dataVisible = $columnsDataVisible[$key];
                $cellClasses = 'total_value total_cell report_value report_cell total_value_' . $dataType . ' total_cell_' . $dataType . ' report_value_' . $dataType . ' report_cell_' . $dataType;
                $cellClasses .= $dataVisible == 'html' ? ' totalCellHidden' : '';
                $rowTotals .= '<td class="' . $cellClasses . '">' . $value . '</td>';
            }
        }
        $rowTotals .= '</tr>';
        $html .= $rowTotals;
        $html .= '</tbody></table>';
    }
    // Totals end
    if ($report_charts == 'Both') {
        $html .= $htmlChart;
    }
    if ($isHTML) {
        $idFile .= ".html";
        $html = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>" . $htmlCss . $html . "</body></html>";
        $descriptor = fopen($currentDir . $tmpFilesDir . $idFile, "w");
        fwrite($descriptor, $html);
        fclose($descriptor);
        if (!$store) {
            setcookie("fileDownloadToken", "token");
            // blockUI
            header("Content-type: application/force-download");
            header("Content-Disposition: attachment; filename=\"" . $idFile . "\"");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($tmpFilesDir . $idFile));
            readfile($tmpFilesDir . $idFile);
            //Eliminamos ficheros tmp
            unlink($tmpFilesDir . $idFile);
        } else {
            //Almacenar el html y devolver la ruta y nombre del fichero
            return $idFile;
        }
    } else {
        $idFile .= ".pdf";
        asol_ReportsUtils::reports_log('asol', 'Instantiating and configuring PDF', __FILE__, __METHOD__, __LINE__);
        //Define ASOL images base path
        define('ASOL_PATH_IMAGES', $currentDir);
        $tcpdf_orientation = $pdf_orientation == "landscape" ? 'L' : 'P';
        $pdf = new TCPDF($tcpdf_orientation, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        // set default header data
        $moduleHeader = !empty($module) ? ' - ' . $mod_strings['LBL_REPORT_MODULE_HEADER_LABEL'] . ' ' . $module : '';
        $pdfTitle = $reportName . $moduleHeader;
        $pdfSubtitle = date("Y-m-d H:i:s", $reportDate) . " - " . $userTZ;
        $logoImageWidth = 40;
        $pdf->SetHeaderData($logoURL, $logoImageWidth, $pdfTitle, $pdfSubtitle);
        if (isset($sugar_config["asolReportsExportPdfFontTTF"])) {
            $fontName = $sugar_config["asolReportsExportPdfFontTTF"];
            if (!file_exists('modules/asol_Reports/tcpdf/fonts/' . $fontName . '.php')) {
                $pdf->addTTFfont('modules/asol_Reports/tcpdf/fonts/' . $fontName . '.ttf', 'TrueTypeUnicode', '', 32);
            }
        } else {
            $fontName = 'Helvetica';
        }
        // set header and footer fonts
        $pdf->setHeaderFont(array($fontName, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(array($fontName, '', PDF_FONT_SIZE_DATA));
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont($fontName);
        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        asol_ReportsUtils::reports_log('asol', 'Loading HTML with PDF', __FILE__, __METHOD__, __LINE__);
        if (isset($sugar_config["asolReportsExportReplaceByEmptyString"])) {
            foreach ($sugar_config["asolReportsExportReplaceByEmptyString"] as $token) {
                $html = str_replace($token, "", $html);
            }
        }
        $pdf->SetFont($fontName, '', 8, '', true);
        $pdf->AddPage();
        $pdf->writeHTML($htmlCss . $html, true, false, true, false);
        $pdf->lastPage();
        $pdf->Output($currentDir . $tmpFilesDir . $idFile, 'F');
        foreach ($pdfChart as $key => $chart) {
            unlink($chart);
        }
        return $idFile;
    }
}