Merge branch 'ent-9801-bloqueo-de-boton-en-generacion-de-ficheros-pdf-csv-json-varias-secciones' into 'develop'

Prepare download control

See merge request artica/pandorafms!5276
This commit is contained in:
Diego Muñoz-Reja 2022-12-12 08:29:51 +00:00
commit 31919d4d2c
23 changed files with 157 additions and 45 deletions

View File

@ -124,6 +124,8 @@ if (!empty($groups)) {
if (!empty($downtimes)) {
ob_clean();
// Show contentype header
// Set cookie for download control.
setDownloadCookieToken();
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="pandora_planned_downtime_'.date('Y/m/d H:i:s').'.csv"');
@ -161,7 +163,7 @@ if (!empty($downtimes)) {
if (!empty($downtime_agents)) {
foreach ($downtime_agents as $downtime_agent) {
$downtime_items = [];
$downtime_items[] = $downtime_agent[alias];
$downtime_items[] = $downtime_agent['alias'];
if (!$downtime_agent['all_modules']) {
$agent_id = $downtime_agent['agent_id'];

View File

@ -907,7 +907,7 @@ if ($downtimes === false && $filter_performed === false) {
__('Export to CSV'),
'csv_export',
false,
'location.href="godmode/agentes/planned_downtime.export_csv.php?'.$filter_params_str.'"',
'blockResubmit($(this)); location.href=\'godmode/agentes/planned_downtime.export_csv.php?'.$filter_params_str.'\'',
'class="sub next"'
);
echo '</div>';

View File

@ -189,6 +189,8 @@ if ($export_profile) {
}
}
// Set cookie for download control.
setDownloadCookieToken();
// Send headers to tell the browser we're sending a file
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename='.preg_replace('/\s/', '_', $profile_info['name']).'.csv');
@ -285,7 +287,7 @@ foreach ($result as $row) {
]
);
$data[3] = '<a href="index.php?sec=gmodules&sec2=godmode/modules/manage_network_templates'.'&delete_profile=1&delete_profile='.$row['id_np'].'" '.'onclick="if (!confirm(\''.__('Are you sure?').'\')) return false;">'.html_print_image('images/cross.png', true, ['title' => __('Delete'), 'class' => 'invert_filter']).'</a>';
$data[3] .= '<a href="index.php?sec=gmodules&sec2=godmode/modules/manage_network_templates'.'&export_profile='.$row['id_np'].'">'.html_print_image('images/csv.png', true, ['title' => __('Export to CSV'), 'class' => 'invert_filter']).'</a>';
$data[3] .= '<a onclick="blockResubmit($(this))" href="index.php?sec=gmodules&sec2=godmode/modules/manage_network_templates'.'&export_profile='.$row['id_np'].'">'.html_print_image('images/csv.png', true, ['title' => __('Export to CSV'), 'class' => 'invert_filter']).'</a>';
array_push($table->data, $data);
}

View File

@ -1055,7 +1055,7 @@ switch ($action) {
]
);
$data[2] .= '</a>';
$data[3] = '<a href="'.ui_get_full_url(false, false, false, false).'ajax.php?page='.$config['homedir'].'/operation/reporting/reporting_xml&id='.$report['id_report'].'">';
$data[3] = '<a onclick="blockResubmit($(this))" href="'.ui_get_full_url(false, false, false, false).'ajax.php?page='.$config['homedir'].'/operation/reporting/reporting_xml&id='.$report['id_report'].'">';
$data[3] .= html_print_image(
'images/xml.png',
true,

View File

@ -141,8 +141,9 @@ class Diagnostics extends Wizard
'images/pdf.png',
true,
[
'title' => __('Export to PDF'),
'class' => 'invert_filter',
'title' => __('Export to PDF'),
'class' => 'invert_filter',
'onclick' => 'blockResubmit($(this))',
]
);
$header_buttons = [

View File

@ -506,6 +506,7 @@ class ModuleTemplates extends HTML
header('Content-Disposition: attachment; filename='.preg_replace('/\s/', '_', $fileName).'.csv');
header('Pragma: no-cache');
header('Expires: 0');
setDownloadCookieToken();
// Clean up output buffering
while (@ob_end_clean()) {
@ -931,7 +932,7 @@ class ModuleTemplates extends HTML
]
);
$data[3] = '<a href="'.$this->baseUrl.'&action=delete&id_np='.$row['id_np'].'" onclick="if (!confirm(\''.__('Are you sure?').'\')) return false;">'.html_print_image('images/cross.png', true, ['title' => __('Delete'), 'class' => 'invert_filter']).'</a>';
$data[3] .= '<a href="'.$this->baseUrl.'&action=export&id_np='.$row['id_np'].'">'.html_print_image('images/csv.png', true, ['title' => __('Export to CSV'), 'class' => 'invert_filter']).'</a>';
$data[3] .= '<a href="'.$this->baseUrl.'&action=export&id_np='.$row['id_np'].'" onclick="blockResubmit($(this))">'.html_print_image('images/csv.png', true, ['title' => __('Export to CSV'), 'class' => 'invert_filter']).'</a>';
array_push($table->data, $data);
}

View File

@ -6269,3 +6269,24 @@ function arrayOutputSorting($sort, $sortField)
}
};
}
/**
* Get dowload started cookie from js and set ready cokkie for download ready comntrol.
*
* @return
*/
function setDownloadCookieToken()
{
$download_cookie = get_cookie('downloadToken', false);
if ($download_cookie === false) {
return;
} else {
setcookie(
'downloadReady',
$download_cookie,
(time() + 15),
'/'
);
}
}

View File

@ -46,6 +46,8 @@ function reporting_xml_get_report($report, $filename, $return=false)
// Download if marked to download.
if ($filename !== false) {
// Cookie for download control.
setDownloadCookieToken();
header('Content-Type: application/xml; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$filename.'.xml"');
}

View File

@ -3540,6 +3540,11 @@ function ui_print_datatable(array $parameters)
titleAttr: "'.__('Export current page to CSV').'",
title: "export_'.$parameters['id'].'_current_page_'.date('Y-m-d').'",
fieldSeparator: "'.$config['csv_divider'].'",
action: function ( e, dt, node, config ) {
blockResubmit(node);
// Call the default csvHtml5 action method to create the CSV file
$.fn.dataTable.ext.buttons.csvHtml5.action.call(this, e, dt, node, config);
},
exportOptions : {
modifier : {
// DataTables core
@ -3547,7 +3552,7 @@ function ui_print_datatable(array $parameters)
page : "All",
search : "applied"
}'.$export_columns.'
}
},
}
] : [],
lengthMenu: '.json_encode($pagination_options).',
@ -3671,6 +3676,16 @@ function ui_print_datatable(array $parameters)
$js .= '$(".datatables_thead_tr").css("height", 0);';
}
if (isset($parameters['csv']) === true) {
$js."'$('#".$table_id."').on( 'buttons-processing', function ( e, indicator ) {
if ( indicator ) {
console.log('a');
}
else {
console.log('b');
}";
}
$js .= '});';
$js .= '</script>';

View File

@ -51,6 +51,9 @@ $default_filename = 'data_exported - '.date($config['date_format']);
$filename = (string) get_parameter('filename', $default_filename);
$filename = io_safe_output($filename);
// Set cookie for download control.
setDownloadCookieToken();
/*
* $data = array(
* 'head' => array(<column>,<column>,...,<column>),

View File

@ -2716,6 +2716,7 @@ function pandoraFlotArea(
$("#menu_export_csv_" + graph_id).click(function(e) {
e.preventDefault();
blockResubmit($(this));
plot.exportDataCSV();
var es_firefox =
navigator.userAgent.toLowerCase().indexOf("firefox") > -1;

File diff suppressed because one or more lines are too long

View File

@ -456,8 +456,7 @@ function load_modal(settings) {
// Function that shows a dialog box to confirm closures of generic manners.
// The modal id is random.
// eslint-disable-next-line no-unused-vars
function confirmDialog(settings) {
var randomStr = uniqId();
function confirmDialog(settings, idDialog = uniqId()) {
var hideOkButton = "";
var hideCancelButton = "";
@ -487,11 +486,11 @@ function confirmDialog(settings) {
if (typeof settings.message == "function") {
$("body").append(
'<div id="confirm_' + randomStr + '">' + settings.message() + "</div>"
'<div id="confirm_' + idDialog + '">' + settings.message() + "</div>"
);
} else {
$("body").append(
'<div id="confirm_' + randomStr + '">' + settings.message + "</div>"
'<div id="confirm_' + idDialog + '">' + settings.message + "</div>"
);
}
@ -542,8 +541,8 @@ function confirmDialog(settings) {
buttons.unshift(newButton);
}
$("#confirm_" + randomStr);
$("#confirm_" + randomStr)
$("#confirm_" + idDialog);
$("#confirm_" + idDialog)
.dialog({
open: settings.open,
title: settings.title,
@ -763,3 +762,75 @@ function getGroupIcon(id_group, img_container) {
}
});
}
/* Prepare download control */
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2)
return parts
.pop()
.split(";")
.shift();
}
function expireCookie(cName) {
document.cookie =
encodeURIComponent(cName) +
"=deleted; expires=" +
new Date(0).toUTCString();
}
function setCursor(buttonStyle, button) {
button.css("cursor", buttonStyle);
}
function setToken(tokenName, token) {
token = typeof token !== "undefined" ? token : new Date().getTime();
document.cookie = tokenName + "=" + token + ";" + "-1" + ";path=/";
return token;
}
var downloadTimer;
var attempts = 30;
// Prevents double-submits by waiting for a cookie from the server.
function blockResubmit(button) {
var downloadToken = setToken("downloadToken");
setCursor("wait", button);
// Disable butoon to prevent clicking until download is ready.
button.disable();
button.click(false);
//Show dialog.
confirmDialog(
{
title: get_php_value("prepareDownloadTitle"),
message: get_php_value("prepareDownloadMsg"),
hideCancelButton: true
},
"downloadDialog"
);
downloadTimer = setInterval(function() {
var downloadReady = getCookie("downloadReady");
if (downloadToken == downloadReady || attempts == 0) {
unblockSubmit(button);
}
attempts--;
}, 1000);
}
function unblockSubmit(button) {
setCursor("pointer", button);
button.enable();
button.on("click");
clearInterval(downloadTimer);
$("#confirm_downloadDialog").dialog("close");
expireCookie("downloadToken");
expireCookie("downloadReady");
attempts = 30;
}

View File

@ -23,4 +23,8 @@ html_print_div(['id' => 'forced_title_layer', 'class' => 'forced_title_layer', '
set_js_value('absolute_homeurl', ui_get_full_url(false, false, false, false));
set_js_value('homeurl', $config['homeurl']);
set_js_value('homedir', $config['homedir'].'/');
// Prevent double request message.
set_js_value('prepareDownloadTitle', __('Generating content'));
set_js_value('prepareDownloadMsg', __('Generating content, please wait'));
// ======================================================================

View File

@ -86,6 +86,9 @@ if (!empty($module)) {
while (@ob_end_clean()) {
}
// Set cookie for download control.
setDownloadCookieToken();
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=export_'.date('Ymd', $start).'_'.date('Ymd', $end).'.'.$extension);
header('Pragma: no-cache');

View File

@ -85,6 +85,9 @@ if (!empty($module)) {
while (@ob_end_clean()) {
}
// Set cookie for download control.
setDownloadCookieToken();
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=export_'.date('Ymd', $start).'_'.date('Ymd', $end).'.'.$extension);
header('Pragma: no-cache');

View File

@ -402,9 +402,11 @@ ui_require_jquery_file('bgiframe');
switch (type) {
case 'csv':
blockResubmit($(this));
f.action = "operation/agentes/exportdata.csv.php";
break;
case 'excel':
blockResubmit($(this));
f.action = "operation/agentes/exportdata.excel.php";
break;
case 'avg':

View File

@ -1448,7 +1448,7 @@ if ($pure) {
// CSV.
$csv['active'] = false;
$csv['text'] = '<a class="events_link" href="'.ui_get_full_url(false, false, false, false).'operation/events/export_csv.php?'.($filter_b64 ?? '').'">'.html_print_image(
$csv['text'] = '<a class="events_link" onclick="blockResubmit($(this))" href="'.ui_get_full_url(false, false, false, false).'operation/events/export_csv.php?'.($filter_b64 ?? '').'">'.html_print_image(
'images/csv.png',
true,
[

View File

@ -150,6 +150,7 @@ $now = date('Y-m-d');
// Download header.
header('Content-type: text/txt');
header('Content-Disposition: attachment; filename="export_events_'.$now.'.csv"');
setDownloadCookieToken();
try {
$fb64 = get_parameter('fb64', null);

View File

@ -111,6 +111,9 @@ $filename = 'tickets_export-'.date('Ymd').'-'.date('His').'.csv';
ob_clean();
// Set cookie for download control.
setDownloadCookieToken();
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);

View File

@ -428,7 +428,7 @@ $integria_incidents_form .= '<div class="float-right mrgn_lft_5px">'.html_print_
__('Export to CSV'),
'csv_export',
false,
"location.href='operation/incidents/integriaims_export_csv.php?tickets_filters=$decode_csv'",
"blockResubmit($(this)); location.href='operation/incidents/integriaims_export_csv.php?tickets_filters=$decode_csv'",
'class="sub next"',
true
).'</div>';

View File

@ -140,7 +140,7 @@ $table->data['1']['2'] .= html_print_submit_button(
__('Export to CSV'),
'export_csv',
false,
'class="sub next"',
'class="sub next" onclick="blockResumit($(this))"',
true
);
@ -221,6 +221,8 @@ if (get_parameter('export_csv')) {
ob_end_clean();
}
// Set cookie for download control.
setDownloadCookieToken();
// Write metadata.
header('Content-type: text/csv;');
header('Content-Disposition: attachment; filename="network_data.csv"');

View File

@ -9478,6 +9478,8 @@ class Mpdf implements \Psr\Log\LoggerAwareInterface
function Output($name = '', $dest = '')
{
$this->logger->debug(sprintf('PDF generated in %.6F seconds', microtime(true) - $this->time0), ['context' => LogContext::STATISTICS]);
// Set cokie token to indicate download is ready.
setDownloadCookieToken();
// Finish document if necessary
if ($this->state < 3) {