Translated using Weblate (Bengali)
[phpmyadmin.git] / js / server_status_monitor.js
blob2f9bbb147c8606319cd0fa087f865449c84b8b75
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').find('.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').find('tr td').css('width', chartSize.width + 'px');
407         $('#chartGrid').find('.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').find('tr:first');
415         var row = 0;
417         var tempManageCols = function () {
418             if (numColumns > monitorSettings.columns) {
419                 if ($tr.next().length === 0) {
420                     $tr.after('<tr></tr>');
421                 }
422                 $tr.next().prepend($(this));
423             }
424             numColumns++;
425         };
427         var tempAddCol = function () {
428             if ($(this).next().length !== 0) {
429                 $(this).append($(this).next().find('td:first'));
430             }
431         };
433         while ($tr.length !== 0) {
434             numColumns = 1;
435             // To many cells in one row => put into next row
436             $tr.find('td').each(tempManageCols);
438             // To little cells in one row => for each cell to little,
439             // move all cells backwards by 1
440             if ($tr.next().length > 0) {
441                 var cnt = monitorSettings.columns - $tr.find('td').length;
442                 for (var i = 0; i < cnt; i++) {
443                     $tr.append($tr.next().find('td:first'));
444                     $tr.nextAll().each(tempAddCol);
445                 }
446             }
448             $tr = $tr.next();
449             row++;
450         }
452         if (monitorSettings.gridMaxPoints == 'auto') {
453             runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
454         }
456         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
457         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
459         if (editMode) {
460             $("#chartGrid").sortableTable('refresh');
461         }
463         refreshChartGrid();
464         saveMonitor(); // Save settings
465     });
467     $('div.popupContent select[name="gridChartRefresh"]').change(function () {
468         monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
469         clearTimeout(runtime.refreshTimeout);
471         if (runtime.refreshRequest) {
472             runtime.refreshRequest.abort();
473         }
475         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
476         // fixing chart shift towards left on refresh rate change
477         //runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
478         runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
480         saveMonitor(); // Save settings
481     });
483     $('a[href="#addNewChart"]').click(function (event) {
484         event.preventDefault();
485         var dlgButtons = { };
487         dlgButtons[PMA_messages.strAddChart] = function () {
488             var type = $('input[name="chartType"]:checked').val();
490             if (type == 'preset') {
491                 newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')];
492             } else {
493                 // If user builds his own chart, it's being set/updated
494                 // each time he adds a series
495                 // So here we only warn if he didn't add a series yet
496                 if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
497                     alert(PMA_messages.strAddOneSeriesWarning);
498                     return;
499                 }
500             }
502             newChart.title = $('input[name="chartTitle"]').val();
503             // Add a cloned object to the chart grid
504             addChart($.extend(true, {}, newChart));
506             newChart = null;
508             saveMonitor(); // Save settings
510             $(this).dialog("close");
511         };
513         dlgButtons[PMA_messages.strClose] = function () {
514             newChart = null;
515             $('span#clearSeriesLink').hide();
516             $('#seriesPreview').html('');
517             $(this).dialog("close");
518         };
520         var $presetList = $('#addChartDialog').find('select[name="presetCharts"]');
521         if ($presetList.html().length === 0) {
522             $.each(presetCharts, function (key, value) {
523                 $presetList.append('<option value="' + key + '">' + value.title + '</option>');
524             });
525             $presetList.change(function () {
526                 $('input[name="chartTitle"]').val(
527                     $presetList.find(':selected').text()
528                 );
529                 $('#chartPreset').prop('checked', true);
530             });
531             $('#chartPreset').click(function () {
532                 $('input[name="chartTitle"]').val(
533                     $presetList.find(':selected').text()
534                 );
535             });
536             $('#chartStatusVar').click(function () {
537                 $('input[name="chartTitle"]').val(
538                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
539                 );
540             });
541             $('#chartSeries').change(function () {
542                 $('input[name="chartTitle"]').val(
543                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
544                 );
545             });
546         }
548         $('#addChartDialog').dialog({
549             width: 'auto',
550             height: 'auto',
551             buttons: dlgButtons
552         });
554         $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
556         return false;
557     });
559     $('a[href="#exportMonitorConfig"]').click(function (event) {
560         event.preventDefault();
561         var gridCopy = {};
562         $.each(runtime.charts, function (key, elem) {
563             gridCopy[key] = {};
564             gridCopy[key].nodes = elem.nodes;
565             gridCopy[key].settings = elem.settings;
566             gridCopy[key].title = elem.title;
567         });
568         var exportData = {
569             monitorCharts: gridCopy,
570             monitorSettings: monitorSettings
571         };
573         var blob = new Blob([JSON.stringify(exportData)], {type: "application/octet-stream"});
574         var url = window.URL.createObjectURL(blob);
575         window.location.href = url;
576         window.URL.revokeObjectURL(url);
577     });
579     $('a[href="#importMonitorConfig"]').click(function (event) {
580         event.preventDefault();
581         $('#emptyDialog').dialog({title: PMA_messages.strImportDialogTitle});
582         $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form>' +
583             '<input type="file" name="file" id="import_file"> </form>');
585         var dlgBtns = {};
587         dlgBtns[PMA_messages.strImport] = function () {
588             var input = $('#emptyDialog').find('#import_file')[0];
589             var reader = new FileReader();
591             reader.onerror = function(event) {
592                 alert(PMA_messages.strFailedParsingConfig + "\n" + event.target.error.code);
593             };
594             reader.onload = function(e) {
596                 var data = e.target.result;
598                 // Try loading config
599                 try {
600                     json = JSON.parse(data);
601                 } catch (err) {
602                     alert(PMA_messages.strFailedParsingConfig);
603                     $('#emptyDialog').dialog('close');
604                     return;
605                 }
607                 // Basic check, is this a monitor config json?
608                 if (!json || ! json.monitorCharts || ! json.monitorCharts) {
609                     alert(PMA_messages.strFailedParsingConfig);
610                     $('#emptyDialog').dialog('close');
611                     return;
612                 }
614                 // If json ok, try applying config
615                 try {
616                     window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts);
617                     window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
618                     rebuildGrid();
619                 } catch (err) {
620                     console.log(err);
621                     alert(PMA_messages.strFailedBuildingGrid);
622                     // If an exception is thrown, load default again
623                     if (isStorageSupported('localStorage')) {
624                         window.localStorage.removeItem('monitorCharts');
625                         window.localStorage.removeItem('monitorSettings');
626                     }
627                     rebuildGrid();
628                 }
630                 $('#emptyDialog').dialog('close');
631             };
632             reader.readAsText(input.files[0]);
633         };
635         dlgBtns[PMA_messages.strCancel] = function () {
636             $(this).dialog('close');
637         };
639         $('#emptyDialog').dialog({
640             width: 'auto',
641             height: 'auto',
642             buttons: dlgBtns
643         });
644     });
646     $('a[href="#clearMonitorConfig"]').click(function (event) {
647         event.preventDefault();
648         if (isStorageSupported('localStorage')) {
649             window.localStorage.removeItem('monitorCharts');
650             window.localStorage.removeItem('monitorSettings');
651             window.localStorage.removeItem('monitorVersion');
652         }
653         $(this).hide();
654         rebuildGrid();
655     });
657     $('a[href="#pauseCharts"]').click(function (event) {
658         event.preventDefault();
659         runtime.redrawCharts = ! runtime.redrawCharts;
660         if (! runtime.redrawCharts) {
661             $(this).html(PMA_getImage('play.png') + PMA_messages.strResumeMonitor);
662         } else {
663             $(this).html(PMA_getImage('pause.png') + PMA_messages.strPauseMonitor);
664             if (! runtime.charts) {
665                 initGrid();
666                 $('a[href="#settingsPopup"]').show();
667             }
668         }
669         return false;
670     });
672     $('a[href="#monitorInstructionsDialog"]').click(function (event) {
673         event.preventDefault();
675         var $dialog = $('#monitorInstructionsDialog');
677         $dialog.dialog({
678             width: 595,
679             height: 'auto'
680         }).find('img.ajaxIcon').show();
682         var loadLogVars = function (getvars) {
683             var vars = { ajax_request: true, logging_vars: true };
684             if (getvars) {
685                 $.extend(vars, getvars);
686             }
688             $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
689                 function (data) {
690                     var logVars;
691                     if (typeof data !== 'undefined' && data.success === true) {
692                         logVars = data.message;
693                     } else {
694                         return serverResponseError();
695                     }
696                     var icon = PMA_getImage('s_success.png'), msg = '', str = '';
698                     if (logVars.general_log == 'ON') {
699                         if (logVars.slow_query_log == 'ON') {
700                             msg = PMA_messages.strBothLogOn;
701                         } else {
702                             msg = PMA_messages.strGenLogOn;
703                         }
704                     }
706                     if (msg.length === 0 && logVars.slow_query_log == 'ON') {
707                         msg = PMA_messages.strSlowLogOn;
708                     }
710                     if (msg.length === 0) {
711                         icon = PMA_getImage('s_error.png');
712                         msg = PMA_messages.strBothLogOff;
713                     }
715                     str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
716                     str += icon + msg + '<br />';
718                     if (logVars.log_output != 'TABLE') {
719                         str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
720                     } else {
721                         str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
722                     }
724                     if (logVars.slow_query_log == 'ON') {
725                         if (logVars.long_query_time > 2) {
726                             str += PMA_getImage('s_attention.png') + ' ';
727                             str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
728                             str += '<br />';
729                         }
731                         if (logVars.long_query_time < 2) {
732                             str += PMA_getImage('s_success.png') + ' ';
733                             str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
734                             str += '<br />';
735                         }
736                     }
738                     str += '</div>';
740                     if (is_superuser) {
741                         str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
742                         str += '<div class="smallIndent">';
743                         str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
745                         var varValue = 'TABLE';
746                         if (logVars.log_output == 'TABLE') {
747                             varValue = 'FILE';
748                         }
750                         str += '- <a class="set" href="#log_output-' + varValue + '">';
751                         str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
752                         str += ' </a><br />';
754                         if (logVars.general_log != 'ON') {
755                             str += '- <a class="set" href="#general_log-ON">';
756                             str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
757                             str += ' </a><br />';
758                         } else {
759                             str += '- <a class="set" href="#general_log-OFF">';
760                             str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
761                             str += ' </a><br />';
762                         }
764                         if (logVars.slow_query_log != 'ON') {
765                             str += '- <a class="set" href="#slow_query_log-ON">';
766                             str +=  PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
767                             str += ' </a><br />';
768                         } else {
769                             str += '- <a class="set" href="#slow_query_log-OFF">';
770                             str +=  PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
771                             str += ' </a><br />';
772                         }
774                         varValue = 5;
775                         if (logVars.long_query_time > 2) {
776                             varValue = 1;
777                         }
779                         str += '- <a class="set" href="#long_query_time-' + varValue + '">';
780                         str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
781                         str += ' </a><br />';
783                     } else {
784                         str += PMA_messages.strNoSuperUser + '<br/>';
785                     }
787                     str += '</div>';
789                     $dialog.find('div.monitorUse').toggle(
790                         logVars.log_output == 'TABLE' && (logVars.slow_query_log == 'ON' || logVars.general_log == 'ON')
791                     );
793                     $dialog.find('div.ajaxContent').html(str);
794                     $dialog.find('img.ajaxIcon').hide();
795                     $dialog.find('a.set').click(function () {
796                         var nameValue = $(this).attr('href').split('-');
797                         loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
798                         $dialog.find('img.ajaxIcon').show();
799                     });
800                 }
801             );
802         };
805         loadLogVars();
807         return false;
808     });
810     $('input[name="chartType"]').change(function () {
811         $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
812         var title = $('input[name="chartTitle"]').val();
813         if (title == PMA_messages.strChartTitle ||
814             title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
815         ) {
816             $('input[name="chartTitle"]')
817                 .data('lastRadio', $(this).attr('id'))
818                 .val($('label[for="' + $(this).attr('id') + '"]').text());
819         }
821     });
823     $('input[name="useDivisor"]').change(function () {
824         $('span.divisorInput').toggle(this.checked);
825     });
827     $('input[name="useUnit"]').change(function () {
828         $('span.unitInput').toggle(this.checked);
829     });
831     $('select[name="varChartList"]').change(function () {
832         if (this.selectedIndex !== 0) {
833             $('#variableInput').val(this.value);
834         }
835     });
837     $('a[href="#kibDivisor"]').click(function (event) {
838         event.preventDefault();
839         $('input[name="valueDivisor"]').val(1024);
840         $('input[name="valueUnit"]').val(PMA_messages.strKiB);
841         $('span.unitInput').toggle(true);
842         $('input[name="useUnit"]').prop('checked', true);
843         return false;
844     });
846     $('a[href="#mibDivisor"]').click(function (event) {
847         event.preventDefault();
848         $('input[name="valueDivisor"]').val(1024 * 1024);
849         $('input[name="valueUnit"]').val(PMA_messages.strMiB);
850         $('span.unitInput').toggle(true);
851         $('input[name="useUnit"]').prop('checked', true);
852         return false;
853     });
855     $('a[href="#submitClearSeries"]').click(function (event) {
856         event.preventDefault();
857         $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
858         newChart = null;
859         $('#clearSeriesLink').hide();
860     });
862     $('a[href="#submitAddSeries"]').click(function (event) {
863         event.preventDefault();
864         if ($('#variableInput').val() === "") {
865             return false;
866         }
868         if (newChart === null) {
869             $('#seriesPreview').html('');
871             newChart = {
872                 title: $('input[name="chartTitle"]').val(),
873                 nodes: [],
874                 series: [],
875                 maxYLabel: 0
876             };
877         }
879         var serie = {
880             dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
881             display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
882         };
884         if (serie.dataPoints[0].name == 'Processes') {
885             serie.dataPoints[0].type = 'proc';
886         }
888         if ($('input[name="useDivisor"]').prop('checked')) {
889             serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
890         }
892         if ($('input[name="useUnit"]').prop('checked')) {
893             serie.unit = $('input[name="valueUnit"]').val();
894         }
896         var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
897         str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
898         str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
900         var newSeries = {
901             label: $('#variableInput').val().replace(/_/g, " ")
902         };
903         newChart.series.push(newSeries);
904         $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
905         newChart.nodes.push(serie);
906         $('#variableInput').val('');
907         $('input[name="differentialValue"]').prop('checked', true);
908         $('input[name="useDivisor"]').prop('checked', false);
909         $('input[name="useUnit"]').prop('checked', false);
910         $('input[name="useDivisor"]').trigger('change');
911         $('input[name="useUnit"]').trigger('change');
912         $('select[name="varChartList"]').get(0).selectedIndex = 0;
914         $('#clearSeriesLink').show();
916         return false;
917     });
919     $("#variableInput").autocomplete({
920         source: variableNames
921     });
923     /* Initializes the monitor, called only once */
924     function initGrid() {
926         var i;
928         /* Apply default values & config */
929         if (isStorageSupported('localStorage')) {
930             if (typeof window.localStorage.monitorCharts !== 'undefined') {
931                 runtime.charts = JSON.parse(window.localStorage.monitorCharts);
932             }
933             if (typeof window.localStorage.monitorSettings !== 'undefined') {
934                 monitorSettings = JSON.parse(window.localStorage.monitorSettings);
935             }
937             $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
939             if (runtime.charts !== null
940                 && typeof window.localStorage.monitorVersion !== 'undefined'
941                 && monitorProtocolVersion != window.localStorage.monitorVersion
942             ) {
943                 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
944                 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
946                 var dlgBtns = {};
947                 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
949                 $('#emptyDialog').dialog({
950                     width: 400,
951                     buttons: dlgBtns
952                 });
953             }
954         }
956         if (runtime.charts === null) {
957             runtime.charts = defaultChartGrid;
958         }
959         if (monitorSettings === null) {
960             monitorSettings = defaultMonitorSettings;
961         }
963         $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
964         $('select[name="chartColumns"]').val(monitorSettings.columns);
966         if (monitorSettings.gridMaxPoints == 'auto') {
967             runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
968         } else {
969             runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
970         }
972         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
973         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
975         /* Calculate how much spacing there is between each chart */
976         $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
977         chartSpacing = {
978             width: $('#chartGrid').find('td:nth-child(2)').offset().left -
979                 $('#chartGrid').find('td:nth-child(1)').offset().left,
980             height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
981                 $('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top
982         };
983         $('#chartGrid').html('');
985         /* Add all charts - in correct order */
986         var keys = [];
987         $.each(runtime.charts, function (key, value) {
988             keys.push(key);
989         });
990         keys.sort();
991         for (i = 0; i < keys.length; i++) {
992             addChart(runtime.charts[keys[i]], true);
993         }
995         /* Fill in missing cells */
996         var numCharts = $('#chartGrid').find('.monitorChart').length;
997         var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
998         for (i = 0; i < numMissingCells; i++) {
999             $('#chartGrid').find('tr:last').append('<td></td>');
1000         }
1002         // Empty cells should keep their size so you can drop onto them
1003         calculateChartSize();
1004         $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
1006         buildRequiredDataList();
1007         refreshChartGrid();
1008     }
1010     /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1011      * data from each chart and restores it after the monitor is initialized again */
1012     function rebuildGrid() {
1013         var oldData = null;
1014         if (runtime.charts) {
1015             oldData = {};
1016             $.each(runtime.charts, function (key, chartObj) {
1017                 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1018                     oldData[chartObj.nodes[i].dataPoint] = [];
1019                     for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1020                         oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1021                     }
1022                 }
1023             });
1024         }
1026         destroyGrid();
1027         initGrid();
1028     }
1030     /* Calculactes the dynamic chart size that depends on the column width */
1031     function calculateChartSize() {
1032         var panelWidth;
1033         if ($("body").height() > $(window).height()) { // has vertical scroll bar
1034             panelWidth = $('#logTable').innerWidth();
1035         } else {
1036             panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1037         }
1039         var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1040         chartSize = {
1041             width: Math.floor(wdt),
1042             height: Math.floor(0.75 * wdt)
1043         };
1044     }
1046     /* Adds a chart to the chart grid */
1047     function addChart(chartObj, initialize) {
1049         var i;
1050         var settings = {
1051             title: escapeHtml(chartObj.title),
1052             grid: {
1053                 drawBorder: false,
1054                 shadow: false,
1055                 background: 'rgba(0,0,0,0)'
1056             },
1057             axes: {
1058                 xaxis: {
1059                     renderer: $.jqplot.DateAxisRenderer,
1060                     tickOptions: {
1061                         formatString: '%H:%M:%S',
1062                         showGridline: false
1063                     },
1064                     min: runtime.xmin,
1065                     max: runtime.xmax
1066                 },
1067                 yaxis: {
1068                     min: 0,
1069                     max: 100,
1070                     tickInterval: 20
1071                 }
1072             },
1073             seriesDefaults: {
1074                 rendererOptions: {
1075                     smooth: true
1076                 },
1077                 showLine: true,
1078                 lineWidth: 2,
1079                 markerOptions: {
1080                     size: 6
1081                 }
1082             },
1083             highlighter: {
1084                 show: true
1085             }
1086         };
1088         if (settings.title === PMA_messages.strSystemCPUUsage ||
1089             settings.title === PMA_messages.strQueryCacheEfficiency
1090         ) {
1091             settings.axes.yaxis.tickOptions = {
1092                 formatString: "%d %%"
1093             };
1094         } else if (settings.title === PMA_messages.strSystemMemory ||
1095             settings.title === PMA_messages.strSystemSwap
1096         ) {
1097             settings.stackSeries = true;
1098             settings.axes.yaxis.tickOptions = {
1099                 formatter: $.jqplot.byteFormatter(2) // MiB
1100             };
1101         } else if (settings.title === PMA_messages.strTraffic) {
1102             settings.axes.yaxis.tickOptions = {
1103                 formatter: $.jqplot.byteFormatter(1) // KiB
1104             };
1105         } else if (settings.title === PMA_messages.strQuestions ||
1106             settings.title === PMA_messages.strConnections
1107         ) {
1108             settings.axes.yaxis.tickOptions = {
1109                 formatter: function (format, val) {
1110                     if (Math.abs(val) >= 1000000) {
1111                         return $.jqplot.sprintf("%.3g M", val / 1000000);
1112                     } else if (Math.abs(val) >= 1000) {
1113                         return $.jqplot.sprintf("%.3g k", val / 1000);
1114                     } else {
1115                         return $.jqplot.sprintf("%d", val);
1116                     }
1117                 }
1118             };
1119         }
1121         settings.series = chartObj.series;
1123         if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1124             var numCharts = $('#chartGrid').find('.monitorChart').length;
1126             if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1127                 $('#chartGrid').append('<tr></tr>');
1128             }
1130             if (!chartSize) {
1131                 calculateChartSize();
1132             }
1133             $('#chartGrid').find('tr:last').append(
1134                 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1135                 '<div class="ui-state-default monitorChart"' +
1136                 ' id="gridchart' + runtime.chartAI + '"' +
1137                 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1138                 '</div></td>'
1139             );
1140         }
1142         // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1143         // also chart won't plot initially with no data and data comes on refreshChartGrid()
1144         var series = [];
1145         for (i in chartObj.series) {
1146             series.push([[0, 0]]);
1147         }
1149         var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) {
1150             var j;
1151             // TODO: move style to theme CSS
1152             var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1153                 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1154             // x value i.e. time
1155             var timeValue = str.split(",")[0];
1156             var seriesValue;
1157             tooltipHtml += 'Time: ' + timeValue;
1158             tooltipHtml += '<span style="font-weight:bold;">';
1159             // Add y values to the tooltip per series
1160             for (j in plot.series) {
1161                 // get y value if present
1162                 if (plot.series[j].data.length > pointIndex) {
1163                     seriesValue = plot.series[j].data[pointIndex][1];
1164                 } else {
1165                     return;
1166                 }
1167                 var seriesLabel = plot.series[j].label;
1168                 var seriesColor = plot.series[j].color;
1169                 // format y value
1170                 if (plot.series[0]._yaxis.tickOptions.formatter) {
1171                     // using formatter function
1172                     seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1173                 } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1174                     // using format string
1175                     seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1176                 }
1177                 tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1178                     seriesLabel + ': ' + seriesValue + '</span>';
1179             }
1180             tooltipHtml += '</span></div>';
1181             return tooltipHtml;
1182         };
1184         // set Tooltip for each series
1185         for (i in settings.series) {
1186             settings.series[i].highlighter = {
1187                 show: true,
1188                 tooltipContentEditor: tempTooltipContentEditor
1189             };
1190         }
1192         chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1193         // remove [0,0] after plotting
1194         for (i in chartObj.chart.series) {
1195             chartObj.chart.series[i].data.shift();
1196         }
1198         var $legend = $('<div />').css('padding', '0.5em');
1199         for (i in chartObj.chart.series) {
1200             $legend.append(
1201                 $('<div />').append(
1202                     $('<div>').css({
1203                         width: '1em',
1204                         height: '1em',
1205                         background: chartObj.chart.seriesColors[i]
1206                     }).addClass('floatleft')
1207                 ).append(
1208                     $('<div>').text(
1209                         chartObj.chart.series[i].label
1210                     ).addClass('floatleft')
1211                 ).append(
1212                     $('<div class="clearfloat">')
1213                 ).addClass('floatleft')
1214             );
1215         }
1216         $('#gridchart' + runtime.chartAI)
1217             .parent()
1218             .append($legend);
1220         if (initialize !== true) {
1221             runtime.charts['c' + runtime.chartAI] = chartObj;
1222             buildRequiredDataList();
1223         }
1225         // time span selection
1226         $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1227             drawTimeSpan = true;
1228             selectionTimeDiff.push(datapos.xaxis);
1229             if ($('#selection_box').length) {
1230                 $('#selection_box').remove();
1231             }
1232             var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
1233             $(document.body).append(selectionBox);
1234             selectionStartX = ev.pageX;
1235             selectionStartY = ev.pageY;
1236             selectionBox
1237                 .attr({id: 'selection_box'})
1238                 .css({
1239                     top: selectionStartY - gridpos.y,
1240                     left: selectionStartX
1241                 })
1242                 .fadeIn();
1243         });
1245         $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1246             if (! drawTimeSpan || editMode) {
1247                 return;
1248             }
1250             selectionTimeDiff.push(datapos.xaxis);
1252             if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1253                 selectionTimeDiff = [];
1254                 return;
1255             }
1256             //get date from timestamp
1257             var min = new Date(Math.ceil(selectionTimeDiff[0]));
1258             var max = new Date(Math.ceil(selectionTimeDiff[1]));
1259             PMA_getLogAnalyseDialog(min, max);
1260             selectionTimeDiff = [];
1261             drawTimeSpan = false;
1262         });
1264         $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1265             if (! drawTimeSpan || editMode) {
1266                 return;
1267             }
1268             if (selectionStartX !== undefined) {
1269                 $('#selection_box')
1270                     .css({
1271                         width: Math.ceil(ev.pageX - selectionStartX)
1272                     })
1273                     .fadeIn();
1274             }
1275         });
1277         $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1278             drawTimeSpan = false;
1279         });
1281         $(document.body).mouseup(function () {
1282             if ($('#selection_box').length) {
1283                 $('#selection_box').remove();
1284             }
1285         });
1287         // Edit, Print icon only in edit mode
1288         $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1290         runtime.chartAI++;
1291     }
1293     function PMA_getLogAnalyseDialog(min, max) {
1294         var $logAnalyseDialog = $('#logAnalyseDialog');
1295         var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
1296         var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
1297         $dateStart.prop("readonly", true);
1298         $dateEnd.prop("readonly", true);
1300         var dlgBtns = { };
1302         dlgBtns[PMA_messages.strFromSlowLog] = function () {
1303             loadLog('slow', min, max);
1304             $(this).dialog("close");
1305         };
1307         dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1308             loadLog('general', min, max);
1309             $(this).dialog("close");
1310         };
1312         $logAnalyseDialog.dialog({
1313             width: 'auto',
1314             height: 'auto',
1315             buttons: dlgBtns
1316         });
1318         PMA_addDatepicker($dateStart, 'datetime', {
1319             showMillisec: false,
1320             showMicrosec: false,
1321             timeFormat: 'HH:mm:ss'
1322         });
1323         PMA_addDatepicker($dateEnd, 'datetime', {
1324             showMillisec: false,
1325             showMicrosec: false,
1326             timeFormat: 'HH:mm:ss'
1327         });
1328         $dateStart.datepicker('setDate', min);
1329         $dateEnd.datepicker('setDate', max);
1330     }
1332     function loadLog(type, min, max) {
1333         var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
1334         var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
1336         loadLogStatistics({
1337             src: type,
1338             start: dateStart,
1339             end: dateEnd,
1340             removeVariables: $('#removeVariables').prop('checked'),
1341             limitTypes: $('#limitTypes').prop('checked')
1342         });
1343     }
1345     /* Called in regular intervals, this function updates the values of each chart in the grid */
1346     function refreshChartGrid() {
1347         /* Send to server */
1348         runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1349             ajax_request: true,
1350             chart_data: 1,
1351             type: 'chartgrid',
1352             requiredData: JSON.stringify(runtime.dataList),
1353             server: PMA_commonParams.get('server'),
1354             token: PMA_commonParams.get('token')
1355         }, function (data) {
1356             var chartData;
1357             if (typeof data !== 'undefined' && data.success === true) {
1358                 chartData = data.message;
1359             } else {
1360                 return serverResponseError();
1361             }
1362             var value, i = 0;
1363             var diff;
1364             var total;
1366             /* Update values in each graph */
1367             $.each(runtime.charts, function (orderKey, elem) {
1368                 var key = elem.chartID;
1369                 // If newly added chart, we have no data for it yet
1370                 if (! chartData[key]) {
1371                     return;
1372                 }
1373                 // Draw all series
1374                 total = 0;
1375                 for (var j = 0; j < elem.nodes.length; j++) {
1376                     // Update x-axis
1377                     if (i === 0 && j === 0) {
1378                         if (oldChartData === null) {
1379                             diff = chartData.x - runtime.xmax;
1380                         } else {
1381                             diff = parseInt(chartData.x - oldChartData.x, 10);
1382                         }
1384                         runtime.xmin += diff;
1385                         runtime.xmax += diff;
1386                     }
1388                     //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1389                     /* Calculate y value */
1391                     // If transform function given, use it
1392                     if (elem.nodes[j].transformFn) {
1393                         value = chartValueTransform(
1394                             elem.nodes[j].transformFn,
1395                             chartData[key][j],
1396                             // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1397                             (
1398                                 oldChartData === null ||
1399                                 oldChartData[key] === null ||
1400                                 oldChartData[key] === undefined ? null : oldChartData[key][j]
1401                             )
1402                         );
1404                     // Otherwise use original value and apply differential and divisor if given,
1405                     // in this case we have only one data point per series - located at chartData[key][j][0]
1406                     } else {
1407                         value = parseFloat(chartData[key][j][0].value);
1409                         if (elem.nodes[j].display == 'differential') {
1410                             if (oldChartData === null ||
1411                                 oldChartData[key] === null ||
1412                                 oldChartData[key] === undefined
1413                             ) {
1414                                 continue;
1415                             }
1416                             value -= oldChartData[key][j][0].value;
1417                         }
1419                         if (elem.nodes[j].valueDivisor) {
1420                             value = value / elem.nodes[j].valueDivisor;
1421                         }
1422                     }
1424                     // Set y value, if defined
1425                     if (value !== undefined) {
1426                         elem.chart.series[j].data.push([chartData.x, value]);
1427                         if (value > elem.maxYLabel) {
1428                             elem.maxYLabel = value;
1429                         } else if (elem.maxYLabel === 0) {
1430                             elem.maxYLabel = 0.5;
1431                         }
1432                         // free old data point values and update maxYLabel
1433                         if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1434                             elem.chart.series[j].data[0][0] < runtime.xmin
1435                         ) {
1436                             // check if the next freeable point is highest
1437                             if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1438                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1439                                 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1440                             } else {
1441                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1442                             }
1443                         }
1444                         if (elem.title === PMA_messages.strSystemMemory ||
1445                             elem.title === PMA_messages.strSystemSwap
1446                         ) {
1447                             total += value;
1448                         }
1449                     }
1450                 }
1452                 // update chart options
1453                 // keep ticks number/positioning consistent while refreshrate changes
1454                 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1455                 elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
1456                     (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1457                     (runtime.xmax - tickInterval), runtime.xmax];
1459                 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1460                     elem.title !== PMA_messages.strQueryCacheEfficiency &&
1461                     elem.title !== PMA_messages.strSystemMemory &&
1462                     elem.title !== PMA_messages.strSystemSwap
1463                 ) {
1464                     elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
1465                     elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
1466                 } else if (elem.title === PMA_messages.strSystemMemory ||
1467                     elem.title === PMA_messages.strSystemSwap
1468                 ) {
1469                     elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
1470                     elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
1471                 }
1472                 i++;
1474                 if (runtime.redrawCharts) {
1475                     elem.chart.replot();
1476                 }
1477             });
1479             oldChartData = chartData;
1481             runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1482         });
1483     }
1485     /* Function to get highest plotted point's y label, to scale the chart,
1486      * TODO: make jqplot's autoscale:true work here
1487      */
1488     function getMaxYLabel(dataValues) {
1489         var maxY = dataValues[0][1];
1490         $.each(dataValues, function (k, v) {
1491             maxY = (v[1] > maxY) ? v[1] : maxY;
1492         });
1493         return maxY;
1494     }
1496     /* Function that supplies special value transform functions for chart values */
1497     function chartValueTransform(name, cur, prev) {
1498         switch (name) {
1499         case 'cpu-linux':
1500             if (prev === null) {
1501                 return undefined;
1502             }
1503             // cur and prev are datapoint arrays, but containing
1504             // only 1 element for cpu-linux
1505             cur = cur[0];
1506             prev = prev[0];
1508             var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1509             var diff_idle = cur.idle - prev.idle;
1510             return 100 * (diff_total - diff_idle) / diff_total;
1512         // Query cache efficiency (%)
1513         case 'qce':
1514             if (prev === null) {
1515                 return undefined;
1516             }
1517             // cur[0].value is Qcache_hits, cur[1].value is Com_select
1518             var diffQHits = cur[0].value - prev[0].value;
1519             // No NaN please :-)
1520             if (cur[1].value - prev[1].value === 0) {
1521                 return 0;
1522             }
1524             return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1526         // Query cache usage (%)
1527         case 'qcu':
1528             if (cur[1].value === 0) {
1529                 return 0;
1530             }
1531             // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1532             return 100 - cur[0].value / cur[1].value * 100;
1534         }
1535         return undefined;
1536     }
1538     /* Build list of nodes that need to be retrieved from server.
1539      * It creates something like a stripped down version of the runtime.charts object.
1540      */
1541     function buildRequiredDataList() {
1542         runtime.dataList = {};
1543         // Store an own id, because the property name is subject of reordering,
1544         // thus destroying our mapping with runtime.charts <=> runtime.dataList
1545         var chartID = 0;
1546         $.each(runtime.charts, function (key, chart) {
1547             runtime.dataList[chartID] = [];
1548             for (var i = 0, l = chart.nodes.length; i < l; i++) {
1549                 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1550             }
1551             runtime.charts[key].chartID = chartID;
1552             chartID++;
1553         });
1554     }
1556     /* Loads the log table data, generates the table and handles the filters */
1557     function loadLogStatistics(opts) {
1558         var tableStr = '';
1559         var logRequest = null;
1561         if (! opts.removeVariables) {
1562             opts.removeVariables = false;
1563         }
1564         if (! opts.limitTypes) {
1565             opts.limitTypes = false;
1566         }
1568         $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1569         $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1570                                 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1571                                 'ajax_clock_small.gif" alt="">');
1572         var dlgBtns = {};
1574         dlgBtns[PMA_messages.strCancelRequest] = function () {
1575             if (logRequest !== null) {
1576                 logRequest.abort();
1577             }
1579             $(this).dialog("close");
1580         };
1582         $('#emptyDialog').dialog({
1583             width: 'auto',
1584             height: 'auto',
1585             buttons: dlgBtns
1586         });
1589         logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
1590             {   ajax_request: true,
1591                 log_data: 1,
1592                 type: opts.src,
1593                 time_start: Math.round(opts.start / 1000),
1594                 time_end: Math.round(opts.end / 1000),
1595                 removeVariables: opts.removeVariables,
1596                 limitTypes: opts.limitTypes
1597             },
1598             function (data) {
1599                 var logData;
1600                 var dlgBtns = {};
1601                 if (typeof data !== 'undefined' && data.success === true) {
1602                     logData = data.message;
1603                 } else {
1604                     return serverResponseError();
1605                 }
1607                 if (logData.rows.length === 0) {
1608                     $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1609                     $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1611                     dlgBtns[PMA_messages.strClose] = function () {
1612                         $(this).dialog("close");
1613                     };
1615                     $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1616                     return;
1617                 }
1619                 runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
1621                 /* Show some stats in the dialog */
1622                 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1623                 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1624                 $.each(logData.sum, function (key, value) {
1625                     key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1626                     if (key == 'Total') {
1627                         key = '<b>' + key + '</b>';
1628                     }
1629                     $('#emptyDialog').append(key + ': ' + value + '<br/>');
1630                 });
1632                 /* Add filter options if more than a bunch of rows there to filter */
1633                 if (logData.numRows > 12) {
1634                     $('#logTable').prepend(
1635                         '<fieldset id="logDataFilter">' +
1636                         '    <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1637                         '    <div class="formelement">' +
1638                         '        <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1639                         '        <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1640                         '    </div>' +
1641                         ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1642                         '    <div class="formelement">' +
1643                         '       <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1644                         '       <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1645                         '   </div' +
1646                         '</fieldset>'
1647                     );
1649                     $('#noWHEREData').change(function () {
1650                         filterQueries(true);
1651                     });
1653                     if (logData.numRows > 250) {
1654                         $('#startFilterQueryText').click(filterQueries);
1655                     } else {
1656                         $('#filterQueryText').keyup(filterQueries);
1657                     }
1659                 }
1661                 dlgBtns[PMA_messages.strJumpToTable] = function () {
1662                     $(this).dialog("close");
1663                     $(document).scrollTop($('#logTable').offset().top);
1664                 };
1666                 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1667             }
1668         );
1670         /* Handles the actions performed when the user uses any of the
1671          * log table filters which are the filter by name and grouping
1672          * with ignoring data in WHERE clauses
1673          *
1674          * @param boolean Should be true when the users enabled or disabled
1675          *                to group queries ignoring data in WHERE clauses
1676         */
1677         function filterQueries(varFilterChange) {
1678             var cell, textFilter;
1679             var val = $('#filterQueryText').val();
1681             if (val.length === 0) {
1682                 textFilter = null;
1683             } else {
1684                 try {
1685                     textFilter = new RegExp(val, 'i');
1686                     $('#filterQueryText').removeClass('error');
1687                 } catch(e) {
1688                     if (e instanceof SyntaxError) {
1689                         $('#filterQueryText').addClass('error');
1690                         textFilter = null;
1691                     }
1692                 }
1693             }
1695             var rowSum = 0, totalSum = 0, i = 0, q;
1696             var noVars = $('#noWHEREData').prop('checked');
1697             var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1698             var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1699             var filteredQueries = {}, filteredQueriesLines = {};
1700             var hide = false, rowData;
1701             var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1702             var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1703             var isSlowLog = opts.src == 'slow';
1704             var columnSums = {};
1706             // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1707             var countRow = function (query, row) {
1708                 var cells = row.match(/<td>(.*?)<\/td>/gi);
1709                 if (!columnSums[query]) {
1710                     columnSums[query] = [0, 0, 0, 0];
1711                 }
1713                 // lock_time and query_time and displayed in timespan format
1714                 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1715                 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1716                 // rows_examind and rows_sent are just numbers
1717                 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1718                 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1719             };
1721             // We just assume the sql text is always in the second last column, and that the total count is right of it
1722             $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1723                 var $t = $(this);
1724                 // If query is a SELECT and user enabled or disabled to group
1725                 // queries ignoring data in where statements, we
1726                 // need to re-calculate the sums of each row
1727                 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1728                     if (noVars) {
1729                         // Group on => Sum up identical columns, and hide all but 1
1731                         q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1732                         q = q.replace(functionFilter, ' $1(...)');
1734                         // Js does not specify a limit on property name length,
1735                         // so we can abuse it as index :-)
1736                         if (filteredQueries[q]) {
1737                             filteredQueries[q] += parseInt($t.next().text(), 10);
1738                             totalSum += parseInt($t.next().text(), 10);
1739                             hide = true;
1740                         } else {
1741                             filteredQueries[q] = parseInt($t.next().text(), 10);
1742                             filteredQueriesLines[q] = i;
1743                             $t.text(q);
1744                         }
1745                         if (isSlowLog) {
1746                             countRow(q, $t.parent().html());
1747                         }
1749                     } else {
1750                         // Group off: Restore original columns
1752                         rowData = $t.parent().data('query');
1753                         // Restore SQL text
1754                         $t.text(rowData[queryColumnName]);
1755                         // Restore total count
1756                         $t.next().text(rowData[sumColumnName]);
1757                         // Restore slow log columns
1758                         if (isSlowLog) {
1759                             $t.parent().children('td:nth-child(3)').text(rowData.query_time);
1760                             $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
1761                             $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
1762                             $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
1763                         }
1764                     }
1765                 }
1767                 // If not required to be hidden, do we need
1768                 // to hide because of a not matching text filter?
1769                 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1770                     hide = true;
1771                 }
1773                 // Now display or hide this column
1774                 if (hide) {
1775                     $t.parent().css('display', 'none');
1776                 } else {
1777                     totalSum += parseInt($t.next().text(), 10);
1778                     rowSum++;
1779                     $t.parent().css('display', '');
1780                 }
1782                 hide = false;
1783                 i++;
1784             });
1786             // We finished summarizing counts => Update count values of all grouped entries
1787             if (varFilterChange) {
1788                 if (noVars) {
1789                     var numCol, row, $table = $('#logTable').find('table tbody');
1790                     $.each(filteredQueriesLines, function (key, value) {
1791                         if (filteredQueries[key] <= 1) {
1792                             return;
1793                         }
1795                         row =  $table.children('tr:nth-child(' + (value + 1) + ')');
1796                         numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1797                         numCol.text(filteredQueries[key]);
1799                         if (isSlowLog) {
1800                             row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1801                             row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1802                             row.children('td:nth-child(5)').text(columnSums[key][2]);
1803                             row.children('td:nth-child(6)').text(columnSums[key][3]);
1804                         }
1805                     });
1806                 }
1808                 $('#logTable').find('table').trigger("update");
1809                 setTimeout(function () {
1810                     $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1811                 }, 0);
1812             }
1814             // Display some stats at the bottom of the table
1815             $('#logTable').find('table tfoot tr')
1816                 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1817                       PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
1818                       PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1819         }
1820     }
1822     /* Turns a timespan (12:12:12) into a number */
1823     function timeToSec(timeStr) {
1824         var time = timeStr.split(':');
1825         return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1826     }
1828     /* Turns a number into a timespan (100 into 00:01:40) */
1829     function secToTime(timeInt) {
1830         var hours = Math.floor(timeInt / 3600);
1831         timeInt -= hours * 3600;
1832         var minutes = Math.floor(timeInt / 60);
1833         timeInt -= minutes * 60;
1835         if (hours < 10) {
1836             hours = '0' + hours;
1837         }
1838         if (minutes < 10) {
1839             minutes = '0' + minutes;
1840         }
1841         if (timeInt < 10) {
1842             timeInt = '0' + timeInt;
1843         }
1845         return hours + ':' + minutes + ':' + timeInt;
1846     }
1848     /* Constructs the log table out of the retrieved server data */
1849     function buildLogTable(data, groupInserts) {
1850         var rows = data.rows;
1851         var cols = [];
1852         var $table = $('<table class="sortable"></table>');
1853         var $tBody, $tRow, $tCell;
1855         $('#logTable').html($table);
1857         var tempPushKey = function (key, value) {
1858             cols.push(key);
1859         };
1861         var formatValue = function (name, value) {
1862             if (name == 'user_host') {
1863                 return value.replace(/(\[.*?\])+/g, '');
1864             }
1865             return escapeHtml(value);
1866         };
1868         for (var i = 0, l = rows.length; i < l; i++) {
1869             if (i === 0) {
1870                 $.each(rows[0], tempPushKey);
1871                 $table.append('<thead>' +
1872                               '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1873                               '</thead>'
1874                 );
1876                 $table.append($tBody = $('<tbody></tbody>'));
1877             }
1879             $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1880             var cl = '';
1881             for (var j = 0, ll = cols.length; j < ll; j++) {
1882                 // Assuming the query column is the second last
1883                 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1884                     $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1885                     $tCell.click(openQueryAnalyzer);
1886                 } else {
1887                     $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1888                 }
1890                 $tRow.data('query', rows[i]);
1891             }
1892         }
1894         $table.append('<tfoot>' +
1895                     '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1896                     ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
1897                     '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1899         // Append a tooltip to the count column, if there exist one
1900         if ($('#logTable').find('tr:first th:last').text().indexOf("#") > -1) {
1901             $('#logTable').find('tr:first th:last').append('&nbsp;' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
1903             var tooltipContent = PMA_messages.strCountColumnExplanation;
1904             if (groupInserts) {
1905                 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1906             }
1908             PMA_tooltip(
1909                 $('img.qroupedQueryInfoIcon'),
1910                 'img',
1911                 tooltipContent
1912             );
1913         }
1915         $('#logTable').find('table').tablesorter({
1916             sortList: [[cols.length - 1, 1]],
1917             widgets: ['fast-zebra']
1918         });
1920         $('#logTable').find('table thead th')
1921             .append('<div class="sorticon"></div>');
1923         return cols;
1924     }
1926     /* Opens the query analyzer dialog */
1927     function openQueryAnalyzer() {
1928         var rowData = $(this).parent().data('query');
1929         var query = rowData.argument || rowData.sql_text;
1931         if (codemirror_editor) {
1932             //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1933             //query = PMA_SQLPrettyPrint(query);
1934             codemirror_editor.setValue(query);
1935             // Codemirror is bugged, it doesn't refresh properly sometimes.
1936             // Following lines seem to fix that
1937             setTimeout(function () {
1938                 codemirror_editor.refresh();
1939             }, 50);
1940         }
1941         else {
1942             $('#sqlquery').val(query);
1943         }
1945         var profilingChart = null;
1946         var dlgBtns = {};
1948         dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1949             loadQueryAnalysis(rowData);
1950         };
1951         dlgBtns[PMA_messages.strClose] = function () {
1952             $(this).dialog('close');
1953         };
1955         $('#queryAnalyzerDialog').dialog({
1956             width: 'auto',
1957             height: 'auto',
1958             resizable: false,
1959             buttons: dlgBtns,
1960             close: function () {
1961                 if (profilingChart !== null) {
1962                     profilingChart.destroy();
1963                 }
1964                 $('#queryAnalyzerDialog').find('div.placeHolder').html('');
1965                 if (codemirror_editor) {
1966                     codemirror_editor.setValue('');
1967                 } else {
1968                     $('#sqlquery').val('');
1969                 }
1970             }
1971         });
1972     }
1974     /* Loads and displays the analyzed query data */
1975     function loadQueryAnalysis(rowData) {
1976         var db = rowData.db || '';
1978         $('#queryAnalyzerDialog').find('div.placeHolder').html(
1979             PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1980             pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1982         $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1983             ajax_request: true,
1984             query_analyzer: true,
1985             query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1986             database: db,
1987             server: PMA_commonParams.get('server'),
1988             token: PMA_commonParams.get('token')
1989         }, function (data) {
1990             var i, l;
1991             if (typeof data !== 'undefined' && data.success === true) {
1992                 data = data.message;
1993             }
1994             if (data.error) {
1995                 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
1996                     data.error = PMA_messages.strServerLogError;
1997                 }
1998                 $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
1999                 return;
2000             }
2001             var totalTime = 0;
2002             // Float sux, I'll use table :(
2003             $('#queryAnalyzerDialog').find('div.placeHolder')
2004                 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
2006             var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2007             if (data.explain.length > 1) {
2008                 explain += ' (';
2009                 for (i = 0; i < data.explain.length; i++) {
2010                     if (i > 0) {
2011                         explain += ', ';
2012                     }
2013                     explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2014                 }
2015                 explain += ')';
2016             }
2017             explain += '<p></p>';
2019             var tempExplain = function (key, value) {
2020                 value = (value === null) ? 'null' : escapeHtml(value);
2022                 if (key == 'type' && value.toLowerCase() == 'all') {
2023                     value = '<span class="attention">' + value + '</span>';
2024                 }
2025                 if (key == 'Extra') {
2026                     value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2027                 }
2028                 explain += key + ': ' + value + '<br />';
2029             };
2031             for (i = 0, l = data.explain.length; i < l; i++) {
2032                 explain += '<div class="explain-' + i + '"' + (i > 0 ?  'style="display:none;"' : '') + '>';
2033                 $.each(data.explain[i], tempExplain);
2034                 explain += '</div>';
2035             }
2037             explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2039             $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
2041             $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
2042                 var id = $(this).attr('href').split('-')[1];
2043                 $(this).parent().find('div[class*="explain"]').hide();
2044                 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2045             });
2047             if (data.profiling) {
2048                 var chartData = [];
2049                 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2050                 var duration;
2051                 var otherTime = 0;
2053                 for (i = 0, l = data.profiling.length; i < l; i++) {
2054                     duration = parseFloat(data.profiling[i].duration);
2056                     totalTime += duration;
2058                     numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2059                 }
2061                 // Only put those values in the pie which are > 2%
2062                 for (i = 0, l = data.profiling.length; i < l; i++) {
2063                     duration = parseFloat(data.profiling[i].duration);
2065                     if (duration / totalTime > 0.02) {
2066                         chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2067                     } else {
2068                         otherTime += duration;
2069                     }
2070                 }
2072                 if (otherTime > 0) {
2073                     chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2074                 }
2076                 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2077                 numberTable += '</tbody></table>';
2079                 $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
2080                     '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2081                     '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2082                     numberTable + ' <div id="queryProfiling"></div>');
2084                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
2085                     $('#queryAnalyzerDialog').find('#queryProfiling').hide();
2086                     $('#queryAnalyzerDialog').find('table.queryNums').show();
2087                     return false;
2088                 });
2090                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
2091                     $('#queryAnalyzerDialog').find('#queryProfiling').show();
2092                     $('#queryAnalyzerDialog').find('table.queryNums').hide();
2093                     return false;
2094                 });
2096                 profilingChart = PMA_createProfilingChart(
2097                     'queryProfiling',
2098                     chartData
2099                 );
2101                 //$('#queryProfiling').resizable();
2102             }
2103         });
2104     }
2106     /* Saves the monitor to localstorage */
2107     function saveMonitor() {
2108         var gridCopy = {};
2110         $.each(runtime.charts, function (key, elem) {
2111             gridCopy[key] = {};
2112             gridCopy[key].nodes = elem.nodes;
2113             gridCopy[key].settings = elem.settings;
2114             gridCopy[key].title = elem.title;
2115             gridCopy[key].series = elem.series;
2116             gridCopy[key].maxYLabel = elem.maxYLabel;
2117         });
2119         if (isStorageSupported('localStorage')) {
2120             window.localStorage.monitorCharts = JSON.stringify(gridCopy);
2121             window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
2122             window.localStorage.monitorVersion = monitorProtocolVersion;
2123         }
2125         $('a[href="#clearMonitorConfig"]').show();
2126     }
2129 // Run the monitor once loaded
2130 AJAX.registerOnload('server_status_monitor.js', function () {
2131     $('a[href="#pauseCharts"]').trigger('click');
2134 function serverResponseError() {
2135     var btns = {};
2136     btns[PMA_messages.strReloadPage] = function () {
2137         window.location.reload();
2138     };
2139     $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2140     $('#emptyDialog').html(
2141         PMA_getImage('s_attention.png') +
2142         PMA_messages.strInvalidResponseExplanation
2143     );
2144     $('#emptyDialog').dialog({ buttons: btns });
2147 /* Destroys all monitor related resources */
2148 function destroyGrid() {
2149     if (runtime.charts) {
2150         $.each(runtime.charts, function (key, value) {
2151             try {
2152                 value.chart.destroy();
2153             } catch (err) {}
2154         });
2155     }
2157     try {
2158         runtime.refreshRequest.abort();
2159     } catch (err) {}
2160     try {
2161         clearTimeout(runtime.refreshTimeout);
2162     } catch (err) {}
2163     $('#chartGrid').html('');
2164     runtime.charts = null;
2165     runtime.chartAI = 0;
2166     monitorSettings = null; //TODO:this not global variable