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