Translated using Weblate (Italian)
[phpmyadmin.git] / js / server_status_monitor.js
blobc3a0c5389372746e048bbefac5b18f2931838b0a
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 var runtime = {},
3     server_time_diff,
4     server_os,
5     is_superuser,
6     server_db_isLocal,
7     chartSize;
8 AJAX.registerOnload('server_status_monitor.js', function () {
9     var $js_data_form = $('#js_data');
10     server_time_diff  = new Date().getTime() - $js_data_form.find("input[name=server_time]").val();
11     server_os =         $js_data_form.find("input[name=server_os]").val();
12     is_superuser =      $js_data_form.find("input[name=is_superuser]").val();
13     server_db_isLocal = $js_data_form.find("input[name=server_db_isLocal]").val();
14 });
16 /**
17  * Unbind all event handlers before tearing down a page
18  */
19 AJAX.registerTeardown('server_status_monitor.js', function () {
20     $('#emptyDialog').remove();
21     $('#addChartDialog').remove();
22     $('a.popupLink').unbind('click');
23     $('body').unbind('click');
24 });
25 /**
26  * Popup behaviour
27  */
28 AJAX.registerOnload('server_status_monitor.js', function () {
29     $('<div />')
30         .attr('id', 'emptyDialog')
31         .appendTo('#page_content');
32     $('#addChartDialog')
33         .appendTo('#page_content');
35     $('a.popupLink').click(function () {
36         var $link = $(this);
37         $('div.' + $link.attr('href').substr(1))
38             .show()
39             .offset({ top: $link.offset().top + $link.height() + 5, left: $link.offset().left })
40             .addClass('openedPopup');
42         return false;
43     });
44     $('body').click(function (event) {
45         $('div.openedPopup').each(function () {
46             var $cnt = $(this);
47             var pos = $cnt.offset();
48             // Hide if the mouseclick is outside the popupcontent
49             if (event.pageX < pos.left ||
50                 event.pageY < pos.top ||
51                 event.pageX > pos.left + $cnt.outerWidth() ||
52                 event.pageY > pos.top + $cnt.outerHeight()
53             ) {
54                 $cnt.hide().removeClass('openedPopup');
55             }
56         });
57     });
58 });
60 AJAX.registerTeardown('server_status_monitor.js', function () {
61     $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').unbind('click');
62     $('div.popupContent select[name="chartColumns"]').unbind('change');
63     $('div.popupContent select[name="gridChartRefresh"]').unbind('change');
64     $('a[href="#addNewChart"]').unbind('click');
65     $('a[href="#exportMonitorConfig"]').unbind('click');
66     $('a[href="#importMonitorConfig"]').unbind('click');
67     $('a[href="#clearMonitorConfig"]').unbind('click');
68     $('a[href="#pauseCharts"]').unbind('click');
69     $('a[href="#monitorInstructionsDialog"]').unbind('click');
70     $('input[name="chartType"]').unbind('click');
71     $('input[name="useDivisor"]').unbind('click');
72     $('input[name="useUnit"]').unbind('click');
73     $('select[name="varChartList"]').unbind('click');
74     $('a[href="#kibDivisor"]').unbind('click');
75     $('a[href="#mibDivisor"]').unbind('click');
76     $('a[href="#submitClearSeries"]').unbind('click');
77     $('a[href="#submitAddSeries"]').unbind('click');
78     // $("input#variableInput").destroy();
79     $('#chartPreset').unbind('click');
80     $('#chartStatusVar').unbind('click');
81     destroyGrid();
82 });
84 AJAX.registerOnload('server_status_monitor.js', function () {
85     // Show tab links
86     $('div.tabLinks').show();
87     $('#loadingMonitorIcon').remove();
88     // Codemirror is loaded on demand so we might need to initialize it
89     if (! codemirror_editor) {
90         var $elm = $('#sqlquery');
91         if ($elm.length > 0 && typeof CodeMirror != 'undefined') {
92             codemirror_editor = CodeMirror.fromTextArea(
93                 $elm[0],
94                 {
95                     lineNumbers: true,
96                     matchBrackets: true,
97                     indentUnit: 4,
98                     mode: "text/x-mysql",
99                     lineWrapping: true
100                 }
101             );
102         }
103     }
104     // Timepicker is loaded on demand so we need to initialize
105     // datetime fields from the 'load log' dialog
106     $('#logAnalyseDialog .datetimefield').each(function () {
107         PMA_addDatepicker($(this));
108     });
110     /**** Monitor charting implementation ****/
111     /* Saves the previous ajax response for differential values */
112     var oldChartData = null;
113     // Holds about to be created chart
114     var newChart = null;
115     var chartSpacing;
117     // Whenever the monitor object (runtime.charts) or the settings object
118     // (monitorSettings) changes in a way incompatible to the previous version,
119     // increase this number. It will reset the users monitor and settings object
120     // in his localStorage to the default configuration
121     var monitorProtocolVersion = '1.0';
123     // Runtime parameter of the monitor, is being fully set in initGrid()
124     runtime = {
125         // Holds all visible charts in the grid
126         charts: null,
127         // Stores the timeout handler so it can be cleared
128         refreshTimeout: null,
129         // Stores the GET request to refresh the charts
130         refreshRequest: null,
131         // Chart auto increment
132         chartAI: 0,
133         // To play/pause the monitor
134         redrawCharts: false,
135         // Object that contains a list of nodes that need to be retrieved
136         // from the server for chart updates
137         dataList: [],
138         // Current max points per chart (needed for auto calculation)
139         gridMaxPoints: 20,
140         // displayed time frame
141         xmin: -1,
142         xmax: -1
143     };
144     var monitorSettings = null;
146     var defaultMonitorSettings = {
147         columns: 3,
148         chartSize: { width: 295, height: 250 },
149         // Max points in each chart. Settings it to 'auto' sets
150         // gridMaxPoints to (chartwidth - 40) / 12
151         gridMaxPoints: 'auto',
152         /* Refresh rate of all grid charts in ms */
153         gridRefresh: 5000
154     };
156     // Allows drag and drop rearrange and print/edit icons on charts
157     var editMode = false;
159     /* List of preconfigured charts that the user may select */
160     var presetCharts = {
161         // Query cache efficiency
162         'qce': {
163             title: PMA_messages.strQueryCacheEfficiency,
164             series: [ {
165                 label: PMA_messages.strQueryCacheEfficiency
166             } ],
167             nodes: [ {
168                 dataPoints: [{type: 'statusvar', name: 'Qcache_hits'}, {type: 'statusvar', name: 'Com_select'}],
169                 transformFn: 'qce'
170             } ],
171             maxYLabel: 0
172         },
173         // Query cache usage
174         'qcu': {
175             title: PMA_messages.strQueryCacheUsage,
176             series: [ {
177                 label: PMA_messages.strQueryCacheUsed
178             } ],
179             nodes: [ {
180                 dataPoints: [{type: 'statusvar', name: 'Qcache_free_memory'}, {type: 'servervar', name: 'query_cache_size'}],
181                 transformFn: 'qcu'
182             } ],
183             maxYLabel: 0
184         }
185     };
187     // time span selection
188     var selectionTimeDiff = [];
189     var selectionStartX, selectionStartY, selectionEndX, selectionEndY;
190     var drawTimeSpan = false;
192     // chart tooltip
193     var tooltipBox;
195     /* Add OS specific system info charts to the preset chart list */
196     switch (server_os) {
197     case 'WINNT':
198         $.extend(presetCharts, {
199             'cpu': {
200                 title: PMA_messages.strSystemCPUUsage,
201                 series: [ {
202                     label: PMA_messages.strAverageLoad
203                 } ],
204                 nodes: [ {
205                     dataPoints: [{ type: 'cpu', name: 'loadavg'}]
206                 } ],
207                 maxYLabel: 100
208             },
210             'memory': {
211                 title: PMA_messages.strSystemMemory,
212                 series: [ {
213                     label: PMA_messages.strTotalMemory,
214                     fill: true
215                 }, {
216                     dataType: 'memory',
217                     label: PMA_messages.strUsedMemory,
218                     fill: true
219                 } ],
220                 nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 },
221                         { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }
222                 ],
223                 maxYLabel: 0
224             },
226             'swap': {
227                 title: PMA_messages.strSystemSwap,
228                 series: [ {
229                     label: PMA_messages.strTotalSwap,
230                     fill: true
231                 }, {
232                     label: PMA_messages.strUsedSwap,
233                     fill: true
234                 } ],
235                 nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }]},
236                         { dataPoints: [{ type: 'memory', name: 'SwapUsed' }]}
237                 ],
238                 maxYLabel: 0
239             }
240         });
241         break;
243     case 'Linux':
244         $.extend(presetCharts, {
245             'cpu': {
246                 title: PMA_messages.strSystemCPUUsage,
247                 series: [ {
248                     label: PMA_messages.strAverageLoad
249                 } ],
250                 nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux'}],
251                 maxYLabel: 0
252             },
253             'memory': {
254                 title: PMA_messages.strSystemMemory,
255                 series: [
256                     { label: PMA_messages.strBufferedMemory, fill: true},
257                     { label: PMA_messages.strUsedMemory, fill: true},
258                     { label: PMA_messages.strCachedMemory, fill: true},
259                     { label: PMA_messages.strFreeMemory, fill: true}
260                 ],
261                 nodes: [
262                     { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 },
263                     { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
264                     { dataPoints: [{ type: 'memory', name: 'Cached' }],  valueDivisor: 1024 },
265                     { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
266                 ],
267                 maxYLabel: 0
268             },
269             'swap': {
270                 title: PMA_messages.strSystemSwap,
271                 series: [
272                     { label: PMA_messages.strCachedSwap, fill: true},
273                     { label: PMA_messages.strUsedSwap, fill: true},
274                     { label: PMA_messages.strFreeSwap, fill: true}
275                 ],
276                 nodes: [
277                     { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 },
278                     { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
279                     { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
280                 ],
281                 maxYLabel: 0
282             }
283         });
284         break;
286     case 'SunOS':
287         $.extend(presetCharts, {
288             'cpu': {
289                 title: PMA_messages.strSystemCPUUsage,
290                 series: [ {
291                     label: PMA_messages.strAverageLoad
292                 } ],
293                 nodes: [ {
294                     dataPoints: [{ type: 'cpu', name: 'loadavg'}]
295                 } ],
296                 maxYLabel: 0
297             },
298             'memory': {
299                 title: PMA_messages.strSystemMemory,
300                 series: [
301                     { label: PMA_messages.strUsedMemory, fill: true },
302                     { label: PMA_messages.strFreeMemory, fill: true }
303                 ],
304                 nodes: [
305                     { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
306                     { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
307                 ],
308                 maxYLabel: 0
309             },
310             'swap': {
311                 title: PMA_messages.strSystemSwap,
312                 series: [
313                     { label: PMA_messages.strUsedSwap, fill: true },
314                     { label: PMA_messages.strFreeSwap, fill: true }
315                 ],
316                 nodes: [
317                     { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
318                     { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
319                 ],
320                 maxYLabel: 0
321             }
322         });
323         break;
324     }
326     // Default setting for the chart grid
327     var defaultChartGrid = {
328         'c0': {
329             title: PMA_messages.strQuestions,
330             series: [
331                 {label: PMA_messages.strQuestions}
332             ],
333             nodes: [
334                 {dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' }
335             ],
336             maxYLabel: 0
337         },
338         'c1': {
339             title: PMA_messages.strChartConnectionsTitle,
340             series: [
341                 {label: PMA_messages.strConnections},
342                 {label: PMA_messages.strProcesses}
343             ],
344             nodes: [
345                 {dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' },
346                 {dataPoints: [{ type: 'proc', name: 'processes' }] }
347             ],
348             maxYLabel: 0
349         },
350         'c2': {
351             title: PMA_messages.strTraffic,
352             series: [
353                 {label: PMA_messages.strBytesSent},
354                 {label: PMA_messages.strBytesReceived}
355             ],
356             nodes: [
357                 {dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 },
358                 {dataPoints: [{ type: 'statusvar', name: 'Bytes_received' }], display: 'differential', valueDivisor: 1024 }
359             ],
360             maxYLabel: 0
361         }
362     };
364     // Server is localhost => We can add cpu/memory/swap to the default chart
365     if (server_db_isLocal) {
366         defaultChartGrid['c3'] = presetCharts['cpu'];
367         defaultChartGrid['c4'] = presetCharts['memory'];
368         defaultChartGrid['c5'] = presetCharts['swap'];
369     }
371     $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').click(function (event) {
372         event.preventDefault();
373         editMode = !editMode;
374         if ($(this).attr('href') == '#endChartEditMode') {
375             editMode = false;
376         }
378         $('a[href="#endChartEditMode"]').toggle(editMode);
380         if (editMode) {
381             // Close the settings popup
382             $('div.popupContent').hide().removeClass('openedPopup');
384             $("#chartGrid").sortableTable({
385                 ignoreRect: {
386                     top: 8,
387                     left: chartSize.width - 63,
388                     width: 54,
389                     height: 24
390                 }
391             });
393         } else {
394             $("#chartGrid").sortableTable('destroy');
395         }
396         saveMonitor(); // Save settings
397         return false;
398     });
400     // global settings
401     $('div.popupContent select[name="chartColumns"]').change(function () {
402         monitorSettings.columns = parseInt(this.value, 10);
404         calculateChartSize();
405         // Empty cells should keep their size so you can drop onto them
406         $('#chartGrid tr td').css('width', chartSize.width + 'px');
407         $('#chartGrid .monitorChart').css({
408             width: chartSize.width + 'px',
409             height: chartSize.height + 'px'
410         });
412         /* Reorder all charts that it fills all column cells */
413         var numColumns;
414         var $tr = $('#chartGrid tr:first');
415         var row = 0;
416         while ($tr.length !== 0) {
417             numColumns = 1;
418             // To many cells in one row => put into next row
419             $tr.find('td').each(function () {
420                 if (numColumns > monitorSettings.columns) {
421                     if ($tr.next().length === 0) {
422                         $tr.after('<tr></tr>');
423                     }
424                     $tr.next().prepend($(this));
425                 }
426                 numColumns++;
427             });
429             // To little cells in one row => for each cell to little,
430             // move all cells backwards by 1
431             if ($tr.next().length > 0) {
432                 var cnt = monitorSettings.columns - $tr.find('td').length;
433                 for (var i = 0; i < cnt; i++) {
434                     $tr.append($tr.next().find('td:first'));
435                     $tr.nextAll().each(function () {
436                         if ($(this).next().length !== 0) {
437                             $(this).append($(this).next().find('td:first'));
438                         }
439                     });
440                 }
441             }
443             $tr = $tr.next();
444             row++;
445         }
447         if (monitorSettings.gridMaxPoints == 'auto') {
448             runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
449         }
451         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
452         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
454         if (editMode) {
455             $("#chartGrid").sortableTable('refresh');
456         }
458         refreshChartGrid();
459         saveMonitor(); // Save settings
460     });
462     $('div.popupContent select[name="gridChartRefresh"]').change(function () {
463         monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
464         clearTimeout(runtime.refreshTimeout);
466         if (runtime.refreshRequest) {
467             runtime.refreshRequest.abort();
468         }
470         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
471         // fixing chart shift towards left on refresh rate change
472         //runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
473         runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
475         saveMonitor(); // Save settings
476     });
478     $('a[href="#addNewChart"]').click(function (event) {
479         event.preventDefault();
480         var dlgButtons = { };
482         dlgButtons[PMA_messages.strAddChart] = function () {
483             var type = $('input[name="chartType"]:checked').val();
485             if (type == 'preset') {
486                 newChart = presetCharts[$('#addChartDialog select[name="presetCharts"]').prop('value')];
487             } else {
488                 // If user builds his own chart, it's being set/updated
489                 // each time he adds a series
490                 // So here we only warn if he didn't add a series yet
491                 if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
492                     alert(PMA_messages.strAddOneSeriesWarning);
493                     return;
494                 }
495             }
497             newChart.title = $('input[name="chartTitle"]').val();
498             // Add a cloned object to the chart grid
499             addChart($.extend(true, {}, newChart));
501             newChart = null;
503             saveMonitor(); // Save settings
505             $(this).dialog("close");
506         };
508         dlgButtons[PMA_messages.strClose] = function () {
509             newChart = null;
510             $('span#clearSeriesLink').hide();
511             $('#seriesPreview').html('');
512             $(this).dialog("close");
513         };
515         var $presetList = $('#addChartDialog select[name="presetCharts"]');
516         if ($presetList.html().length === 0) {
517             $.each(presetCharts, function (key, value) {
518                 $presetList.append('<option value="' + key + '">' + value.title + '</option>');
519             });
520             $presetList.change(function () {
521                 $('input[name="chartTitle"]').val(
522                     $presetList.find(':selected').text()
523                 );
524                 $('#chartPreset').prop('checked', true);
525             });
526             $('#chartPreset').click(function () {
527                 $('input[name="chartTitle"]').val(
528                     $presetList.find(':selected').text()
529                 );
530             });
531             $('#chartStatusVar').click(function () {
532                 $('input[name="chartTitle"]').val(
533                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
534                 );
535             });
536             $('#chartSeries').change(function () {
537                 $('input[name="chartTitle"]').val(
538                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
539                 );
540             });
541         }
543         $('#addChartDialog').dialog({
544             width: 'auto',
545             height: 'auto',
546             buttons: dlgButtons
547         });
549         $('#addChartDialog #seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
551         return false;
552     });
554     $('a[href="#exportMonitorConfig"]').click(function (event) {
555         event.preventDefault();
556         var gridCopy = {};
557         $.each(runtime.charts, function (key, elem) {
558             gridCopy[key] = {};
559             gridCopy[key].nodes = elem.nodes;
560             gridCopy[key].settings = elem.settings;
561             gridCopy[key].title = elem.title;
562         });
563         var exportData = {
564             monitorCharts: gridCopy,
565             monitorSettings: monitorSettings
566         };
567         $('<form />', {
568             "class": "disableAjax",
569             method: "post",
570             action: "file_echo.php?" + PMA_commonParams.get('common_query') + "&filename=1",
571             style: "display:none;"
572         })
573         .append(
574             $('<input />', {
575                 type: "hidden",
576                 name: "monitorconfig",
577                 value: JSON.stringify(exportData)
578             })
579         )
580         .appendTo('body')
581         .submit()
582         .remove();
583     });
585     $('a[href="#importMonitorConfig"]').click(function (event) {
586         event.preventDefault();
587         $('#emptyDialog').dialog({title: PMA_messages.strImportDialogTitle});
588         $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form action="file_echo.php?' + PMA_commonParams.get('common_query') + '&import=1" method="post" enctype="multipart/form-data">' +
589             '<input type="file" name="file"> <input type="hidden" name="import" value="1"> </form>');
591         var dlgBtns = {};
593         dlgBtns[PMA_messages.strImport] = function () {
594             var $iframe, $form;
595             $('body').append($iframe = $('<iframe id="monitorConfigUpload" style="display:none;"></iframe>'));
596             var d = $iframe[0].contentWindow.document;
597             d.open();
598             d.close();
599             mew = d;
601             $iframe.load(function () {
602                 var json;
604                 // Try loading config
605                 try {
606                     var data = $('body', $('iframe#monitorConfigUpload')[0].contentWindow.document).html();
607                     // Chrome wraps around '<pre style="word-wrap: break-word; white-space: pre-wrap;">' to any text content -.-
608                     json = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
609                 } catch (err) {
610                     alert(PMA_messages.strFailedParsingConfig);
611                     $('#emptyDialog').dialog('close');
612                     return;
613                 }
615                 // Basic check, is this a monitor config json?
616                 if (!json || ! json.monitorCharts || ! json.monitorCharts) {
617                     alert(PMA_messages.strFailedParsingConfig);
618                     $('#emptyDialog').dialog('close');
619                     return;
620                 }
622                 // If json ok, try applying config
623                 try {
624                     window.localStorage['monitorCharts'] = JSON.stringify(json.monitorCharts);
625                     window.localStorage['monitorSettings'] = JSON.stringify(json.monitorSettings);
626                     rebuildGrid();
627                 } catch (err) {
628                     alert(PMA_messages.strFailedBuildingGrid);
629                     // If an exception is thrown, load default again
630                     window.localStorage.removeItem('monitorCharts');
631                     window.localStorage.removeItem('monitorSettings');
632                     rebuildGrid();
633                 }
635                 $('#emptyDialog').dialog('close');
636             });
638             $("body", d).append($form = $('#emptyDialog').find('form'));
639             $form.submit();
640             $('#emptyDialog').append('<img class="ajaxIcon" src="' + pmaThemeImage + 'ajax_clock_small.gif" alt="">');
641         };
643         dlgBtns[PMA_messages.strCancel] = function () {
644             $(this).dialog('close');
645         };
648         $('#emptyDialog').dialog({
649             width: 'auto',
650             height: 'auto',
651             buttons: dlgBtns
652         });
653     });
655     $('a[href="#clearMonitorConfig"]').click(function (event) {
656         event.preventDefault();
657         window.localStorage.removeItem('monitorCharts');
658         window.localStorage.removeItem('monitorSettings');
659         window.localStorage.removeItem('monitorVersion');
660         $(this).hide();
661         rebuildGrid();
662     });
664     $('a[href="#pauseCharts"]').click(function (event) {
665         event.preventDefault();
666         runtime.redrawCharts = ! runtime.redrawCharts;
667         if (! runtime.redrawCharts) {
668             $(this).html(PMA_getImage('play.png') + ' ' + PMA_messages.strResumeMonitor);
669         } else {
670             $(this).html(PMA_getImage('pause.png') + ' ' + PMA_messages.strPauseMonitor);
671             if (! runtime.charts) {
672                 initGrid();
673                 $('a[href="#settingsPopup"]').show();
674             }
675         }
676         return false;
677     });
679     $('a[href="#monitorInstructionsDialog"]').click(function (event) {
680         event.preventDefault();
682         var $dialog = $('#monitorInstructionsDialog');
684         $dialog.dialog({
685             width: 595,
686             height: 'auto'
687         }).find('img.ajaxIcon').show();
689         var loadLogVars = function (getvars) {
690             var vars = { ajax_request: true, logging_vars: true };
691             if (getvars) {
692                 $.extend(vars, getvars);
693             }
695             $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'), vars,
696                 function (data) {
697                     var logVars;
698                     if (data.success === true) {
699                         logVars = data.message;
700                     } else {
701                         return serverResponseError();
702                     }
703                     var icon = PMA_getImage('s_success.png'), msg = '', str = '';
705                     if (logVars['general_log'] == 'ON') {
706                         if (logVars['slow_query_log'] == 'ON') {
707                             msg = PMA_messages.strBothLogOn;
708                         } else {
709                             msg = PMA_messages.strGenLogOn;
710                         }
711                     }
713                     if (msg.length === 0 && logVars['slow_query_log'] == 'ON') {
714                         msg = PMA_messages.strSlowLogOn;
715                     }
717                     if (msg.length === 0) {
718                         icon = PMA_getImage('s_error.png');
719                         msg = PMA_messages.strBothLogOff;
720                     }
722                     str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
723                     str += icon + msg + '<br />';
725                     if (logVars['log_output'] != 'TABLE') {
726                         str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
727                     } else {
728                         str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
729                     }
731                     if (logVars['slow_query_log'] == 'ON') {
732                         if (logVars['long_query_time'] > 2) {
733                             str += PMA_getImage('s_attention.png') + ' ';
734                             str += $.sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars['long_query_time']);
735                             str += '<br />';
736                         }
738                         if (logVars['long_query_time'] < 2) {
739                             str += PMA_getImage('s_success.png') + ' ';
740                             str += $.sprintf(PMA_messages.strLongQueryTimeSet, logVars['long_query_time']);
741                             str += '<br />';
742                         }
743                     }
745                     str += '</div>';
747                     if (is_superuser) {
748                         str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
749                         str += '<div class="smallIndent">';
750                         str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
752                         var varValue = 'TABLE';
753                         if (logVars['log_output'] == 'TABLE') {
754                             varValue = 'FILE';
755                         }
757                         str += '- <a class="set" href="#log_output-' + varValue + '">';
758                         str += $.sprintf(PMA_messages.strSetLogOutput, varValue);
759                         str += ' </a><br />';
761                         if (logVars['general_log'] != 'ON') {
762                             str += '- <a class="set" href="#general_log-ON">';
763                             str += $.sprintf(PMA_messages.strEnableVar, 'general_log');
764                             str += ' </a><br />';
765                         } else {
766                             str += '- <a class="set" href="#general_log-OFF">';
767                             str += $.sprintf(PMA_messages.strDisableVar, 'general_log');
768                             str += ' </a><br />';
769                         }
771                         if (logVars['slow_query_log'] != 'ON') {
772                             str += '- <a class="set" href="#slow_query_log-ON">';
773                             str +=  $.sprintf(PMA_messages.strEnableVar, 'slow_query_log');
774                             str += ' </a><br />';
775                         } else {
776                             str += '- <a class="set" href="#slow_query_log-OFF">';
777                             str +=  $.sprintf(PMA_messages.strDisableVar, 'slow_query_log');
778                             str += ' </a><br />';
779                         }
781                         varValue = 5;
782                         if (logVars['long_query_time'] > 2) {
783                             varValue = 1;
784                         }
786                         str += '- <a class="set" href="#long_query_time-' + varValue + '">';
787                         str += $.sprintf(PMA_messages.setSetLongQueryTime, varValue);
788                         str += ' </a><br />';
790                     } else {
791                         str += PMA_messages.strNoSuperUser + '<br/>';
792                     }
794                     str += '</div>';
796                     $dialog.find('div.monitorUse').toggle(
797                         logVars['log_output'] == 'TABLE' && (logVars['slow_query_log'] == 'ON' || logVars['general_log'] == 'ON')
798                     );
800                     $dialog.find('div.ajaxContent').html(str);
801                     $dialog.find('img.ajaxIcon').hide();
802                     $dialog.find('a.set').click(function () {
803                         var nameValue = $(this).attr('href').split('-');
804                         loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
805                         $dialog.find('img.ajaxIcon').show();
806                     });
807                 }
808             );
809         };
812         loadLogVars();
814         return false;
815     });
817     $('input[name="chartType"]').change(function () {
818         $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
819         var title = $('input[name="chartTitle"]').val();
820         if (title == PMA_messages.strChartTitle ||
821             title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
822         ) {
823             $('input[name="chartTitle"]')
824                 .data('lastRadio', $(this).attr('id'))
825                 .val($('label[for="' + $(this).attr('id') + '"]').text());
826         }
828     });
830     $('input[name="useDivisor"]').change(function () {
831         $('span.divisorInput').toggle(this.checked);
832     });
834     $('input[name="useUnit"]').change(function () {
835         $('span.unitInput').toggle(this.checked);
836     });
838     $('select[name="varChartList"]').change(function () {
839         if (this.selectedIndex !== 0) {
840             $('#variableInput').val(this.value);
841         }
842     });
844     $('a[href="#kibDivisor"]').click(function (event) {
845         event.preventDefault();
846         $('input[name="valueDivisor"]').val(1024);
847         $('input[name="valueUnit"]').val(PMA_messages.strKiB);
848         $('span.unitInput').toggle(true);
849         $('input[name="useUnit"]').prop('checked', true);
850         return false;
851     });
853     $('a[href="#mibDivisor"]').click(function (event) {
854         event.preventDefault();
855         $('input[name="valueDivisor"]').val(1024 * 1024);
856         $('input[name="valueUnit"]').val(PMA_messages.strMiB);
857         $('span.unitInput').toggle(true);
858         $('input[name="useUnit"]').prop('checked', true);
859         return false;
860     });
862     $('a[href="#submitClearSeries"]').click(function (event) {
863         event.preventDefault();
864         $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
865         newChart = null;
866         $('#clearSeriesLink').hide();
867     });
869     $('a[href="#submitAddSeries"]').click(function (event) {
870         event.preventDefault();
871         if ($('#variableInput').val() === "") {
872             return false;
873         }
875         if (newChart === null) {
876             $('#seriesPreview').html('');
878             newChart = {
879                 title: $('input[name="chartTitle"]').val(),
880                 nodes: [],
881                 series: [],
882                 maxYLabel: 0
883             };
884         }
886         var serie = {
887             dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
888             display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
889         };
891         if (serie.dataPoints[0].name == 'Processes') {
892             serie.dataPoints[0].type = 'proc';
893         }
895         if ($('input[name="useDivisor"]').prop('checked')) {
896             serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
897         }
899         if ($('input[name="useUnit"]').prop('checked')) {
900             serie.unit = $('input[name="valueUnit"]').val();
901         }
903         var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
904         str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
905         str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
907         var newSeries = {
908             label: $('#variableInput').val().replace(/_/g, " ")
909         };
910         newChart.series.push(newSeries);
911         $('#seriesPreview').append('- ' + newSeries.label + str + '<br/>');
912         newChart.nodes.push(serie);
913         $('#variableInput').val('');
914         $('input[name="differentialValue"]').prop('checked', true);
915         $('input[name="useDivisor"]').prop('checked', false);
916         $('input[name="useUnit"]').prop('checked', false);
917         $('input[name="useDivisor"]').trigger('change');
918         $('input[name="useUnit"]').trigger('change');
919         $('select[name="varChartList"]').get(0).selectedIndex = 0;
921         $('#clearSeriesLink').show();
923         return false;
924     });
926     $("#variableInput").autocomplete({
927         source: variableNames
928     });
930     /* Initializes the monitor, called only once */
931     function initGrid() {
933         var i;
935         /* Apply default values & config */
936         if (window.localStorage) {
937             if (window.localStorage['monitorCharts']) {
938                 runtime.charts = $.parseJSON(window.localStorage['monitorCharts']);
939             }
940             if (window.localStorage['monitorSettings']) {
941                 monitorSettings = $.parseJSON(window.localStorage['monitorSettings']);
942             }
944             $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
946             if (runtime.charts !== null && monitorProtocolVersion != window.localStorage['monitorVersion']) {
947                 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
948                 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
950                 var dlgBtns = {};
951                 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
953                 $('#emptyDialog').dialog({
954                     width: 400,
955                     buttons: dlgBtns
956                 });
957             }
958         }
960         if (runtime.charts === null) {
961             runtime.charts = defaultChartGrid;
962         }
963         if (monitorSettings === null) {
964             monitorSettings = defaultMonitorSettings;
965         }
967         $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
968         $('select[name="chartColumns"]').val(monitorSettings.columns);
970         if (monitorSettings.gridMaxPoints == 'auto') {
971             runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
972         } else {
973             runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
974         }
976         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
977         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
979         /* Calculate how much spacing there is between each chart */
980         $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
981         chartSpacing = {
982             width: $('#chartGrid td:nth-child(2)').offset().left -
983                 $('#chartGrid td:nth-child(1)').offset().left,
984             height: $('#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top -
985                 $('#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top
986         };
987         $('#chartGrid').html('');
989         /* Add all charts - in correct order */
990         var keys = [];
991         $.each(runtime.charts, function (key, value) {
992             keys.push(key);
993         });
994         keys.sort();
995         for (i = 0; i < keys.length; i++) {
996             addChart(runtime.charts[keys[i]], true);
997         }
999         /* Fill in missing cells */
1000         var numCharts = $('#chartGrid .monitorChart').length;
1001         var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
1002         for (i = 0; i < numMissingCells; i++) {
1003             $('#chartGrid tr:last').append('<td></td>');
1004         }
1006         // Empty cells should keep their size so you can drop onto them
1007         calculateChartSize();
1008         $('#chartGrid tr td').css('width', chartSize.width + 'px');
1010         buildRequiredDataList();
1011         refreshChartGrid();
1012     }
1014     /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1015      * data from each chart and restores it after the monitor is initialized again */
1016     function rebuildGrid() {
1017         var oldData = null;
1018         if (runtime.charts) {
1019             oldData = {};
1020             $.each(runtime.charts, function (key, chartObj) {
1021                 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1022                     oldData[chartObj.nodes[i].dataPoint] = [];
1023                     for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1024                         oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1025                     }
1026                 }
1027             });
1028         }
1030         destroyGrid();
1031         initGrid();
1032     }
1034     /* Calculactes the dynamic chart size that depends on the column width */
1035     function calculateChartSize() {
1036         var panelWidth;
1037         if ($("body").height() > $(window).height()) { // has vertical scroll bar
1038             panelWidth = $('#logTable').innerWidth();
1039         } else {
1040             panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1041         }
1043         var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1044         chartSize = {
1045             width: Math.floor(wdt),
1046             height: Math.floor(0.75 * wdt)
1047         };
1048     }
1050     /* Adds a chart to the chart grid */
1051     function addChart(chartObj, initialize) {
1053         var i;
1054         var settings = {
1055             title: escapeHtml(chartObj.title),
1056             grid: {
1057                 drawBorder: false,
1058                 shadow: false,
1059                 background: 'rgba(0,0,0,0)'
1060             },
1061             axes: {
1062                 xaxis: {
1063                     renderer: $.jqplot.DateAxisRenderer,
1064                     tickOptions: {
1065                         formatString: '%H:%M:%S',
1066                         showGridline: false
1067                     },
1068                     min: runtime.xmin,
1069                     max: runtime.xmax
1070                 },
1071                 yaxis: {
1072                     min: 0,
1073                     max: 100,
1074                     tickInterval: 20
1075                 }
1076             },
1077             seriesDefaults: {
1078                 rendererOptions: {
1079                     smooth: true
1080                 },
1081                 showLine: true,
1082                 lineWidth: 2
1083             },
1084             highlighter: {
1085                 show: true
1086             }
1087         };
1089         if (settings.title === PMA_messages.strSystemCPUUsage ||
1090             settings.title === PMA_messages.strQueryCacheEfficiency
1091         ) {
1092             settings.axes.yaxis.tickOptions = {
1093                 formatString: "%d %%"
1094             };
1095         } else if (settings.title === PMA_messages.strSystemMemory ||
1096             settings.title === PMA_messages.strSystemSwap
1097         ) {
1098             settings.stackSeries = true;
1099             settings.axes.yaxis.tickOptions = {
1100                 formatter: $.jqplot.byteFormatter(2) // MiB
1101             };
1102         } else if (settings.title === PMA_messages.strTraffic) {
1103             settings.axes.yaxis.tickOptions = {
1104                 formatter: $.jqplot.byteFormatter(1) // KiB
1105             };
1106         } else if (settings.title === PMA_messages.strQuestions ||
1107             settings.title === PMA_messages.strConnections
1108         ) {
1109             settings.axes.yaxis.tickOptions = {
1110                 formatter: function (format, val) {
1111                     if (Math.abs(val) >= 1000000) {
1112                         return $.jqplot.sprintf("%.3g M", val / 1000000);
1113                     } else if (Math.abs(val) >= 1000) {
1114                         return $.jqplot.sprintf("%.3g k", val / 1000);
1115                     } else {
1116                         return $.jqplot.sprintf("%d", val);
1117                     }
1118                 }
1119             };
1120         }
1122         settings.series = chartObj.series;
1124         if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1125             var numCharts = $('#chartGrid .monitorChart').length;
1127             if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1128                 $('#chartGrid').append('<tr></tr>');
1129             }
1131             if (!chartSize) {
1132                 calculateChartSize();
1133             }
1134             $('#chartGrid tr:last').append(
1135                 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1136                 '<div class="ui-state-default monitorChart"' +
1137                 ' id="gridchart' + runtime.chartAI + '"' +
1138                 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1139                 '</div></td>'
1140             );
1141         }
1143         // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1144         // also chart won't plot initially with no data and data comes on refreshChartGrid()
1145         var series = [];
1146         for (i in chartObj.series) {
1147             series.push([[0, 0]]);
1148         }
1150         // set Tooltip for each series
1151         for (i in settings.series) {
1152             settings.series[i].highlighter = {
1153                 show: true,
1154                 tooltipContentEditor: function (str, seriesIndex, pointIndex, plot) {
1155                     var j;
1156                     // TODO: move style to theme CSS
1157                     var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1158                         'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1159                     // x value i.e. time
1160                     var timeValue = str.split(",")[0];
1161                     var seriesValue;
1162                     tooltipHtml += 'Time: ' + timeValue;
1163                     tooltipHtml += '<span style="font-weight:bold;">';
1164                     // Add y values to the tooltip per series
1165                     for (j in plot.series) {
1166                         // get y value if present
1167                         if (plot.series[j].data.length > pointIndex) {
1168                             seriesValue = plot.series[j].data[pointIndex][1];
1169                         } else {
1170                             return;
1171                         }
1172                         var seriesLabel = plot.series[j].label;
1173                         var seriesColor = plot.series[j].color;
1174                         // format y value
1175                         if (plot.series[0]._yaxis.tickOptions.formatter) {
1176                             // using formatter function
1177                             seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1178                         } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1179                             // using format string
1180                             seriesValue = $.sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1181                         }
1182                         tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1183                             seriesLabel + ': ' + seriesValue + '</span>';
1184                     }
1185                     tooltipHtml += '</span></div>';
1186                     return tooltipHtml;
1187                 }
1188             };
1189         }
1191         chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1192         // remove [0,0] after plotting
1193         for (i in chartObj.chart.series) {
1194             chartObj.chart.series[i].data.shift();
1195         }
1197         var $legend = $('<div />').css('padding', '0.5em');
1198         for (i in chartObj.chart.series) {
1199             $legend.append(
1200                 $('<div />').append(
1201                     $('<div>').css({
1202                         width: '1em',
1203                         height: '1em',
1204                         background: chartObj.chart.seriesColors[i]
1205                     }).addClass('floatleft')
1206                 ).append(
1207                     $('<div>').text(
1208                         chartObj.chart.series[i].label
1209                     ).addClass('floatleft')
1210                 ).append(
1211                     $('<div class="clearfloat">')
1212                 ).addClass('floatleft')
1213             );
1214         }
1215         $('#gridchart' + runtime.chartAI)
1216             .parent()
1217             .append($legend);
1219         if (initialize !== true) {
1220             runtime.charts['c' + runtime.chartAI] = chartObj;
1221             buildRequiredDataList();
1222         }
1224         // time span selection
1225         $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1226             drawTimeSpan = true;
1227             selectionTimeDiff.push(datapos.xaxis);
1228             if ($('#selection_box').length) {
1229                 $('#selection_box').remove();
1230             }
1231             selectionBox = $('<div id="selection_box" style="z-index:1000;height:250px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
1232             $(document.body).append(selectionBox);
1233             selectionStartX = ev.pageX;
1234             selectionStartY = ev.pageY;
1235             selectionBox
1236                 .attr({id: 'selection_box'})
1237                 .css({
1238                     top: selectionStartY - gridpos.y,
1239                     left: selectionStartX
1240                 })
1241                 .fadeIn();
1242         });
1244         $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1245             if (! drawTimeSpan || editMode) {
1246                 return;
1247             }
1249             selectionTimeDiff.push(datapos.xaxis);
1251             if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1252                 selectionTimeDiff = [];
1253                 return;
1254             }
1255             //get date from timestamp
1256             var min = new Date(Math.ceil(selectionTimeDiff[0]));
1257             var max = new Date(Math.ceil(selectionTimeDiff[1]));
1258             PMA_getLogAnalyseDialog(min, max);
1259             selectionTimeDiff = [];
1260             drawTimeSpan = false;
1261         });
1263         $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1264             if (! drawTimeSpan || editMode) {
1265                 return;
1266             }
1267             if (selectionStartX !== undefined) {
1268                 $('#selection_box')
1269                     .css({
1270                         width: Math.ceil(ev.pageX - selectionStartX)
1271                     })
1272                     .fadeIn();
1273             }
1274         });
1276         $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1277             drawTimeSpan = false;
1278         });
1280         $(document.body).mouseup(function () {
1281             if ($('#selection_box').length) {
1282                 selectionBox.remove();
1283             }
1284         });
1286         // Edit, Print icon only in edit mode
1287         $('#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1289         runtime.chartAI++;
1290     }
1292     function PMA_getLogAnalyseDialog(min, max) {
1293         var $dateStart = $('#logAnalyseDialog input[name="dateStart"]');
1294         var $dateEnd = $('#logAnalyseDialog input[name="dateEnd"]');
1295         $dateStart.prop("readonly", true);
1296         $dateEnd.prop("readonly", true);
1298         var dlgBtns = { };
1300         dlgBtns[PMA_messages.strFromSlowLog] = function () {
1301             loadLog('slow', min, max);
1302             $(this).dialog("close");
1303         };
1305         dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1306             loadLog('general', min, max);
1307             $(this).dialog("close");
1308         };
1310         $('#logAnalyseDialog').dialog({
1311             width: 'auto',
1312             height: 'auto',
1313             buttons: dlgBtns
1314         });
1316         PMA_addDatepicker($dateStart, 'datetime', {
1317             showMillisec: false,
1318             showMicrosec: false,
1319             timeFormat: 'HH:mm:ss'
1320         });
1321         PMA_addDatepicker($dateEnd, 'datetime', {
1322             showMillisec: false,
1323             showMicrosec: false,
1324             timeFormat: 'HH:mm:ss'
1325         });
1326         $('#logAnalyseDialog input[name="dateStart"]').datepicker('setDate', min);
1327         $('#logAnalyseDialog input[name="dateEnd"]').datepicker('setDate', max);
1328     }
1330     function loadLog(type, min, max) {
1331         var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').datepicker('getDate')) || min;
1332         var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').datepicker('getDate')) || max;
1334         loadLogStatistics({
1335             src: type,
1336             start: dateStart,
1337             end: dateEnd,
1338             removeVariables: $('#removeVariables').prop('checked'),
1339             limitTypes: $('#limitTypes').prop('checked')
1340         });
1341     }
1343     /* Called in regular intervalls, this function updates the values of each chart in the grid */
1344     function refreshChartGrid() {
1345         /* Send to server */
1346         runtime.refreshRequest = $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), {
1347             ajax_request: true,
1348             chart_data: 1,
1349             type: 'chartgrid',
1350             requiredData: JSON.stringify(runtime.dataList)
1351         }, function (data) {
1352             var chartData;
1353             if (data.success === true) {
1354                 chartData = data.message;
1355             } else {
1356                 return serverResponseError();
1357             }
1358             var value, i = 0;
1359             var diff;
1360             var total;
1362             /* Update values in each graph */
1363             $.each(runtime.charts, function (orderKey, elem) {
1364                 var key = elem.chartID;
1365                 // If newly added chart, we have no data for it yet
1366                 if (! chartData[key]) {
1367                     return;
1368                 }
1369                 // Draw all series
1370                 total = 0;
1371                 for (var j = 0; j < elem.nodes.length; j++) {
1372                     // Update x-axis
1373                     if (i === 0 && j === 0) {
1374                         if (oldChartData === null) {
1375                             diff = chartData.x - runtime.xmax;
1376                         } else {
1377                             diff = parseInt(chartData.x - oldChartData.x, 10);
1378                         }
1380                         runtime.xmin += diff;
1381                         runtime.xmax += diff;
1382                     }
1384                     //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1385                     /* Calculate y value */
1387                     // If transform function given, use it
1388                     if (elem.nodes[j].transformFn) {
1389                         value = chartValueTransform(
1390                             elem.nodes[j].transformFn,
1391                             chartData[key][j],
1392                             // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1393                             (
1394                                 oldChartData === null ||
1395                                 oldChartData[key] === null ||
1396                                 oldChartData[key] === undefined ? null : oldChartData[key][j]
1397                             )
1398                         );
1400                     // Otherwise use original value and apply differential and divisor if given,
1401                     // in this case we have only one data point per series - located at chartData[key][j][0]
1402                     } else {
1403                         value = parseFloat(chartData[key][j][0].value);
1405                         if (elem.nodes[j].display == 'differential') {
1406                             if (oldChartData === null ||
1407                                 oldChartData[key] === null ||
1408                                 oldChartData[key] === undefined
1409                             ) {
1410                                 continue;
1411                             }
1412                             value -= oldChartData[key][j][0].value;
1413                         }
1415                         if (elem.nodes[j].valueDivisor) {
1416                             value = value / elem.nodes[j].valueDivisor;
1417                         }
1418                     }
1420                     // Set y value, if defined
1421                     if (value !== undefined) {
1422                         elem.chart.series[j].data.push([chartData.x, value]);
1423                         if (value > elem.maxYLabel) {
1424                             elem.maxYLabel = value;
1425                         } else if (elem.maxYLabel === 0) {
1426                             elem.maxYLabel = 0.5;
1427                         }
1428                         // free old data point values and update maxYLabel
1429                         if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1430                             elem.chart.series[j].data[0][0] < runtime.xmin
1431                         ) {
1432                             // check if the next freeable point is highest
1433                             if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1434                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1435                                 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1436                             } else {
1437                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1438                             }
1439                         }
1440                         if (elem.title === PMA_messages.strSystemMemory ||
1441                             elem.title === PMA_messages.strSystemSwap
1442                         ) {
1443                             total += value;
1444                         }
1445                     }
1446                 }
1448                 // update chart options
1449                 // keep ticks number/positioning consistent while refreshrate changes
1450                 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1451                 elem.chart['axes']['xaxis'].ticks = [(runtime.xmax - tickInterval * 4),
1452                     (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1453                     (runtime.xmax - tickInterval), runtime.xmax];
1455                 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1456                     elem.title !== PMA_messages.strQueryCacheEfficiency &&
1457                     elem.title !== PMA_messages.strSystemMemory &&
1458                     elem.title !== PMA_messages.strSystemSwap
1459                 ) {
1460                     elem.chart['axes']['yaxis']['max'] = Math.ceil(elem.maxYLabel * 1.1);
1461                     elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(elem.maxYLabel * 1.1 / 5);
1462                 } else if (elem.title === PMA_messages.strSystemMemory ||
1463                     elem.title === PMA_messages.strSystemSwap
1464                 ) {
1465                     elem.chart['axes']['yaxis']['max'] = Math.ceil(total * 1.1 / 100) * 100;
1466                     elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(total * 1.1 / 5);
1467                 }
1468                 i++;
1470                 if (runtime.redrawCharts) {
1471                     elem.chart.replot();
1472                 }
1473             });
1475             oldChartData = chartData;
1477             runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1478         });
1479     }
1481     /* Function to get highest plotted point's y label, to scale the chart,
1482      * TODO: make jqplot's autoscale:true work here
1483      */
1484     function getMaxYLabel(dataValues) {
1485         var maxY = dataValues[0][1];
1486         $.each(dataValues, function (k, v) {
1487             maxY = (v[1] > maxY) ? v[1] : maxY;
1488         });
1489         return maxY;
1490     }
1492     /* Function that supplies special value transform functions for chart values */
1493     function chartValueTransform(name, cur, prev) {
1494         switch (name) {
1495         case 'cpu-linux':
1496             if (prev === null) {
1497                 return undefined;
1498             }
1499             // cur and prev are datapoint arrays, but containing
1500             // only 1 element for cpu-linux
1501             cur = cur[0];
1502             prev = prev[0];
1504             var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1505             var diff_idle = cur.idle - prev.idle;
1506             return 100 * (diff_total - diff_idle) / diff_total;
1508         // Query cache efficiency (%)
1509         case 'qce':
1510             if (prev === null) {
1511                 return undefined;
1512             }
1513             // cur[0].value is Qcache_hits, cur[1].value is Com_select
1514             var diffQHits = cur[0].value - prev[0].value;
1515             // No NaN please :-)
1516             if (cur[1].value - prev[1].value === 0) {
1517                 return 0;
1518             }
1520             return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1522         // Query cache usage (%)
1523         case 'qcu':
1524             if (cur[1].value === 0) {
1525                 return 0;
1526             }
1527             // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1528             return 100 - cur[0].value / cur[1].value * 100;
1530         }
1531         return undefined;
1532     }
1534     /* Build list of nodes that need to be retrieved from server.
1535      * It creates something like a stripped down version of the runtime.charts object.
1536      */
1537     function buildRequiredDataList() {
1538         runtime.dataList = {};
1539         // Store an own id, because the property name is subject of reordering,
1540         // thus destroying our mapping with runtime.charts <=> runtime.dataList
1541         var chartID = 0;
1542         $.each(runtime.charts, function (key, chart) {
1543             runtime.dataList[chartID] = [];
1544             for (var i = 0, l = chart.nodes.length; i < l; i++) {
1545                 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1546             }
1547             runtime.charts[key].chartID = chartID;
1548             chartID++;
1549         });
1550     }
1552     /* Loads the log table data, generates the table and handles the filters */
1553     function loadLogStatistics(opts) {
1554         var tableStr = '';
1555         var logRequest = null;
1557         if (! opts.removeVariables) {
1558             opts.removeVariables = false;
1559         }
1560         if (! opts.limitTypes) {
1561             opts.limitTypes = false;
1562         }
1564         $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1565         $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1566                                 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1567                                 'ajax_clock_small.gif" alt="">');
1568         var dlgBtns = {};
1570         dlgBtns[PMA_messages.strCancelRequest] = function () {
1571             if (logRequest !== null) {
1572                 logRequest.abort();
1573             }
1575             $(this).dialog("close");
1576         };
1578         $('#emptyDialog').dialog({
1579             width: 'auto',
1580             height: 'auto',
1581             buttons: dlgBtns
1582         });
1585         logRequest = $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'),
1586             {   ajax_request: true,
1587                 log_data: 1,
1588                 type: opts.src,
1589                 time_start: Math.round(opts.start / 1000),
1590                 time_end: Math.round(opts.end / 1000),
1591                 removeVariables: opts.removeVariables,
1592                 limitTypes: opts.limitTypes
1593             },
1594             function (data) {
1595                 var logData;
1596                 var dlgBtns = {};
1597                 if (data.success === true) {
1598                     logData = data.message;
1599                 } else {
1600                     return serverResponseError();
1601                 }
1603                 if (logData.rows.length !== 0) {
1604                     runtime.logDataCols = buildLogTable(logData);
1606                     /* Show some stats in the dialog */
1607                     $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1608                     $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1609                     $.each(logData.sum, function (key, value) {
1610                         key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1611                         if (key == 'Total') {
1612                             key = '<b>' + key + '</b>';
1613                         }
1614                         $('#emptyDialog').append(key + ': ' + value + '<br/>');
1615                     });
1617                     /* Add filter options if more than a bunch of rows there to filter */
1618                     if (logData.numRows > 12) {
1619                         $('#logTable').prepend(
1620                             '<fieldset id="logDataFilter">' +
1621                             '    <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1622                             '    <div class="formelement">' +
1623                             '        <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1624                             '        <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1625                             '    </div>' +
1626                             ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1627                             '    <div class="formelement">' +
1628                             '       <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1629                             '       <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1630                             '   </div' +
1631                             '</fieldset>'
1632                         );
1634                         $('#logTable #noWHEREData').change(function () {
1635                             filterQueries(true);
1636                         });
1638                         if (logData.numRows > 250) {
1639                             $('#logTable #startFilterQueryText').click(filterQueries);
1640                         } else {
1641                             $('#logTable #filterQueryText').keyup(filterQueries);
1642                         }
1644                     }
1646                     dlgBtns[PMA_messages.strJumpToTable] = function () {
1647                         $(this).dialog("close");
1648                         $(document).scrollTop($('#logTable').offset().top);
1649                     };
1651                     $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1653                 } else {
1654                     $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1655                     $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1657                     dlgBtns[PMA_messages.strClose] = function () {
1658                         $(this).dialog("close");
1659                     };
1661                     $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1662                 }
1663             }
1664         );
1666         /* Handles the actions performed when the user uses any of the
1667          * log table filters which are the filter by name and grouping
1668          * with ignoring data in WHERE clauses
1669          *
1670          * @param boolean Should be true when the users enabled or disabled
1671          *                to group queries ignoring data in WHERE clauses
1672         */
1673         function filterQueries(varFilterChange) {
1674             var odd_row = false, cell, textFilter;
1675             var val = $('#logTable #filterQueryText').val();
1677             if (val.length === 0) {
1678                 textFilter = null;
1679             } else {
1680                 textFilter = new RegExp(val, 'i');
1681             }
1683             var rowSum = 0, totalSum = 0, i = 0, q;
1684             var noVars = $('#logTable #noWHEREData').prop('checked');
1685             var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1686             var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1687             var filteredQueries = {}, filteredQueriesLines = {};
1688             var hide = false, rowData;
1689             var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1690             var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1691             var isSlowLog = opts.src == 'slow';
1692             var columnSums = {};
1694             // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1695             var countRow = function (query, row) {
1696                 var cells = row.match(/<td>(.*?)<\/td>/gi);
1697                 if (!columnSums[query]) {
1698                     columnSums[query] = [0, 0, 0, 0];
1699                 }
1701                 // lock_time and query_time and displayed in timespan format
1702                 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1703                 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1704                 // rows_examind and rows_sent are just numbers
1705                 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1706                 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1707             };
1709             // We just assume the sql text is always in the second last column, and that the total count is right of it
1710             $('#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1711                 var $t = $(this);
1712                 // If query is a SELECT and user enabled or disabled to group
1713                 // queries ignoring data in where statements, we
1714                 // need to re-calculate the sums of each row
1715                 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1716                     if (noVars) {
1717                         // Group on => Sum up identical columns, and hide all but 1
1719                         q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1720                         q = q.replace(functionFilter, ' $1(...)');
1722                         // Js does not specify a limit on property name length,
1723                         // so we can abuse it as index :-)
1724                         if (filteredQueries[q]) {
1725                             filteredQueries[q] += parseInt($t.next().text(), 10);
1726                             totalSum += parseInt($t.next().text(), 10);
1727                             hide = true;
1728                         } else {
1729                             filteredQueries[q] = parseInt($t.next().text(), 10);
1730                             filteredQueriesLines[q] = i;
1731                             $t.text(q);
1732                         }
1733                         if (isSlowLog) {
1734                             countRow(q, $t.parent().html());
1735                         }
1737                     } else {
1738                         // Group off: Restore original columns
1740                         rowData = $t.parent().data('query');
1741                         // Restore SQL text
1742                         $t.text(rowData[queryColumnName]);
1743                         // Restore total count
1744                         $t.next().text(rowData[sumColumnName]);
1745                         // Restore slow log columns
1746                         if (isSlowLog) {
1747                             $t.parent().children('td:nth-child(3)').text(rowData['query_time']);
1748                             $t.parent().children('td:nth-child(4)').text(rowData['lock_time']);
1749                             $t.parent().children('td:nth-child(5)').text(rowData['rows_sent']);
1750                             $t.parent().children('td:nth-child(6)').text(rowData['rows_examined']);
1751                         }
1752                     }
1753                 }
1755                 // If not required to be hidden, do we need
1756                 // to hide because of a not matching text filter?
1757                 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1758                     hide = true;
1759                 }
1761                 // Now display or hide this column
1762                 if (hide) {
1763                     $t.parent().css('display', 'none');
1764                 } else {
1765                     totalSum += parseInt($t.next().text(), 10);
1766                     rowSum++;
1768                     odd_row = ! odd_row;
1769                     $t.parent().css('display', '');
1770                     if (odd_row) {
1771                         $t.parent().addClass('odd');
1772                         $t.parent().removeClass('even');
1773                     } else {
1774                         $t.parent().addClass('even');
1775                         $t.parent().removeClass('odd');
1776                     }
1777                 }
1779                 hide = false;
1780                 i++;
1781             });
1783             // We finished summarizing counts => Update count values of all grouped entries
1784             if (varFilterChange) {
1785                 if (noVars) {
1786                     var numCol, row, $table = $('#logTable table tbody');
1787                     $.each(filteredQueriesLines, function (key, value) {
1788                         if (filteredQueries[key] <= 1) {
1789                             return;
1790                         }
1792                         row =  $table.children('tr:nth-child(' + (value + 1) + ')');
1793                         numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1794                         numCol.text(filteredQueries[key]);
1796                         if (isSlowLog) {
1797                             row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1798                             row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1799                             row.children('td:nth-child(5)').text(columnSums[key][2]);
1800                             row.children('td:nth-child(6)').text(columnSums[key][3]);
1801                         }
1802                     });
1803                 }
1805                 $('#logTable table').trigger("update");
1806                 setTimeout(function () {
1807                     $('#logTable table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1808                 }, 0);
1809             }
1811             // Display some stats at the bottom of the table
1812             $('#logTable table tfoot tr')
1813                 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1814                       PMA_messages.strSumRows + ' ' + rowSum + '<span style="float:right">' +
1815                       PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1816         }
1817     }
1819     /* Turns a timespan (12:12:12) into a number */
1820     function timeToSec(timeStr) {
1821         var time = timeStr.split(':');
1822         return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1823     }
1825     /* Turns a number into a timespan (100 into 00:01:40) */
1826     function secToTime(timeInt) {
1827         var hours = Math.floor(timeInt / 3600);
1828         timeInt -= hours * 3600;
1829         var minutes = Math.floor(timeInt / 60);
1830         timeInt -= minutes * 60;
1832         if (hours < 10) {
1833             hours = '0' + hours;
1834         }
1835         if (minutes < 10) {
1836             minutes = '0' + minutes;
1837         }
1838         if (timeInt < 10) {
1839             timeInt = '0' + timeInt;
1840         }
1842         return hours + ':' + minutes + ':' + timeInt;
1843     }
1845     /* Constructs the log table out of the retrieved server data */
1846     function buildLogTable(data) {
1847         var rows = data.rows;
1848         var cols = [];
1849         var $table = $('<table class="sortable"></table>');
1850         var $tBody, $tRow, $tCell;
1852         $('#logTable').html($table);
1854         var formatValue = function (name, value) {
1855             if (name == 'user_host') {
1856                 return value.replace(/(\[.*?\])+/g, '');
1857             }
1858             return value;
1859         };
1861         for (var i = 0, l = rows.length; i < l; i++) {
1862             if (i === 0) {
1863                 $.each(rows[0], function (key, value) {
1864                     cols.push(key);
1865                 });
1866                 $table.append('<thead>' +
1867                               '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1868                               '</thead>'
1869                 );
1871                 $table.append($tBody = $('<tbody></tbody>'));
1872             }
1874             $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1875             var cl = '';
1876             for (var j = 0, ll = cols.length; j < ll; j++) {
1877                 // Assuming the query column is the second last
1878                 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1879                     $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1880                     $tCell.click(openQueryAnalyzer);
1881                 } else {
1882                     $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1883                 }
1885                 $tRow.data('query', rows[i]);
1886             }
1887         }
1889         $table.append('<tfoot>' +
1890                     '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1891                     ' ' + data.numRows + '<span style="float:right">' + PMA_messages.strTotal +
1892                     '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1894         // Append a tooltip to the count column, if there exist one
1895         if ($('#logTable th:last').html() == '#') {
1896             $('#logTable th:last').append('&nbsp;' + PMA_getImage('b_docs.png', '', {'class': 'qroupedQueryInfoIcon'}));
1898             var tooltipContent = PMA_messages.strCountColumnExplanation;
1899             if (groupInserts) {
1900                 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1901             }
1903             PMA_tooltip(
1904                 $('img.qroupedQueryInfoIcon'),
1905                 'img',
1906                 tooltipContent
1907             );
1908         }
1910         $('#logTable table').tablesorter({
1911             sortList: [[cols.length - 1, 1]],
1912             widgets: ['fast-zebra']
1913         });
1915         $('#logTable table thead th')
1916             .append('<img class="icon sortableIcon" src="themes/dot.gif" alt="">');
1918         return cols;
1919     }
1921     /* Opens the query analyzer dialog */
1922     function openQueryAnalyzer() {
1923         var rowData = $(this).parent().data('query');
1924         var query = rowData.argument || rowData.sql_text;
1926         if (codemirror_editor) {
1927             //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1928             //query = PMA_SQLPrettyPrint(query);
1929             codemirror_editor.setValue(query);
1930             // Codemirror is bugged, it doesn't refresh properly sometimes.
1931             // Following lines seem to fix that
1932             setTimeout(function () {
1933                 codemirror_editor.refresh();
1934             }, 50);
1935         }
1936         else {
1937             $('#sqlquery').val(query);
1938         }
1940         var profilingChart = null;
1941         var dlgBtns = {};
1943         dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1944             loadQueryAnalysis(rowData);
1945         };
1946         dlgBtns[PMA_messages.strClose] = function () {
1947             $(this).dialog('close');
1948         };
1950         $('#queryAnalyzerDialog').dialog({
1951             width: 'auto',
1952             height: 'auto',
1953             resizable: false,
1954             buttons: dlgBtns,
1955             close: function () {
1956                 if (profilingChart !== null) {
1957                     profilingChart.destroy();
1958                 }
1959                 $('#queryAnalyzerDialog div.placeHolder').html('');
1960                 if (codemirror_editor) {
1961                     codemirror_editor.setValue('');
1962                 } else {
1963                     $('#sqlquery').val('');
1964                 }
1965             }
1966         });
1967     }
1969     /* Loads and displays the analyzed query data */
1970     function loadQueryAnalysis(rowData) {
1971         var db = rowData.db || '';
1973         $('#queryAnalyzerDialog div.placeHolder').html(
1974             PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1975             pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1977         $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), {
1978             ajax_request: true,
1979             query_analyzer: true,
1980             query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1981             database: db
1982         }, function (data) {
1983             var i;
1984             if (data.success === true) {
1985                 data = data.message;
1986             }
1987             if (data.error) {
1988                 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
1989                     data.error = PMA_messages['strServerLogError'];
1990                 }
1991                 $('#queryAnalyzerDialog div.placeHolder').html('<div class="error">' + data.error + '</div>');
1992                 return;
1993             }
1994             var totalTime = 0;
1995             // Float sux, I'll use table :(
1996             $('#queryAnalyzerDialog div.placeHolder')
1997                 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
1999             var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2000             if (data.explain.length > 1) {
2001                 explain += ' (';
2002                 for (i = 0; i < data.explain.length; i++) {
2003                     if (i > 0) {
2004                         explain += ', ';
2005                     }
2006                     explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2007                 }
2008                 explain += ')';
2009             }
2010             explain += '<p></p>';
2011             for (i = 0, l = data.explain.length; i < l; i++) {
2012                 explain += '<div class="explain-' + i + '"' + (i > 0 ?  'style="display:none;"' : '') + '>';
2013                 $.each(data.explain[i], function (key, value) {
2014                     value = (value === null) ? 'null' : value;
2016                     if (key == 'type' && value.toLowerCase() == 'all') {
2017                         value = '<span class="attention">' + value + '</span>';
2018                     }
2019                     if (key == 'Extra') {
2020                         value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2021                     }
2022                     explain += key + ': ' + value + '<br />';
2023                 });
2024                 explain += '</div>';
2025             }
2027             explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2029             $('#queryAnalyzerDialog div.placeHolder td.explain').append(explain);
2031             $('#queryAnalyzerDialog div.placeHolder a[href*="#showExplain"]').click(function () {
2032                 var id = $(this).attr('href').split('-')[1];
2033                 $(this).parent().find('div[class*="explain"]').hide();
2034                 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2035             });
2037             if (data.profiling) {
2038                 var chartData = [];
2039                 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2040                 var duration;
2041                 var otherTime = 0;
2043                 for (i = 0, l = data.profiling.length; i < l; i++) {
2044                     duration = parseFloat(data.profiling[i].duration);
2046                     totalTime += duration;
2048                     numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2049                 }
2051                 // Only put those values in the pie which are > 2%
2052                 for (i = 0, l = data.profiling.length; i < l; i++) {
2053                     duration = parseFloat(data.profiling[i].duration);
2055                     if (duration / totalTime > 0.02) {
2056                         chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2057                     } else {
2058                         otherTime += duration;
2059                     }
2060                 }
2062                 if (otherTime > 0) {
2063                     chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2064                 }
2066                 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2067                 numberTable += '</tbody></table>';
2069                 $('#queryAnalyzerDialog div.placeHolder td.chart').append(
2070                     '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2071                     '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2072                     numberTable + ' <div id="queryProfiling"></div>');
2074                 $('#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function () {
2075                     $('#queryAnalyzerDialog #queryProfiling').hide();
2076                     $('#queryAnalyzerDialog table.queryNums').show();
2077                     return false;
2078                 });
2080                 $('#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function () {
2081                     $('#queryAnalyzerDialog #queryProfiling').show();
2082                     $('#queryAnalyzerDialog table.queryNums').hide();
2083                     return false;
2084                 });
2086                 profilingChart = PMA_createProfilingChartJqplot(
2087                         'queryProfiling',
2088                         chartData
2089                 );
2091                 //$('#queryProfiling').resizable();
2092             }
2093         });
2094     }
2096     /* Saves the monitor to localstorage */
2097     function saveMonitor() {
2098         var gridCopy = {};
2100         $.each(runtime.charts, function (key, elem) {
2101             gridCopy[key] = {};
2102             gridCopy[key].nodes = elem.nodes;
2103             gridCopy[key].settings = elem.settings;
2104             gridCopy[key].title = elem.title;
2105             gridCopy[key].series = elem.series;
2106             gridCopy[key].maxYLabel = elem.maxYLabel;
2107         });
2109         if (window.localStorage) {
2110             window.localStorage['monitorCharts'] = JSON.stringify(gridCopy);
2111             window.localStorage['monitorSettings'] = JSON.stringify(monitorSettings);
2112             window.localStorage['monitorVersion'] = monitorProtocolVersion;
2113         }
2115         $('a[href="#clearMonitorConfig"]').show();
2116     }
2119 // Run the monitor once loaded
2120 AJAX.registerOnload('server_status_monitor.js', function () {
2121     $('a[href="#pauseCharts"]').trigger('click');
2124 function serverResponseError() {
2125     var btns = {};
2126     btns[PMA_messages.strReloadPage] = function () {
2127         window.location.reload();
2128     };
2129     $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2130     $('#emptyDialog').html(
2131         PMA_getImage('s_attention.png') +
2132         PMA_messages.strInvalidResponseExplanation
2133     );
2134     $('#emptyDialog').dialog({ buttons: btns });
2137 /* Destroys all monitor related resources */
2138 function destroyGrid() {
2139     if (runtime.charts) {
2140         $.each(runtime.charts, function (key, value) {
2141             try {
2142                 value.chart.destroy();
2143             } catch (err) {}
2144         });
2145     }
2147     try {
2148         runtime.refreshRequest.abort();
2149     } catch (err) {}
2150     try {
2151         clearTimeout(runtime.refreshTimeout);
2152     } catch (err) {}
2153     $('#chartGrid').html('');
2154     runtime.charts = null;
2155     runtime.chartAI = 0;
2156     monitorSettings = null; //TODO:this not global variable