Translated using Weblate (Korean)
[phpmyadmin.git] / js / server_status_monitor.js
blob84b8a3147749a2ae4c875d8b8c61805aed871888
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 var runtime = {},
3     server_time_diff,
4     server_os,
5     is_superuser,
6     server_db_isLocal,
7     chartSize;
8 AJAX.registerOnload('server_status_monitor.js', function () {
9     var $js_data_form = $('#js_data');
10     server_time_diff  = new Date().getTime() - $js_data_form.find("input[name=server_time]").val();
11     server_os =         $js_data_form.find("input[name=server_os]").val();
12     is_superuser =      $js_data_form.find("input[name=is_superuser]").val();
13     server_db_isLocal = $js_data_form.find("input[name=server_db_isLocal]").val();
14 });
16 /**
17  * Unbind all event handlers before tearing down a page
18  */
19 AJAX.registerTeardown('server_status_monitor.js', function () {
20     $('#emptyDialog').remove();
21     $('#addChartDialog').remove();
22     $('a.popupLink').unbind('click');
23     $('body').unbind('click');
24 });
25 /**
26  * Popup behaviour
27  */
28 AJAX.registerOnload('server_status_monitor.js', function () {
29     $('<div />')
30         .attr('id', 'emptyDialog')
31         .appendTo('#page_content');
32     $('#addChartDialog')
33         .appendTo('#page_content');
35     $('a.popupLink').click(function () {
36         var $link = $(this);
37         $('div.' + $link.attr('href').substr(1))
38             .show()
39             .offset({ top: $link.offset().top + $link.height() + 5, left: $link.offset().left })
40             .addClass('openedPopup');
42         return false;
43     });
44     $('body').click(function (event) {
45         $('div.openedPopup').each(function () {
46             var $cnt = $(this);
47             var pos = $cnt.offset();
48             // Hide if the mouseclick is outside the popupcontent
49             if (event.pageX < pos.left ||
50                 event.pageY < pos.top ||
51                 event.pageX > pos.left + $cnt.outerWidth() ||
52                 event.pageY > pos.top + $cnt.outerHeight()
53             ) {
54                 $cnt.hide().removeClass('openedPopup');
55             }
56         });
57     });
58 });
60 AJAX.registerTeardown('server_status_monitor.js', function () {
61     $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').unbind('click');
62     $('div.popupContent select[name="chartColumns"]').unbind('change');
63     $('div.popupContent select[name="gridChartRefresh"]').unbind('change');
64     $('a[href="#addNewChart"]').unbind('click');
65     $('a[href="#exportMonitorConfig"]').unbind('click');
66     $('a[href="#importMonitorConfig"]').unbind('click');
67     $('a[href="#clearMonitorConfig"]').unbind('click');
68     $('a[href="#pauseCharts"]').unbind('click');
69     $('a[href="#monitorInstructionsDialog"]').unbind('click');
70     $('input[name="chartType"]').unbind('click');
71     $('input[name="useDivisor"]').unbind('click');
72     $('input[name="useUnit"]').unbind('click');
73     $('select[name="varChartList"]').unbind('click');
74     $('a[href="#kibDivisor"]').unbind('click');
75     $('a[href="#mibDivisor"]').unbind('click');
76     $('a[href="#submitClearSeries"]').unbind('click');
77     $('a[href="#submitAddSeries"]').unbind('click');
78     // $("input#variableInput").destroy();
79     $('#chartPreset').unbind('click');
80     $('#chartStatusVar').unbind('click');
81     destroyGrid();
82 });
84 AJAX.registerOnload('server_status_monitor.js', function () {
85     // Show tab links
86     $('div.tabLinks').show();
87     $('#loadingMonitorIcon').remove();
88     // Codemirror is loaded on demand so we might need to initialize it
89     if (! codemirror_editor) {
90         var $elm = $('#sqlquery');
91         if ($elm.length > 0 && typeof CodeMirror != 'undefined') {
92             codemirror_editor = CodeMirror.fromTextArea(
93                 $elm[0],
94                 {
95                     lineNumbers: true,
96                     matchBrackets: true,
97                     indentUnit: 4,
98                     mode: "text/x-mysql",
99                     lineWrapping: true
100                 }
101             );
102         }
103     }
104     // Timepicker is loaded on demand so we need to initialize
105     // datetime fields from the 'load log' dialog
106     $('#logAnalyseDialog').find('.datetimefield').each(function () {
107         PMA_addDatepicker($(this));
108     });
110     /**** Monitor charting implementation ****/
111     /* Saves the previous ajax response for differential values */
112     var oldChartData = null;
113     // Holds about to be created chart
114     var newChart = null;
115     var chartSpacing;
117     // Whenever the monitor object (runtime.charts) or the settings object
118     // (monitorSettings) changes in a way incompatible to the previous version,
119     // increase this number. It will reset the users monitor and settings object
120     // in his localStorage to the default configuration
121     var monitorProtocolVersion = '1.0';
123     // Runtime parameter of the monitor, is being fully set in initGrid()
124     runtime = {
125         // Holds all visible charts in the grid
126         charts: null,
127         // Stores the timeout handler so it can be cleared
128         refreshTimeout: null,
129         // Stores the GET request to refresh the charts
130         refreshRequest: null,
131         // Chart auto increment
132         chartAI: 0,
133         // To play/pause the monitor
134         redrawCharts: false,
135         // Object that contains a list of nodes that need to be retrieved
136         // from the server for chart updates
137         dataList: [],
138         // Current max points per chart (needed for auto calculation)
139         gridMaxPoints: 20,
140         // displayed time frame
141         xmin: -1,
142         xmax: -1
143     };
144     var monitorSettings = null;
146     var defaultMonitorSettings = {
147         columns: 3,
148         chartSize: { width: 295, height: 250 },
149         // Max points in each chart. Settings it to 'auto' sets
150         // gridMaxPoints to (chartwidth - 40) / 12
151         gridMaxPoints: 'auto',
152         /* Refresh rate of all grid charts in ms */
153         gridRefresh: 5000
154     };
156     // Allows drag and drop rearrange and print/edit icons on charts
157     var editMode = false;
159     /* List of preconfigured charts that the user may select */
160     var presetCharts = {
161         // Query cache efficiency
162         'qce': {
163             title: PMA_messages.strQueryCacheEfficiency,
164             series: [ {
165                 label: PMA_messages.strQueryCacheEfficiency
166             } ],
167             nodes: [ {
168                 dataPoints: [{type: 'statusvar', name: 'Qcache_hits'}, {type: 'statusvar', name: 'Com_select'}],
169                 transformFn: 'qce'
170             } ],
171             maxYLabel: 0
172         },
173         // Query cache usage
174         'qcu': {
175             title: PMA_messages.strQueryCacheUsage,
176             series: [ {
177                 label: PMA_messages.strQueryCacheUsed
178             } ],
179             nodes: [ {
180                 dataPoints: [{type: 'statusvar', name: 'Qcache_free_memory'}, {type: 'servervar', name: 'query_cache_size'}],
181                 transformFn: 'qcu'
182             } ],
183             maxYLabel: 0
184         }
185     };
187     // time span selection
188     var selectionTimeDiff = [];
189     var selectionStartX, selectionStartY, selectionEndX, selectionEndY;
190     var drawTimeSpan = false;
192     // chart tooltip
193     var tooltipBox;
195     /* Add OS specific system info charts to the preset chart list */
196     switch (server_os) {
197     case 'WINNT':
198         $.extend(presetCharts, {
199             'cpu': {
200                 title: PMA_messages.strSystemCPUUsage,
201                 series: [ {
202                     label: PMA_messages.strAverageLoad
203                 } ],
204                 nodes: [ {
205                     dataPoints: [{ type: 'cpu', name: 'loadavg'}]
206                 } ],
207                 maxYLabel: 100
208             },
210             'memory': {
211                 title: PMA_messages.strSystemMemory,
212                 series: [ {
213                     label: PMA_messages.strTotalMemory,
214                     fill: true
215                 }, {
216                     dataType: 'memory',
217                     label: PMA_messages.strUsedMemory,
218                     fill: true
219                 } ],
220                 nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 },
221                         { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }
222                 ],
223                 maxYLabel: 0
224             },
226             'swap': {
227                 title: PMA_messages.strSystemSwap,
228                 series: [ {
229                     label: PMA_messages.strTotalSwap,
230                     fill: true
231                 }, {
232                     label: PMA_messages.strUsedSwap,
233                     fill: true
234                 } ],
235                 nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }]},
236                         { dataPoints: [{ type: 'memory', name: 'SwapUsed' }]}
237                 ],
238                 maxYLabel: 0
239             }
240         });
241         break;
243     case 'Linux':
244         $.extend(presetCharts, {
245             'cpu': {
246                 title: PMA_messages.strSystemCPUUsage,
247                 series: [ {
248                     label: PMA_messages.strAverageLoad
249                 } ],
250                 nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux'}],
251                 maxYLabel: 0
252             },
253             'memory': {
254                 title: PMA_messages.strSystemMemory,
255                 series: [
256                     { label: PMA_messages.strBufferedMemory, fill: true},
257                     { label: PMA_messages.strUsedMemory, fill: true},
258                     { label: PMA_messages.strCachedMemory, fill: true},
259                     { label: PMA_messages.strFreeMemory, fill: true}
260                 ],
261                 nodes: [
262                     { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 },
263                     { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
264                     { dataPoints: [{ type: 'memory', name: 'Cached' }],  valueDivisor: 1024 },
265                     { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
266                 ],
267                 maxYLabel: 0
268             },
269             'swap': {
270                 title: PMA_messages.strSystemSwap,
271                 series: [
272                     { label: PMA_messages.strCachedSwap, fill: true},
273                     { label: PMA_messages.strUsedSwap, fill: true},
274                     { label: PMA_messages.strFreeSwap, fill: true}
275                 ],
276                 nodes: [
277                     { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 },
278                     { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
279                     { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
280                 ],
281                 maxYLabel: 0
282             }
283         });
284         break;
286     case 'SunOS':
287         $.extend(presetCharts, {
288             'cpu': {
289                 title: PMA_messages.strSystemCPUUsage,
290                 series: [ {
291                     label: PMA_messages.strAverageLoad
292                 } ],
293                 nodes: [ {
294                     dataPoints: [{ type: 'cpu', name: 'loadavg'}]
295                 } ],
296                 maxYLabel: 0
297             },
298             'memory': {
299                 title: PMA_messages.strSystemMemory,
300                 series: [
301                     { label: PMA_messages.strUsedMemory, fill: true },
302                     { label: PMA_messages.strFreeMemory, fill: true }
303                 ],
304                 nodes: [
305                     { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
306                     { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
307                 ],
308                 maxYLabel: 0
309             },
310             'swap': {
311                 title: PMA_messages.strSystemSwap,
312                 series: [
313                     { label: PMA_messages.strUsedSwap, fill: true },
314                     { label: PMA_messages.strFreeSwap, fill: true }
315                 ],
316                 nodes: [
317                     { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
318                     { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
319                 ],
320                 maxYLabel: 0
321             }
322         });
323         break;
324     }
326     // Default setting for the chart grid
327     var defaultChartGrid = {
328         'c0': {
329             title: PMA_messages.strQuestions,
330             series: [
331                 {label: PMA_messages.strQuestions}
332             ],
333             nodes: [
334                 {dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' }
335             ],
336             maxYLabel: 0
337         },
338         'c1': {
339             title: PMA_messages.strChartConnectionsTitle,
340             series: [
341                 {label: PMA_messages.strConnections},
342                 {label: PMA_messages.strProcesses}
343             ],
344             nodes: [
345                 {dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' },
346                 {dataPoints: [{ type: 'proc', name: 'processes' }] }
347             ],
348             maxYLabel: 0
349         },
350         'c2': {
351             title: PMA_messages.strTraffic,
352             series: [
353                 {label: PMA_messages.strBytesSent},
354                 {label: PMA_messages.strBytesReceived}
355             ],
356             nodes: [
357                 {dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 },
358                 {dataPoints: [{ type: 'statusvar', name: 'Bytes_received' }], display: 'differential', valueDivisor: 1024 }
359             ],
360             maxYLabel: 0
361         }
362     };
364     // Server is localhost => We can add cpu/memory/swap to the default chart
365     if (server_db_isLocal) {
366         defaultChartGrid.c3 = presetCharts.cpu;
367         defaultChartGrid.c4 = presetCharts.memory;
368         defaultChartGrid.c5 = presetCharts.swap;
369     }
371     $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').click(function (event) {
372         event.preventDefault();
373         editMode = !editMode;
374         if ($(this).attr('href') == '#endChartEditMode') {
375             editMode = false;
376         }
378         $('a[href="#endChartEditMode"]').toggle(editMode);
380         if (editMode) {
381             // Close the settings popup
382             $('div.popupContent').hide().removeClass('openedPopup');
384             $("#chartGrid").sortableTable({
385                 ignoreRect: {
386                     top: 8,
387                     left: chartSize.width - 63,
388                     width: 54,
389                     height: 24
390                 }
391             });
393         } else {
394             $("#chartGrid").sortableTable('destroy');
395         }
396         saveMonitor(); // Save settings
397         return false;
398     });
400     // global settings
401     $('div.popupContent select[name="chartColumns"]').change(function () {
402         monitorSettings.columns = parseInt(this.value, 10);
404         calculateChartSize();
405         // Empty cells should keep their size so you can drop onto them
406         $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
407         $('#chartGrid').find('.monitorChart').css({
408             width: chartSize.width + 'px',
409             height: chartSize.height + 'px'
410         });
412         /* Reorder all charts that it fills all column cells */
413         var numColumns;
414         var $tr = $('#chartGrid').find('tr:first');
415         var row = 0;
417         var tempManageCols = function () {
418             if (numColumns > monitorSettings.columns) {
419                 if ($tr.next().length === 0) {
420                     $tr.after('<tr></tr>');
421                 }
422                 $tr.next().prepend($(this));
423             }
424             numColumns++;
425         };
427         var tempAddCol = function () {
428             if ($(this).next().length !== 0) {
429                 $(this).append($(this).next().find('td:first'));
430             }
431         };
433         while ($tr.length !== 0) {
434             numColumns = 1;
435             // To many cells in one row => put into next row
436             $tr.find('td').each(tempManageCols);
438             // To little cells in one row => for each cell to little,
439             // move all cells backwards by 1
440             if ($tr.next().length > 0) {
441                 var cnt = monitorSettings.columns - $tr.find('td').length;
442                 for (var i = 0; i < cnt; i++) {
443                     $tr.append($tr.next().find('td:first'));
444                     $tr.nextAll().each(tempAddCol);
445                 }
446             }
448             $tr = $tr.next();
449             row++;
450         }
452         if (monitorSettings.gridMaxPoints == 'auto') {
453             runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
454         }
456         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
457         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
459         if (editMode) {
460             $("#chartGrid").sortableTable('refresh');
461         }
463         refreshChartGrid();
464         saveMonitor(); // Save settings
465     });
467     $('div.popupContent select[name="gridChartRefresh"]').change(function () {
468         monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
469         clearTimeout(runtime.refreshTimeout);
471         if (runtime.refreshRequest) {
472             runtime.refreshRequest.abort();
473         }
475         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
476         // fixing chart shift towards left on refresh rate change
477         //runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
478         runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
480         saveMonitor(); // Save settings
481     });
483     $('a[href="#addNewChart"]').click(function (event) {
484         event.preventDefault();
485         var dlgButtons = { };
487         dlgButtons[PMA_messages.strAddChart] = function () {
488             var type = $('input[name="chartType"]:checked').val();
490             if (type == 'preset') {
491                 newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')];
492             } else {
493                 // If user builds his own chart, it's being set/updated
494                 // each time he adds a series
495                 // So here we only warn if he didn't add a series yet
496                 if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
497                     alert(PMA_messages.strAddOneSeriesWarning);
498                     return;
499                 }
500             }
502             newChart.title = $('input[name="chartTitle"]').val();
503             // Add a cloned object to the chart grid
504             addChart($.extend(true, {}, newChart));
506             newChart = null;
508             saveMonitor(); // Save settings
510             $(this).dialog("close");
511         };
513         dlgButtons[PMA_messages.strClose] = function () {
514             newChart = null;
515             $('span#clearSeriesLink').hide();
516             $('#seriesPreview').html('');
517             $(this).dialog("close");
518         };
520         var $presetList = $('#addChartDialog').find('select[name="presetCharts"]');
521         if ($presetList.html().length === 0) {
522             $.each(presetCharts, function (key, value) {
523                 $presetList.append('<option value="' + key + '">' + value.title + '</option>');
524             });
525             $presetList.change(function () {
526                 $('input[name="chartTitle"]').val(
527                     $presetList.find(':selected').text()
528                 );
529                 $('#chartPreset').prop('checked', true);
530             });
531             $('#chartPreset').click(function () {
532                 $('input[name="chartTitle"]').val(
533                     $presetList.find(':selected').text()
534                 );
535             });
536             $('#chartStatusVar').click(function () {
537                 $('input[name="chartTitle"]').val(
538                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
539                 );
540             });
541             $('#chartSeries').change(function () {
542                 $('input[name="chartTitle"]').val(
543                     $('#chartSeries').find(':selected').text().replace(/_/g, " ")
544                 );
545             });
546         }
548         $('#addChartDialog').dialog({
549             width: 'auto',
550             height: 'auto',
551             buttons: dlgButtons
552         });
554         $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
556         return false;
557     });
559     $('a[href="#exportMonitorConfig"]').click(function (event) {
560         event.preventDefault();
561         var gridCopy = {};
562         $.each(runtime.charts, function (key, elem) {
563             gridCopy[key] = {};
564             gridCopy[key].nodes = elem.nodes;
565             gridCopy[key].settings = elem.settings;
566             gridCopy[key].title = elem.title;
567         });
568         var exportData = {
569             monitorCharts: gridCopy,
570             monitorSettings: monitorSettings
571         };
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').find('td:nth-child(2)').offset().left -
988                 $('#chartGrid').find('td:nth-child(1)').offset().left,
989             height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
990                 $('#chartGrid').find('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').find('.monitorChart').length;
1006         var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
1007         for (i = 0; i < numMissingCells; i++) {
1008             $('#chartGrid').find('tr:last').append('<td></td>');
1009         }
1011         // Empty cells should keep their size so you can drop onto them
1012         calculateChartSize();
1013         $('#chartGrid').find('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').find('.monitorChart').length;
1135             if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1136                 $('#chartGrid').append('<tr></tr>');
1137             }
1139             if (!chartSize) {
1140                 calculateChartSize();
1141             }
1142             $('#chartGrid').find('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             var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
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                 $('#selection_box').remove();
1293             }
1294         });
1296         // Edit, Print icon only in edit mode
1297         $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1299         runtime.chartAI++;
1300     }
1302     function PMA_getLogAnalyseDialog(min, max) {
1303         var $logAnalyseDialog = $('#logAnalyseDialog');
1304         var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
1305         var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
1306         $dateStart.prop("readonly", true);
1307         $dateEnd.prop("readonly", true);
1309         var dlgBtns = { };
1311         dlgBtns[PMA_messages.strFromSlowLog] = function () {
1312             loadLog('slow', min, max);
1313             $(this).dialog("close");
1314         };
1316         dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1317             loadLog('general', min, max);
1318             $(this).dialog("close");
1319         };
1321         $logAnalyseDialog.dialog({
1322             width: 'auto',
1323             height: 'auto',
1324             buttons: dlgBtns
1325         });
1327         PMA_addDatepicker($dateStart, 'datetime', {
1328             showMillisec: false,
1329             showMicrosec: false,
1330             timeFormat: 'HH:mm:ss'
1331         });
1332         PMA_addDatepicker($dateEnd, 'datetime', {
1333             showMillisec: false,
1334             showMicrosec: false,
1335             timeFormat: 'HH:mm:ss'
1336         });
1337         $dateStart.datepicker('setDate', min);
1338         $dateEnd.datepicker('setDate', max);
1339     }
1341     function loadLog(type, min, max) {
1342         var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
1343         var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
1345         loadLogStatistics({
1346             src: type,
1347             start: dateStart,
1348             end: dateEnd,
1349             removeVariables: $('#removeVariables').prop('checked'),
1350             limitTypes: $('#limitTypes').prop('checked')
1351         });
1352     }
1354     /* Called in regular intervals, this function updates the values of each chart in the grid */
1355     function refreshChartGrid() {
1356         /* Send to server */
1357         runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1358             ajax_request: true,
1359             chart_data: 1,
1360             type: 'chartgrid',
1361             requiredData: JSON.stringify(runtime.dataList)
1362         }, function (data) {
1363             var chartData;
1364             if (typeof data !== 'undefined' && data.success === true) {
1365                 chartData = data.message;
1366             } else {
1367                 return serverResponseError();
1368             }
1369             var value, i = 0;
1370             var diff;
1371             var total;
1373             /* Update values in each graph */
1374             $.each(runtime.charts, function (orderKey, elem) {
1375                 var key = elem.chartID;
1376                 // If newly added chart, we have no data for it yet
1377                 if (! chartData[key]) {
1378                     return;
1379                 }
1380                 // Draw all series
1381                 total = 0;
1382                 for (var j = 0; j < elem.nodes.length; j++) {
1383                     // Update x-axis
1384                     if (i === 0 && j === 0) {
1385                         if (oldChartData === null) {
1386                             diff = chartData.x - runtime.xmax;
1387                         } else {
1388                             diff = parseInt(chartData.x - oldChartData.x, 10);
1389                         }
1391                         runtime.xmin += diff;
1392                         runtime.xmax += diff;
1393                     }
1395                     //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1396                     /* Calculate y value */
1398                     // If transform function given, use it
1399                     if (elem.nodes[j].transformFn) {
1400                         value = chartValueTransform(
1401                             elem.nodes[j].transformFn,
1402                             chartData[key][j],
1403                             // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1404                             (
1405                                 oldChartData === null ||
1406                                 oldChartData[key] === null ||
1407                                 oldChartData[key] === undefined ? null : oldChartData[key][j]
1408                             )
1409                         );
1411                     // Otherwise use original value and apply differential and divisor if given,
1412                     // in this case we have only one data point per series - located at chartData[key][j][0]
1413                     } else {
1414                         value = parseFloat(chartData[key][j][0].value);
1416                         if (elem.nodes[j].display == 'differential') {
1417                             if (oldChartData === null ||
1418                                 oldChartData[key] === null ||
1419                                 oldChartData[key] === undefined
1420                             ) {
1421                                 continue;
1422                             }
1423                             value -= oldChartData[key][j][0].value;
1424                         }
1426                         if (elem.nodes[j].valueDivisor) {
1427                             value = value / elem.nodes[j].valueDivisor;
1428                         }
1429                     }
1431                     // Set y value, if defined
1432                     if (value !== undefined) {
1433                         elem.chart.series[j].data.push([chartData.x, value]);
1434                         if (value > elem.maxYLabel) {
1435                             elem.maxYLabel = value;
1436                         } else if (elem.maxYLabel === 0) {
1437                             elem.maxYLabel = 0.5;
1438                         }
1439                         // free old data point values and update maxYLabel
1440                         if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1441                             elem.chart.series[j].data[0][0] < runtime.xmin
1442                         ) {
1443                             // check if the next freeable point is highest
1444                             if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1445                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1446                                 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1447                             } else {
1448                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1449                             }
1450                         }
1451                         if (elem.title === PMA_messages.strSystemMemory ||
1452                             elem.title === PMA_messages.strSystemSwap
1453                         ) {
1454                             total += value;
1455                         }
1456                     }
1457                 }
1459                 // update chart options
1460                 // keep ticks number/positioning consistent while refreshrate changes
1461                 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1462                 elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
1463                     (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1464                     (runtime.xmax - tickInterval), runtime.xmax];
1466                 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1467                     elem.title !== PMA_messages.strQueryCacheEfficiency &&
1468                     elem.title !== PMA_messages.strSystemMemory &&
1469                     elem.title !== PMA_messages.strSystemSwap
1470                 ) {
1471                     elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
1472                     elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
1473                 } else if (elem.title === PMA_messages.strSystemMemory ||
1474                     elem.title === PMA_messages.strSystemSwap
1475                 ) {
1476                     elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
1477                     elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
1478                 }
1479                 i++;
1481                 if (runtime.redrawCharts) {
1482                     elem.chart.replot();
1483                 }
1484             });
1486             oldChartData = chartData;
1488             runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1489         });
1490     }
1492     /* Function to get highest plotted point's y label, to scale the chart,
1493      * TODO: make jqplot's autoscale:true work here
1494      */
1495     function getMaxYLabel(dataValues) {
1496         var maxY = dataValues[0][1];
1497         $.each(dataValues, function (k, v) {
1498             maxY = (v[1] > maxY) ? v[1] : maxY;
1499         });
1500         return maxY;
1501     }
1503     /* Function that supplies special value transform functions for chart values */
1504     function chartValueTransform(name, cur, prev) {
1505         switch (name) {
1506         case 'cpu-linux':
1507             if (prev === null) {
1508                 return undefined;
1509             }
1510             // cur and prev are datapoint arrays, but containing
1511             // only 1 element for cpu-linux
1512             cur = cur[0];
1513             prev = prev[0];
1515             var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1516             var diff_idle = cur.idle - prev.idle;
1517             return 100 * (diff_total - diff_idle) / diff_total;
1519         // Query cache efficiency (%)
1520         case 'qce':
1521             if (prev === null) {
1522                 return undefined;
1523             }
1524             // cur[0].value is Qcache_hits, cur[1].value is Com_select
1525             var diffQHits = cur[0].value - prev[0].value;
1526             // No NaN please :-)
1527             if (cur[1].value - prev[1].value === 0) {
1528                 return 0;
1529             }
1531             return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1533         // Query cache usage (%)
1534         case 'qcu':
1535             if (cur[1].value === 0) {
1536                 return 0;
1537             }
1538             // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1539             return 100 - cur[0].value / cur[1].value * 100;
1541         }
1542         return undefined;
1543     }
1545     /* Build list of nodes that need to be retrieved from server.
1546      * It creates something like a stripped down version of the runtime.charts object.
1547      */
1548     function buildRequiredDataList() {
1549         runtime.dataList = {};
1550         // Store an own id, because the property name is subject of reordering,
1551         // thus destroying our mapping with runtime.charts <=> runtime.dataList
1552         var chartID = 0;
1553         $.each(runtime.charts, function (key, chart) {
1554             runtime.dataList[chartID] = [];
1555             for (var i = 0, l = chart.nodes.length; i < l; i++) {
1556                 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1557             }
1558             runtime.charts[key].chartID = chartID;
1559             chartID++;
1560         });
1561     }
1563     /* Loads the log table data, generates the table and handles the filters */
1564     function loadLogStatistics(opts) {
1565         var tableStr = '';
1566         var logRequest = null;
1568         if (! opts.removeVariables) {
1569             opts.removeVariables = false;
1570         }
1571         if (! opts.limitTypes) {
1572             opts.limitTypes = false;
1573         }
1575         $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1576         $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1577                                 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1578                                 'ajax_clock_small.gif" alt="">');
1579         var dlgBtns = {};
1581         dlgBtns[PMA_messages.strCancelRequest] = function () {
1582             if (logRequest !== null) {
1583                 logRequest.abort();
1584             }
1586             $(this).dialog("close");
1587         };
1589         $('#emptyDialog').dialog({
1590             width: 'auto',
1591             height: 'auto',
1592             buttons: dlgBtns
1593         });
1596         logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
1597             {   ajax_request: true,
1598                 log_data: 1,
1599                 type: opts.src,
1600                 time_start: Math.round(opts.start / 1000),
1601                 time_end: Math.round(opts.end / 1000),
1602                 removeVariables: opts.removeVariables,
1603                 limitTypes: opts.limitTypes
1604             },
1605             function (data) {
1606                 var logData;
1607                 var dlgBtns = {};
1608                 if (typeof data !== 'undefined' && data.success === true) {
1609                     logData = data.message;
1610                 } else {
1611                     return serverResponseError();
1612                 }
1614                 if (logData.rows.length === 0) {
1615                     $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1616                     $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1618                     dlgBtns[PMA_messages.strClose] = function () {
1619                         $(this).dialog("close");
1620                     };
1622                     $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1623                     return;
1624                 }
1626                 runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
1628                 /* Show some stats in the dialog */
1629                 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1630                 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1631                 $.each(logData.sum, function (key, value) {
1632                     key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1633                     if (key == 'Total') {
1634                         key = '<b>' + key + '</b>';
1635                     }
1636                     $('#emptyDialog').append(key + ': ' + value + '<br/>');
1637                 });
1639                 /* Add filter options if more than a bunch of rows there to filter */
1640                 if (logData.numRows > 12) {
1641                     $('#logTable').prepend(
1642                         '<fieldset id="logDataFilter">' +
1643                         '    <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1644                         '    <div class="formelement">' +
1645                         '        <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1646                         '        <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1647                         '    </div>' +
1648                         ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1649                         '    <div class="formelement">' +
1650                         '       <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1651                         '       <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1652                         '   </div' +
1653                         '</fieldset>'
1654                     );
1656                     $('#noWHEREData').change(function () {
1657                         filterQueries(true);
1658                     });
1660                     if (logData.numRows > 250) {
1661                         $('#startFilterQueryText').click(filterQueries);
1662                     } else {
1663                         $('#filterQueryText').keyup(filterQueries);
1664                     }
1666                 }
1668                 dlgBtns[PMA_messages.strJumpToTable] = function () {
1669                     $(this).dialog("close");
1670                     $(document).scrollTop($('#logTable').offset().top);
1671                 };
1673                 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1674             }
1675         );
1677         /* Handles the actions performed when the user uses any of the
1678          * log table filters which are the filter by name and grouping
1679          * with ignoring data in WHERE clauses
1680          *
1681          * @param boolean Should be true when the users enabled or disabled
1682          *                to group queries ignoring data in WHERE clauses
1683         */
1684         function filterQueries(varFilterChange) {
1685             var odd_row = false, cell, textFilter;
1686             var val = $('#filterQueryText').val();
1688             if (val.length === 0) {
1689                 textFilter = null;
1690             } else {
1691                 textFilter = new RegExp(val, 'i');
1692             }
1694             var rowSum = 0, totalSum = 0, i = 0, q;
1695             var noVars = $('#noWHEREData').prop('checked');
1696             var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1697             var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1698             var filteredQueries = {}, filteredQueriesLines = {};
1699             var hide = false, rowData;
1700             var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1701             var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1702             var isSlowLog = opts.src == 'slow';
1703             var columnSums = {};
1705             // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1706             var countRow = function (query, row) {
1707                 var cells = row.match(/<td>(.*?)<\/td>/gi);
1708                 if (!columnSums[query]) {
1709                     columnSums[query] = [0, 0, 0, 0];
1710                 }
1712                 // lock_time and query_time and displayed in timespan format
1713                 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1714                 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1715                 // rows_examind and rows_sent are just numbers
1716                 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1717                 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1718             };
1720             // We just assume the sql text is always in the second last column, and that the total count is right of it
1721             $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1722                 var $t = $(this);
1723                 // If query is a SELECT and user enabled or disabled to group
1724                 // queries ignoring data in where statements, we
1725                 // need to re-calculate the sums of each row
1726                 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1727                     if (noVars) {
1728                         // Group on => Sum up identical columns, and hide all but 1
1730                         q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1731                         q = q.replace(functionFilter, ' $1(...)');
1733                         // Js does not specify a limit on property name length,
1734                         // so we can abuse it as index :-)
1735                         if (filteredQueries[q]) {
1736                             filteredQueries[q] += parseInt($t.next().text(), 10);
1737                             totalSum += parseInt($t.next().text(), 10);
1738                             hide = true;
1739                         } else {
1740                             filteredQueries[q] = parseInt($t.next().text(), 10);
1741                             filteredQueriesLines[q] = i;
1742                             $t.text(q);
1743                         }
1744                         if (isSlowLog) {
1745                             countRow(q, $t.parent().html());
1746                         }
1748                     } else {
1749                         // Group off: Restore original columns
1751                         rowData = $t.parent().data('query');
1752                         // Restore SQL text
1753                         $t.text(rowData[queryColumnName]);
1754                         // Restore total count
1755                         $t.next().text(rowData[sumColumnName]);
1756                         // Restore slow log columns
1757                         if (isSlowLog) {
1758                             $t.parent().children('td:nth-child(3)').text(rowData.query_time);
1759                             $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
1760                             $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
1761                             $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
1762                         }
1763                     }
1764                 }
1766                 // If not required to be hidden, do we need
1767                 // to hide because of a not matching text filter?
1768                 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1769                     hide = true;
1770                 }
1772                 // Now display or hide this column
1773                 if (hide) {
1774                     $t.parent().css('display', 'none');
1775                 } else {
1776                     totalSum += parseInt($t.next().text(), 10);
1777                     rowSum++;
1779                     odd_row = ! odd_row;
1780                     $t.parent().css('display', '');
1781                     if (odd_row) {
1782                         $t.parent().addClass('odd');
1783                         $t.parent().removeClass('even');
1784                     } else {
1785                         $t.parent().addClass('even');
1786                         $t.parent().removeClass('odd');
1787                     }
1788                 }
1790                 hide = false;
1791                 i++;
1792             });
1794             // We finished summarizing counts => Update count values of all grouped entries
1795             if (varFilterChange) {
1796                 if (noVars) {
1797                     var numCol, row, $table = $('#logTable').find('table tbody');
1798                     $.each(filteredQueriesLines, function (key, value) {
1799                         if (filteredQueries[key] <= 1) {
1800                             return;
1801                         }
1803                         row =  $table.children('tr:nth-child(' + (value + 1) + ')');
1804                         numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1805                         numCol.text(filteredQueries[key]);
1807                         if (isSlowLog) {
1808                             row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1809                             row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1810                             row.children('td:nth-child(5)').text(columnSums[key][2]);
1811                             row.children('td:nth-child(6)').text(columnSums[key][3]);
1812                         }
1813                     });
1814                 }
1816                 $('#logTable').find('table').trigger("update");
1817                 setTimeout(function () {
1818                     $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1819                 }, 0);
1820             }
1822             // Display some stats at the bottom of the table
1823             $('#logTable').find('table tfoot tr')
1824                 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1825                       PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
1826                       PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1827         }
1828     }
1830     /* Turns a timespan (12:12:12) into a number */
1831     function timeToSec(timeStr) {
1832         var time = timeStr.split(':');
1833         return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1834     }
1836     /* Turns a number into a timespan (100 into 00:01:40) */
1837     function secToTime(timeInt) {
1838         var hours = Math.floor(timeInt / 3600);
1839         timeInt -= hours * 3600;
1840         var minutes = Math.floor(timeInt / 60);
1841         timeInt -= minutes * 60;
1843         if (hours < 10) {
1844             hours = '0' + hours;
1845         }
1846         if (minutes < 10) {
1847             minutes = '0' + minutes;
1848         }
1849         if (timeInt < 10) {
1850             timeInt = '0' + timeInt;
1851         }
1853         return hours + ':' + minutes + ':' + timeInt;
1854     }
1856     /* Constructs the log table out of the retrieved server data */
1857     function buildLogTable(data, groupInserts) {
1858         var rows = data.rows;
1859         var cols = [];
1860         var $table = $('<table class="sortable"></table>');
1861         var $tBody, $tRow, $tCell;
1863         $('#logTable').html($table);
1865         var tempPushKey = function (key, value) {
1866             cols.push(key);
1867         };
1869         var formatValue = function (name, value) {
1870             if (name == 'user_host') {
1871                 return value.replace(/(\[.*?\])+/g, '');
1872             }
1873             return escapeHtml(value);
1874         };
1876         for (var i = 0, l = rows.length; i < l; i++) {
1877             if (i === 0) {
1878                 $.each(rows[0], tempPushKey);
1879                 $table.append('<thead>' +
1880                               '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1881                               '</thead>'
1882                 );
1884                 $table.append($tBody = $('<tbody></tbody>'));
1885             }
1887             $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1888             var cl = '';
1889             for (var j = 0, ll = cols.length; j < ll; j++) {
1890                 // Assuming the query column is the second last
1891                 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1892                     $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1893                     $tCell.click(openQueryAnalyzer);
1894                 } else {
1895                     $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1896                 }
1898                 $tRow.data('query', rows[i]);
1899             }
1900         }
1902         $table.append('<tfoot>' +
1903                     '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1904                     ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
1905                     '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1907         // Append a tooltip to the count column, if there exist one
1908         if ($('#logTable').find('tr:first th:last').text().indexOf("#") > -1) {
1909             $('#logTable').find('tr:first th:last').append('&nbsp;' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
1911             var tooltipContent = PMA_messages.strCountColumnExplanation;
1912             if (groupInserts) {
1913                 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1914             }
1916             PMA_tooltip(
1917                 $('img.qroupedQueryInfoIcon'),
1918                 'img',
1919                 tooltipContent
1920             );
1921         }
1923         $('#logTable').find('table').tablesorter({
1924             sortList: [[cols.length - 1, 1]],
1925             widgets: ['fast-zebra']
1926         });
1928         $('#logTable').find('table thead th')
1929             .append('<div class="sorticon"></div>');
1931         return cols;
1932     }
1934     /* Opens the query analyzer dialog */
1935     function openQueryAnalyzer() {
1936         var rowData = $(this).parent().data('query');
1937         var query = rowData.argument || rowData.sql_text;
1939         if (codemirror_editor) {
1940             //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1941             //query = PMA_SQLPrettyPrint(query);
1942             codemirror_editor.setValue(query);
1943             // Codemirror is bugged, it doesn't refresh properly sometimes.
1944             // Following lines seem to fix that
1945             setTimeout(function () {
1946                 codemirror_editor.refresh();
1947             }, 50);
1948         }
1949         else {
1950             $('#sqlquery').val(query);
1951         }
1953         var profilingChart = null;
1954         var dlgBtns = {};
1956         dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1957             loadQueryAnalysis(rowData);
1958         };
1959         dlgBtns[PMA_messages.strClose] = function () {
1960             $(this).dialog('close');
1961         };
1963         $('#queryAnalyzerDialog').dialog({
1964             width: 'auto',
1965             height: 'auto',
1966             resizable: false,
1967             buttons: dlgBtns,
1968             close: function () {
1969                 if (profilingChart !== null) {
1970                     profilingChart.destroy();
1971                 }
1972                 $('#queryAnalyzerDialog').find('div.placeHolder').html('');
1973                 if (codemirror_editor) {
1974                     codemirror_editor.setValue('');
1975                 } else {
1976                     $('#sqlquery').val('');
1977                 }
1978             }
1979         });
1980     }
1982     /* Loads and displays the analyzed query data */
1983     function loadQueryAnalysis(rowData) {
1984         var db = rowData.db || '';
1986         $('#queryAnalyzerDialog').find('div.placeHolder').html(
1987             PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1988             pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1990         $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1991             ajax_request: true,
1992             query_analyzer: true,
1993             query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1994             database: db
1995         }, function (data) {
1996             var i, l;
1997             if (typeof data !== 'undefined' && data.success === true) {
1998                 data = data.message;
1999             }
2000             if (data.error) {
2001                 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
2002                     data.error = PMA_messages.strServerLogError;
2003                 }
2004                 $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
2005                 return;
2006             }
2007             var totalTime = 0;
2008             // Float sux, I'll use table :(
2009             $('#queryAnalyzerDialog').find('div.placeHolder')
2010                 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
2012             var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2013             if (data.explain.length > 1) {
2014                 explain += ' (';
2015                 for (i = 0; i < data.explain.length; i++) {
2016                     if (i > 0) {
2017                         explain += ', ';
2018                     }
2019                     explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2020                 }
2021                 explain += ')';
2022             }
2023             explain += '<p></p>';
2025             var tempExplain = function (key, value) {
2026                 value = (value === null) ? 'null' : escapeHtml(value);
2028                 if (key == 'type' && value.toLowerCase() == 'all') {
2029                     value = '<span class="attention">' + value + '</span>';
2030                 }
2031                 if (key == 'Extra') {
2032                     value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2033                 }
2034                 explain += key + ': ' + value + '<br />';
2035             };
2037             for (i = 0, l = data.explain.length; i < l; i++) {
2038                 explain += '<div class="explain-' + i + '"' + (i > 0 ?  'style="display:none;"' : '') + '>';
2039                 $.each(data.explain[i], tempExplain);
2040                 explain += '</div>';
2041             }
2043             explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2045             $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
2047             $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
2048                 var id = $(this).attr('href').split('-')[1];
2049                 $(this).parent().find('div[class*="explain"]').hide();
2050                 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2051             });
2053             if (data.profiling) {
2054                 var chartData = [];
2055                 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2056                 var duration;
2057                 var otherTime = 0;
2059                 for (i = 0, l = data.profiling.length; i < l; i++) {
2060                     duration = parseFloat(data.profiling[i].duration);
2062                     totalTime += duration;
2064                     numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2065                 }
2067                 // Only put those values in the pie which are > 2%
2068                 for (i = 0, l = data.profiling.length; i < l; i++) {
2069                     duration = parseFloat(data.profiling[i].duration);
2071                     if (duration / totalTime > 0.02) {
2072                         chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2073                     } else {
2074                         otherTime += duration;
2075                     }
2076                 }
2078                 if (otherTime > 0) {
2079                     chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2080                 }
2082                 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2083                 numberTable += '</tbody></table>';
2085                 $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
2086                     '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2087                     '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2088                     numberTable + ' <div id="queryProfiling"></div>');
2090                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
2091                     $('#queryAnalyzerDialog').find('#queryProfiling').hide();
2092                     $('#queryAnalyzerDialog').find('table.queryNums').show();
2093                     return false;
2094                 });
2096                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
2097                     $('#queryAnalyzerDialog').find('#queryProfiling').show();
2098                     $('#queryAnalyzerDialog').find('table.queryNums').hide();
2099                     return false;
2100                 });
2102                 profilingChart = PMA_createProfilingChartJqplot(
2103                     'queryProfiling',
2104                     chartData
2105                 );
2107                 //$('#queryProfiling').resizable();
2108             }
2109         });
2110     }
2112     /* Saves the monitor to localstorage */
2113     function saveMonitor() {
2114         var gridCopy = {};
2116         $.each(runtime.charts, function (key, elem) {
2117             gridCopy[key] = {};
2118             gridCopy[key].nodes = elem.nodes;
2119             gridCopy[key].settings = elem.settings;
2120             gridCopy[key].title = elem.title;
2121             gridCopy[key].series = elem.series;
2122             gridCopy[key].maxYLabel = elem.maxYLabel;
2123         });
2125         if (window.localStorage) {
2126             window.localStorage.monitorCharts = JSON.stringify(gridCopy);
2127             window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
2128             window.localStorage.monitorVersion = monitorProtocolVersion;
2129         }
2131         $('a[href="#clearMonitorConfig"]').show();
2132     }
2135 // Run the monitor once loaded
2136 AJAX.registerOnload('server_status_monitor.js', function () {
2137     $('a[href="#pauseCharts"]').trigger('click');
2140 function serverResponseError() {
2141     var btns = {};
2142     btns[PMA_messages.strReloadPage] = function () {
2143         window.location.reload();
2144     };
2145     $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2146     $('#emptyDialog').html(
2147         PMA_getImage('s_attention.png') +
2148         PMA_messages.strInvalidResponseExplanation
2149     );
2150     $('#emptyDialog').dialog({ buttons: btns });
2153 /* Destroys all monitor related resources */
2154 function destroyGrid() {
2155     if (runtime.charts) {
2156         $.each(runtime.charts, function (key, value) {
2157             try {
2158                 value.chart.destroy();
2159             } catch (err) {}
2160         });
2161     }
2163     try {
2164         runtime.refreshRequest.abort();
2165     } catch (err) {}
2166     try {
2167         clearTimeout(runtime.refreshTimeout);
2168     } catch (err) {}
2169     $('#chartGrid').html('');
2170     runtime.charts = null;
2171     runtime.chartAI = 0;
2172     monitorSettings = null; //TODO:this not global variable