Revert "Login screen improvements and added favicon (#227)"
[openemr.git] / phpmyadmin / js / server_status_monitor.js
blob55bc3b90ec2bc0a63906985e9afebb3460fb1e9f
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                     if (isStorageSupported('localStorage')) {
636                         window.localStorage.removeItem('monitorCharts');
637                         window.localStorage.removeItem('monitorSettings');
638                     }
639                     rebuildGrid();
640                 }
642                 $('#emptyDialog').dialog('close');
643             });
645             $("body", d).append($form = $('#emptyDialog').find('form'));
646             $form.submit();
647             $('#emptyDialog').append('<img class="ajaxIcon" src="' + pmaThemeImage + 'ajax_clock_small.gif" alt="">');
648         };
650         dlgBtns[PMA_messages.strCancel] = function () {
651             $(this).dialog('close');
652         };
655         $('#emptyDialog').dialog({
656             width: 'auto',
657             height: 'auto',
658             buttons: dlgBtns
659         });
660     });
662     $('a[href="#clearMonitorConfig"]').click(function (event) {
663         event.preventDefault();
664         if (isStorageSupported('localStorage')) {
665             window.localStorage.removeItem('monitorCharts');
666             window.localStorage.removeItem('monitorSettings');
667             window.localStorage.removeItem('monitorVersion');
668         }
669         $(this).hide();
670         rebuildGrid();
671     });
673     $('a[href="#pauseCharts"]').click(function (event) {
674         event.preventDefault();
675         runtime.redrawCharts = ! runtime.redrawCharts;
676         if (! runtime.redrawCharts) {
677             $(this).html(PMA_getImage('play.png') + PMA_messages.strResumeMonitor);
678         } else {
679             $(this).html(PMA_getImage('pause.png') + PMA_messages.strPauseMonitor);
680             if (! runtime.charts) {
681                 initGrid();
682                 $('a[href="#settingsPopup"]').show();
683             }
684         }
685         return false;
686     });
688     $('a[href="#monitorInstructionsDialog"]').click(function (event) {
689         event.preventDefault();
691         var $dialog = $('#monitorInstructionsDialog');
693         $dialog.dialog({
694             width: 595,
695             height: 'auto'
696         }).find('img.ajaxIcon').show();
698         var loadLogVars = function (getvars) {
699             var vars = { ajax_request: true, logging_vars: true };
700             if (getvars) {
701                 $.extend(vars, getvars);
702             }
704             $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
705                 function (data) {
706                     var logVars;
707                     if (typeof data !== 'undefined' && data.success === true) {
708                         logVars = data.message;
709                     } else {
710                         return serverResponseError();
711                     }
712                     var icon = PMA_getImage('s_success.png'), msg = '', str = '';
714                     if (logVars.general_log == 'ON') {
715                         if (logVars.slow_query_log == 'ON') {
716                             msg = PMA_messages.strBothLogOn;
717                         } else {
718                             msg = PMA_messages.strGenLogOn;
719                         }
720                     }
722                     if (msg.length === 0 && logVars.slow_query_log == 'ON') {
723                         msg = PMA_messages.strSlowLogOn;
724                     }
726                     if (msg.length === 0) {
727                         icon = PMA_getImage('s_error.png');
728                         msg = PMA_messages.strBothLogOff;
729                     }
731                     str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
732                     str += icon + msg + '<br />';
734                     if (logVars.log_output != 'TABLE') {
735                         str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
736                     } else {
737                         str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
738                     }
740                     if (logVars.slow_query_log == 'ON') {
741                         if (logVars.long_query_time > 2) {
742                             str += PMA_getImage('s_attention.png') + ' ';
743                             str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
744                             str += '<br />';
745                         }
747                         if (logVars.long_query_time < 2) {
748                             str += PMA_getImage('s_success.png') + ' ';
749                             str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
750                             str += '<br />';
751                         }
752                     }
754                     str += '</div>';
756                     if (is_superuser) {
757                         str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
758                         str += '<div class="smallIndent">';
759                         str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
761                         var varValue = 'TABLE';
762                         if (logVars.log_output == 'TABLE') {
763                             varValue = 'FILE';
764                         }
766                         str += '- <a class="set" href="#log_output-' + varValue + '">';
767                         str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
768                         str += ' </a><br />';
770                         if (logVars.general_log != 'ON') {
771                             str += '- <a class="set" href="#general_log-ON">';
772                             str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
773                             str += ' </a><br />';
774                         } else {
775                             str += '- <a class="set" href="#general_log-OFF">';
776                             str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
777                             str += ' </a><br />';
778                         }
780                         if (logVars.slow_query_log != 'ON') {
781                             str += '- <a class="set" href="#slow_query_log-ON">';
782                             str +=  PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
783                             str += ' </a><br />';
784                         } else {
785                             str += '- <a class="set" href="#slow_query_log-OFF">';
786                             str +=  PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
787                             str += ' </a><br />';
788                         }
790                         varValue = 5;
791                         if (logVars.long_query_time > 2) {
792                             varValue = 1;
793                         }
795                         str += '- <a class="set" href="#long_query_time-' + varValue + '">';
796                         str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
797                         str += ' </a><br />';
799                     } else {
800                         str += PMA_messages.strNoSuperUser + '<br/>';
801                     }
803                     str += '</div>';
805                     $dialog.find('div.monitorUse').toggle(
806                         logVars.log_output == 'TABLE' && (logVars.slow_query_log == 'ON' || logVars.general_log == 'ON')
807                     );
809                     $dialog.find('div.ajaxContent').html(str);
810                     $dialog.find('img.ajaxIcon').hide();
811                     $dialog.find('a.set').click(function () {
812                         var nameValue = $(this).attr('href').split('-');
813                         loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
814                         $dialog.find('img.ajaxIcon').show();
815                     });
816                 }
817             );
818         };
821         loadLogVars();
823         return false;
824     });
826     $('input[name="chartType"]').change(function () {
827         $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
828         var title = $('input[name="chartTitle"]').val();
829         if (title == PMA_messages.strChartTitle ||
830             title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
831         ) {
832             $('input[name="chartTitle"]')
833                 .data('lastRadio', $(this).attr('id'))
834                 .val($('label[for="' + $(this).attr('id') + '"]').text());
835         }
837     });
839     $('input[name="useDivisor"]').change(function () {
840         $('span.divisorInput').toggle(this.checked);
841     });
843     $('input[name="useUnit"]').change(function () {
844         $('span.unitInput').toggle(this.checked);
845     });
847     $('select[name="varChartList"]').change(function () {
848         if (this.selectedIndex !== 0) {
849             $('#variableInput').val(this.value);
850         }
851     });
853     $('a[href="#kibDivisor"]').click(function (event) {
854         event.preventDefault();
855         $('input[name="valueDivisor"]').val(1024);
856         $('input[name="valueUnit"]').val(PMA_messages.strKiB);
857         $('span.unitInput').toggle(true);
858         $('input[name="useUnit"]').prop('checked', true);
859         return false;
860     });
862     $('a[href="#mibDivisor"]').click(function (event) {
863         event.preventDefault();
864         $('input[name="valueDivisor"]').val(1024 * 1024);
865         $('input[name="valueUnit"]').val(PMA_messages.strMiB);
866         $('span.unitInput').toggle(true);
867         $('input[name="useUnit"]').prop('checked', true);
868         return false;
869     });
871     $('a[href="#submitClearSeries"]').click(function (event) {
872         event.preventDefault();
873         $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
874         newChart = null;
875         $('#clearSeriesLink').hide();
876     });
878     $('a[href="#submitAddSeries"]').click(function (event) {
879         event.preventDefault();
880         if ($('#variableInput').val() === "") {
881             return false;
882         }
884         if (newChart === null) {
885             $('#seriesPreview').html('');
887             newChart = {
888                 title: $('input[name="chartTitle"]').val(),
889                 nodes: [],
890                 series: [],
891                 maxYLabel: 0
892             };
893         }
895         var serie = {
896             dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
897             display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
898         };
900         if (serie.dataPoints[0].name == 'Processes') {
901             serie.dataPoints[0].type = 'proc';
902         }
904         if ($('input[name="useDivisor"]').prop('checked')) {
905             serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
906         }
908         if ($('input[name="useUnit"]').prop('checked')) {
909             serie.unit = $('input[name="valueUnit"]').val();
910         }
912         var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
913         str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
914         str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
916         var newSeries = {
917             label: $('#variableInput').val().replace(/_/g, " ")
918         };
919         newChart.series.push(newSeries);
920         $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
921         newChart.nodes.push(serie);
922         $('#variableInput').val('');
923         $('input[name="differentialValue"]').prop('checked', true);
924         $('input[name="useDivisor"]').prop('checked', false);
925         $('input[name="useUnit"]').prop('checked', false);
926         $('input[name="useDivisor"]').trigger('change');
927         $('input[name="useUnit"]').trigger('change');
928         $('select[name="varChartList"]').get(0).selectedIndex = 0;
930         $('#clearSeriesLink').show();
932         return false;
933     });
935     $("#variableInput").autocomplete({
936         source: variableNames
937     });
939     /* Initializes the monitor, called only once */
940     function initGrid() {
942         var i;
944         /* Apply default values & config */
945         if (isStorageSupported('localStorage')) {
946             if (typeof window.localStorage.monitorCharts !== 'undefined') {
947                 runtime.charts = $.parseJSON(window.localStorage.monitorCharts);
948             }
949             if (typeof window.localStorage.monitorSettings !== 'undefined') {
950                 monitorSettings = $.parseJSON(window.localStorage.monitorSettings);
951             }
953             $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
955             if (runtime.charts !== null
956                 && typeof window.localStorage.monitorVersion !== 'undefined'
957                 && monitorProtocolVersion != window.localStorage.monitorVersion
958             ) {
959                 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
960                 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
962                 var dlgBtns = {};
963                 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
965                 $('#emptyDialog').dialog({
966                     width: 400,
967                     buttons: dlgBtns
968                 });
969             }
970         }
972         if (runtime.charts === null) {
973             runtime.charts = defaultChartGrid;
974         }
975         if (monitorSettings === null) {
976             monitorSettings = defaultMonitorSettings;
977         }
979         $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
980         $('select[name="chartColumns"]').val(monitorSettings.columns);
982         if (monitorSettings.gridMaxPoints == 'auto') {
983             runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
984         } else {
985             runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
986         }
988         runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
989         runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
991         /* Calculate how much spacing there is between each chart */
992         $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
993         chartSpacing = {
994             width: $('#chartGrid').find('td:nth-child(2)').offset().left -
995                 $('#chartGrid').find('td:nth-child(1)').offset().left,
996             height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
997                 $('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top
998         };
999         $('#chartGrid').html('');
1001         /* Add all charts - in correct order */
1002         var keys = [];
1003         $.each(runtime.charts, function (key, value) {
1004             keys.push(key);
1005         });
1006         keys.sort();
1007         for (i = 0; i < keys.length; i++) {
1008             addChart(runtime.charts[keys[i]], true);
1009         }
1011         /* Fill in missing cells */
1012         var numCharts = $('#chartGrid').find('.monitorChart').length;
1013         var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
1014         for (i = 0; i < numMissingCells; i++) {
1015             $('#chartGrid').find('tr:last').append('<td></td>');
1016         }
1018         // Empty cells should keep their size so you can drop onto them
1019         calculateChartSize();
1020         $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
1022         buildRequiredDataList();
1023         refreshChartGrid();
1024     }
1026     /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1027      * data from each chart and restores it after the monitor is initialized again */
1028     function rebuildGrid() {
1029         var oldData = null;
1030         if (runtime.charts) {
1031             oldData = {};
1032             $.each(runtime.charts, function (key, chartObj) {
1033                 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1034                     oldData[chartObj.nodes[i].dataPoint] = [];
1035                     for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1036                         oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1037                     }
1038                 }
1039             });
1040         }
1042         destroyGrid();
1043         initGrid();
1044     }
1046     /* Calculactes the dynamic chart size that depends on the column width */
1047     function calculateChartSize() {
1048         var panelWidth;
1049         if ($("body").height() > $(window).height()) { // has vertical scroll bar
1050             panelWidth = $('#logTable').innerWidth();
1051         } else {
1052             panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1053         }
1055         var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1056         chartSize = {
1057             width: Math.floor(wdt),
1058             height: Math.floor(0.75 * wdt)
1059         };
1060     }
1062     /* Adds a chart to the chart grid */
1063     function addChart(chartObj, initialize) {
1065         var i;
1066         var settings = {
1067             title: escapeHtml(chartObj.title),
1068             grid: {
1069                 drawBorder: false,
1070                 shadow: false,
1071                 background: 'rgba(0,0,0,0)'
1072             },
1073             axes: {
1074                 xaxis: {
1075                     renderer: $.jqplot.DateAxisRenderer,
1076                     tickOptions: {
1077                         formatString: '%H:%M:%S',
1078                         showGridline: false
1079                     },
1080                     min: runtime.xmin,
1081                     max: runtime.xmax
1082                 },
1083                 yaxis: {
1084                     min: 0,
1085                     max: 100,
1086                     tickInterval: 20
1087                 }
1088             },
1089             seriesDefaults: {
1090                 rendererOptions: {
1091                     smooth: true
1092                 },
1093                 showLine: true,
1094                 lineWidth: 2,
1095                 markerOptions: {
1096                     size: 6
1097                 }
1098             },
1099             highlighter: {
1100                 show: true
1101             }
1102         };
1104         if (settings.title === PMA_messages.strSystemCPUUsage ||
1105             settings.title === PMA_messages.strQueryCacheEfficiency
1106         ) {
1107             settings.axes.yaxis.tickOptions = {
1108                 formatString: "%d %%"
1109             };
1110         } else if (settings.title === PMA_messages.strSystemMemory ||
1111             settings.title === PMA_messages.strSystemSwap
1112         ) {
1113             settings.stackSeries = true;
1114             settings.axes.yaxis.tickOptions = {
1115                 formatter: $.jqplot.byteFormatter(2) // MiB
1116             };
1117         } else if (settings.title === PMA_messages.strTraffic) {
1118             settings.axes.yaxis.tickOptions = {
1119                 formatter: $.jqplot.byteFormatter(1) // KiB
1120             };
1121         } else if (settings.title === PMA_messages.strQuestions ||
1122             settings.title === PMA_messages.strConnections
1123         ) {
1124             settings.axes.yaxis.tickOptions = {
1125                 formatter: function (format, val) {
1126                     if (Math.abs(val) >= 1000000) {
1127                         return $.jqplot.sprintf("%.3g M", val / 1000000);
1128                     } else if (Math.abs(val) >= 1000) {
1129                         return $.jqplot.sprintf("%.3g k", val / 1000);
1130                     } else {
1131                         return $.jqplot.sprintf("%d", val);
1132                     }
1133                 }
1134             };
1135         }
1137         settings.series = chartObj.series;
1139         if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1140             var numCharts = $('#chartGrid').find('.monitorChart').length;
1142             if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1143                 $('#chartGrid').append('<tr></tr>');
1144             }
1146             if (!chartSize) {
1147                 calculateChartSize();
1148             }
1149             $('#chartGrid').find('tr:last').append(
1150                 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1151                 '<div class="ui-state-default monitorChart"' +
1152                 ' id="gridchart' + runtime.chartAI + '"' +
1153                 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1154                 '</div></td>'
1155             );
1156         }
1158         // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1159         // also chart won't plot initially with no data and data comes on refreshChartGrid()
1160         var series = [];
1161         for (i in chartObj.series) {
1162             series.push([[0, 0]]);
1163         }
1165         var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) {
1166             var j;
1167             // TODO: move style to theme CSS
1168             var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1169                 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1170             // x value i.e. time
1171             var timeValue = str.split(",")[0];
1172             var seriesValue;
1173             tooltipHtml += 'Time: ' + timeValue;
1174             tooltipHtml += '<span style="font-weight:bold;">';
1175             // Add y values to the tooltip per series
1176             for (j in plot.series) {
1177                 // get y value if present
1178                 if (plot.series[j].data.length > pointIndex) {
1179                     seriesValue = plot.series[j].data[pointIndex][1];
1180                 } else {
1181                     return;
1182                 }
1183                 var seriesLabel = plot.series[j].label;
1184                 var seriesColor = plot.series[j].color;
1185                 // format y value
1186                 if (plot.series[0]._yaxis.tickOptions.formatter) {
1187                     // using formatter function
1188                     seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1189                 } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1190                     // using format string
1191                     seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1192                 }
1193                 tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1194                     seriesLabel + ': ' + seriesValue + '</span>';
1195             }
1196             tooltipHtml += '</span></div>';
1197             return tooltipHtml;
1198         };
1200         // set Tooltip for each series
1201         for (i in settings.series) {
1202             settings.series[i].highlighter = {
1203                 show: true,
1204                 tooltipContentEditor: tempTooltipContentEditor
1205             };
1206         }
1208         chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1209         // remove [0,0] after plotting
1210         for (i in chartObj.chart.series) {
1211             chartObj.chart.series[i].data.shift();
1212         }
1214         var $legend = $('<div />').css('padding', '0.5em');
1215         for (i in chartObj.chart.series) {
1216             $legend.append(
1217                 $('<div />').append(
1218                     $('<div>').css({
1219                         width: '1em',
1220                         height: '1em',
1221                         background: chartObj.chart.seriesColors[i]
1222                     }).addClass('floatleft')
1223                 ).append(
1224                     $('<div>').text(
1225                         chartObj.chart.series[i].label
1226                     ).addClass('floatleft')
1227                 ).append(
1228                     $('<div class="clearfloat">')
1229                 ).addClass('floatleft')
1230             );
1231         }
1232         $('#gridchart' + runtime.chartAI)
1233             .parent()
1234             .append($legend);
1236         if (initialize !== true) {
1237             runtime.charts['c' + runtime.chartAI] = chartObj;
1238             buildRequiredDataList();
1239         }
1241         // time span selection
1242         $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1243             drawTimeSpan = true;
1244             selectionTimeDiff.push(datapos.xaxis);
1245             if ($('#selection_box').length) {
1246                 $('#selection_box').remove();
1247             }
1248             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;">');
1249             $(document.body).append(selectionBox);
1250             selectionStartX = ev.pageX;
1251             selectionStartY = ev.pageY;
1252             selectionBox
1253                 .attr({id: 'selection_box'})
1254                 .css({
1255                     top: selectionStartY - gridpos.y,
1256                     left: selectionStartX
1257                 })
1258                 .fadeIn();
1259         });
1261         $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1262             if (! drawTimeSpan || editMode) {
1263                 return;
1264             }
1266             selectionTimeDiff.push(datapos.xaxis);
1268             if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1269                 selectionTimeDiff = [];
1270                 return;
1271             }
1272             //get date from timestamp
1273             var min = new Date(Math.ceil(selectionTimeDiff[0]));
1274             var max = new Date(Math.ceil(selectionTimeDiff[1]));
1275             PMA_getLogAnalyseDialog(min, max);
1276             selectionTimeDiff = [];
1277             drawTimeSpan = false;
1278         });
1280         $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1281             if (! drawTimeSpan || editMode) {
1282                 return;
1283             }
1284             if (selectionStartX !== undefined) {
1285                 $('#selection_box')
1286                     .css({
1287                         width: Math.ceil(ev.pageX - selectionStartX)
1288                     })
1289                     .fadeIn();
1290             }
1291         });
1293         $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1294             drawTimeSpan = false;
1295         });
1297         $(document.body).mouseup(function () {
1298             if ($('#selection_box').length) {
1299                 $('#selection_box').remove();
1300             }
1301         });
1303         // Edit, Print icon only in edit mode
1304         $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1306         runtime.chartAI++;
1307     }
1309     function PMA_getLogAnalyseDialog(min, max) {
1310         var $logAnalyseDialog = $('#logAnalyseDialog');
1311         var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
1312         var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
1313         $dateStart.prop("readonly", true);
1314         $dateEnd.prop("readonly", true);
1316         var dlgBtns = { };
1318         dlgBtns[PMA_messages.strFromSlowLog] = function () {
1319             loadLog('slow', min, max);
1320             $(this).dialog("close");
1321         };
1323         dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1324             loadLog('general', min, max);
1325             $(this).dialog("close");
1326         };
1328         $logAnalyseDialog.dialog({
1329             width: 'auto',
1330             height: 'auto',
1331             buttons: dlgBtns
1332         });
1334         PMA_addDatepicker($dateStart, 'datetime', {
1335             showMillisec: false,
1336             showMicrosec: false,
1337             timeFormat: 'HH:mm:ss'
1338         });
1339         PMA_addDatepicker($dateEnd, 'datetime', {
1340             showMillisec: false,
1341             showMicrosec: false,
1342             timeFormat: 'HH:mm:ss'
1343         });
1344         $dateStart.datepicker('setDate', min);
1345         $dateEnd.datepicker('setDate', max);
1346     }
1348     function loadLog(type, min, max) {
1349         var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
1350         var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
1352         loadLogStatistics({
1353             src: type,
1354             start: dateStart,
1355             end: dateEnd,
1356             removeVariables: $('#removeVariables').prop('checked'),
1357             limitTypes: $('#limitTypes').prop('checked')
1358         });
1359     }
1361     /* Called in regular intervals, this function updates the values of each chart in the grid */
1362     function refreshChartGrid() {
1363         /* Send to server */
1364         runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1365             ajax_request: true,
1366             chart_data: 1,
1367             type: 'chartgrid',
1368             requiredData: JSON.stringify(runtime.dataList)
1369         }, function (data) {
1370             var chartData;
1371             if (typeof data !== 'undefined' && data.success === true) {
1372                 chartData = data.message;
1373             } else {
1374                 return serverResponseError();
1375             }
1376             var value, i = 0;
1377             var diff;
1378             var total;
1380             /* Update values in each graph */
1381             $.each(runtime.charts, function (orderKey, elem) {
1382                 var key = elem.chartID;
1383                 // If newly added chart, we have no data for it yet
1384                 if (! chartData[key]) {
1385                     return;
1386                 }
1387                 // Draw all series
1388                 total = 0;
1389                 for (var j = 0; j < elem.nodes.length; j++) {
1390                     // Update x-axis
1391                     if (i === 0 && j === 0) {
1392                         if (oldChartData === null) {
1393                             diff = chartData.x - runtime.xmax;
1394                         } else {
1395                             diff = parseInt(chartData.x - oldChartData.x, 10);
1396                         }
1398                         runtime.xmin += diff;
1399                         runtime.xmax += diff;
1400                     }
1402                     //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1403                     /* Calculate y value */
1405                     // If transform function given, use it
1406                     if (elem.nodes[j].transformFn) {
1407                         value = chartValueTransform(
1408                             elem.nodes[j].transformFn,
1409                             chartData[key][j],
1410                             // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1411                             (
1412                                 oldChartData === null ||
1413                                 oldChartData[key] === null ||
1414                                 oldChartData[key] === undefined ? null : oldChartData[key][j]
1415                             )
1416                         );
1418                     // Otherwise use original value and apply differential and divisor if given,
1419                     // in this case we have only one data point per series - located at chartData[key][j][0]
1420                     } else {
1421                         value = parseFloat(chartData[key][j][0].value);
1423                         if (elem.nodes[j].display == 'differential') {
1424                             if (oldChartData === null ||
1425                                 oldChartData[key] === null ||
1426                                 oldChartData[key] === undefined
1427                             ) {
1428                                 continue;
1429                             }
1430                             value -= oldChartData[key][j][0].value;
1431                         }
1433                         if (elem.nodes[j].valueDivisor) {
1434                             value = value / elem.nodes[j].valueDivisor;
1435                         }
1436                     }
1438                     // Set y value, if defined
1439                     if (value !== undefined) {
1440                         elem.chart.series[j].data.push([chartData.x, value]);
1441                         if (value > elem.maxYLabel) {
1442                             elem.maxYLabel = value;
1443                         } else if (elem.maxYLabel === 0) {
1444                             elem.maxYLabel = 0.5;
1445                         }
1446                         // free old data point values and update maxYLabel
1447                         if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1448                             elem.chart.series[j].data[0][0] < runtime.xmin
1449                         ) {
1450                             // check if the next freeable point is highest
1451                             if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1452                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1453                                 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1454                             } else {
1455                                 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1456                             }
1457                         }
1458                         if (elem.title === PMA_messages.strSystemMemory ||
1459                             elem.title === PMA_messages.strSystemSwap
1460                         ) {
1461                             total += value;
1462                         }
1463                     }
1464                 }
1466                 // update chart options
1467                 // keep ticks number/positioning consistent while refreshrate changes
1468                 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1469                 elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
1470                     (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1471                     (runtime.xmax - tickInterval), runtime.xmax];
1473                 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1474                     elem.title !== PMA_messages.strQueryCacheEfficiency &&
1475                     elem.title !== PMA_messages.strSystemMemory &&
1476                     elem.title !== PMA_messages.strSystemSwap
1477                 ) {
1478                     elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
1479                     elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
1480                 } else if (elem.title === PMA_messages.strSystemMemory ||
1481                     elem.title === PMA_messages.strSystemSwap
1482                 ) {
1483                     elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
1484                     elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
1485                 }
1486                 i++;
1488                 if (runtime.redrawCharts) {
1489                     elem.chart.replot();
1490                 }
1491             });
1493             oldChartData = chartData;
1495             runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1496         });
1497     }
1499     /* Function to get highest plotted point's y label, to scale the chart,
1500      * TODO: make jqplot's autoscale:true work here
1501      */
1502     function getMaxYLabel(dataValues) {
1503         var maxY = dataValues[0][1];
1504         $.each(dataValues, function (k, v) {
1505             maxY = (v[1] > maxY) ? v[1] : maxY;
1506         });
1507         return maxY;
1508     }
1510     /* Function that supplies special value transform functions for chart values */
1511     function chartValueTransform(name, cur, prev) {
1512         switch (name) {
1513         case 'cpu-linux':
1514             if (prev === null) {
1515                 return undefined;
1516             }
1517             // cur and prev are datapoint arrays, but containing
1518             // only 1 element for cpu-linux
1519             cur = cur[0];
1520             prev = prev[0];
1522             var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1523             var diff_idle = cur.idle - prev.idle;
1524             return 100 * (diff_total - diff_idle) / diff_total;
1526         // Query cache efficiency (%)
1527         case 'qce':
1528             if (prev === null) {
1529                 return undefined;
1530             }
1531             // cur[0].value is Qcache_hits, cur[1].value is Com_select
1532             var diffQHits = cur[0].value - prev[0].value;
1533             // No NaN please :-)
1534             if (cur[1].value - prev[1].value === 0) {
1535                 return 0;
1536             }
1538             return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1540         // Query cache usage (%)
1541         case 'qcu':
1542             if (cur[1].value === 0) {
1543                 return 0;
1544             }
1545             // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1546             return 100 - cur[0].value / cur[1].value * 100;
1548         }
1549         return undefined;
1550     }
1552     /* Build list of nodes that need to be retrieved from server.
1553      * It creates something like a stripped down version of the runtime.charts object.
1554      */
1555     function buildRequiredDataList() {
1556         runtime.dataList = {};
1557         // Store an own id, because the property name is subject of reordering,
1558         // thus destroying our mapping with runtime.charts <=> runtime.dataList
1559         var chartID = 0;
1560         $.each(runtime.charts, function (key, chart) {
1561             runtime.dataList[chartID] = [];
1562             for (var i = 0, l = chart.nodes.length; i < l; i++) {
1563                 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1564             }
1565             runtime.charts[key].chartID = chartID;
1566             chartID++;
1567         });
1568     }
1570     /* Loads the log table data, generates the table and handles the filters */
1571     function loadLogStatistics(opts) {
1572         var tableStr = '';
1573         var logRequest = null;
1575         if (! opts.removeVariables) {
1576             opts.removeVariables = false;
1577         }
1578         if (! opts.limitTypes) {
1579             opts.limitTypes = false;
1580         }
1582         $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1583         $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1584                                 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1585                                 'ajax_clock_small.gif" alt="">');
1586         var dlgBtns = {};
1588         dlgBtns[PMA_messages.strCancelRequest] = function () {
1589             if (logRequest !== null) {
1590                 logRequest.abort();
1591             }
1593             $(this).dialog("close");
1594         };
1596         $('#emptyDialog').dialog({
1597             width: 'auto',
1598             height: 'auto',
1599             buttons: dlgBtns
1600         });
1603         logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
1604             {   ajax_request: true,
1605                 log_data: 1,
1606                 type: opts.src,
1607                 time_start: Math.round(opts.start / 1000),
1608                 time_end: Math.round(opts.end / 1000),
1609                 removeVariables: opts.removeVariables,
1610                 limitTypes: opts.limitTypes
1611             },
1612             function (data) {
1613                 var logData;
1614                 var dlgBtns = {};
1615                 if (typeof data !== 'undefined' && data.success === true) {
1616                     logData = data.message;
1617                 } else {
1618                     return serverResponseError();
1619                 }
1621                 if (logData.rows.length === 0) {
1622                     $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1623                     $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1625                     dlgBtns[PMA_messages.strClose] = function () {
1626                         $(this).dialog("close");
1627                     };
1629                     $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1630                     return;
1631                 }
1633                 runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
1635                 /* Show some stats in the dialog */
1636                 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1637                 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1638                 $.each(logData.sum, function (key, value) {
1639                     key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1640                     if (key == 'Total') {
1641                         key = '<b>' + key + '</b>';
1642                     }
1643                     $('#emptyDialog').append(key + ': ' + value + '<br/>');
1644                 });
1646                 /* Add filter options if more than a bunch of rows there to filter */
1647                 if (logData.numRows > 12) {
1648                     $('#logTable').prepend(
1649                         '<fieldset id="logDataFilter">' +
1650                         '    <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1651                         '    <div class="formelement">' +
1652                         '        <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1653                         '        <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1654                         '    </div>' +
1655                         ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1656                         '    <div class="formelement">' +
1657                         '       <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1658                         '       <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1659                         '   </div' +
1660                         '</fieldset>'
1661                     );
1663                     $('#noWHEREData').change(function () {
1664                         filterQueries(true);
1665                     });
1667                     if (logData.numRows > 250) {
1668                         $('#startFilterQueryText').click(filterQueries);
1669                     } else {
1670                         $('#filterQueryText').keyup(filterQueries);
1671                     }
1673                 }
1675                 dlgBtns[PMA_messages.strJumpToTable] = function () {
1676                     $(this).dialog("close");
1677                     $(document).scrollTop($('#logTable').offset().top);
1678                 };
1680                 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1681             }
1682         );
1684         /* Handles the actions performed when the user uses any of the
1685          * log table filters which are the filter by name and grouping
1686          * with ignoring data in WHERE clauses
1687          *
1688          * @param boolean Should be true when the users enabled or disabled
1689          *                to group queries ignoring data in WHERE clauses
1690         */
1691         function filterQueries(varFilterChange) {
1692             var odd_row = false, cell, textFilter;
1693             var val = $('#filterQueryText').val();
1695             if (val.length === 0) {
1696                 textFilter = null;
1697             } else {
1698                 try {
1699                     textFilter = new RegExp(val, 'i');
1700                     $('#filterQueryText').removeClass('error');
1701                 } catch(e) {
1702                     if (e instanceof SyntaxError) {
1703                         $('#filterQueryText').addClass('error');
1704                         textFilter = null;
1705                     }
1706                 }
1707             }
1709             var rowSum = 0, totalSum = 0, i = 0, q;
1710             var noVars = $('#noWHEREData').prop('checked');
1711             var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1712             var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1713             var filteredQueries = {}, filteredQueriesLines = {};
1714             var hide = false, rowData;
1715             var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1716             var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1717             var isSlowLog = opts.src == 'slow';
1718             var columnSums = {};
1720             // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1721             var countRow = function (query, row) {
1722                 var cells = row.match(/<td>(.*?)<\/td>/gi);
1723                 if (!columnSums[query]) {
1724                     columnSums[query] = [0, 0, 0, 0];
1725                 }
1727                 // lock_time and query_time and displayed in timespan format
1728                 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1729                 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1730                 // rows_examind and rows_sent are just numbers
1731                 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1732                 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1733             };
1735             // We just assume the sql text is always in the second last column, and that the total count is right of it
1736             $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1737                 var $t = $(this);
1738                 // If query is a SELECT and user enabled or disabled to group
1739                 // queries ignoring data in where statements, we
1740                 // need to re-calculate the sums of each row
1741                 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1742                     if (noVars) {
1743                         // Group on => Sum up identical columns, and hide all but 1
1745                         q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1746                         q = q.replace(functionFilter, ' $1(...)');
1748                         // Js does not specify a limit on property name length,
1749                         // so we can abuse it as index :-)
1750                         if (filteredQueries[q]) {
1751                             filteredQueries[q] += parseInt($t.next().text(), 10);
1752                             totalSum += parseInt($t.next().text(), 10);
1753                             hide = true;
1754                         } else {
1755                             filteredQueries[q] = parseInt($t.next().text(), 10);
1756                             filteredQueriesLines[q] = i;
1757                             $t.text(q);
1758                         }
1759                         if (isSlowLog) {
1760                             countRow(q, $t.parent().html());
1761                         }
1763                     } else {
1764                         // Group off: Restore original columns
1766                         rowData = $t.parent().data('query');
1767                         // Restore SQL text
1768                         $t.text(rowData[queryColumnName]);
1769                         // Restore total count
1770                         $t.next().text(rowData[sumColumnName]);
1771                         // Restore slow log columns
1772                         if (isSlowLog) {
1773                             $t.parent().children('td:nth-child(3)').text(rowData.query_time);
1774                             $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
1775                             $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
1776                             $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
1777                         }
1778                     }
1779                 }
1781                 // If not required to be hidden, do we need
1782                 // to hide because of a not matching text filter?
1783                 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1784                     hide = true;
1785                 }
1787                 // Now display or hide this column
1788                 if (hide) {
1789                     $t.parent().css('display', 'none');
1790                 } else {
1791                     totalSum += parseInt($t.next().text(), 10);
1792                     rowSum++;
1794                     odd_row = ! odd_row;
1795                     $t.parent().css('display', '');
1796                     if (odd_row) {
1797                         $t.parent().addClass('odd');
1798                         $t.parent().removeClass('even');
1799                     } else {
1800                         $t.parent().addClass('even');
1801                         $t.parent().removeClass('odd');
1802                     }
1803                 }
1805                 hide = false;
1806                 i++;
1807             });
1809             // We finished summarizing counts => Update count values of all grouped entries
1810             if (varFilterChange) {
1811                 if (noVars) {
1812                     var numCol, row, $table = $('#logTable').find('table tbody');
1813                     $.each(filteredQueriesLines, function (key, value) {
1814                         if (filteredQueries[key] <= 1) {
1815                             return;
1816                         }
1818                         row =  $table.children('tr:nth-child(' + (value + 1) + ')');
1819                         numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1820                         numCol.text(filteredQueries[key]);
1822                         if (isSlowLog) {
1823                             row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1824                             row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1825                             row.children('td:nth-child(5)').text(columnSums[key][2]);
1826                             row.children('td:nth-child(6)').text(columnSums[key][3]);
1827                         }
1828                     });
1829                 }
1831                 $('#logTable').find('table').trigger("update");
1832                 setTimeout(function () {
1833                     $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1834                 }, 0);
1835             }
1837             // Display some stats at the bottom of the table
1838             $('#logTable').find('table tfoot tr')
1839                 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1840                       PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
1841                       PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1842         }
1843     }
1845     /* Turns a timespan (12:12:12) into a number */
1846     function timeToSec(timeStr) {
1847         var time = timeStr.split(':');
1848         return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1849     }
1851     /* Turns a number into a timespan (100 into 00:01:40) */
1852     function secToTime(timeInt) {
1853         var hours = Math.floor(timeInt / 3600);
1854         timeInt -= hours * 3600;
1855         var minutes = Math.floor(timeInt / 60);
1856         timeInt -= minutes * 60;
1858         if (hours < 10) {
1859             hours = '0' + hours;
1860         }
1861         if (minutes < 10) {
1862             minutes = '0' + minutes;
1863         }
1864         if (timeInt < 10) {
1865             timeInt = '0' + timeInt;
1866         }
1868         return hours + ':' + minutes + ':' + timeInt;
1869     }
1871     /* Constructs the log table out of the retrieved server data */
1872     function buildLogTable(data, groupInserts) {
1873         var rows = data.rows;
1874         var cols = [];
1875         var $table = $('<table class="sortable"></table>');
1876         var $tBody, $tRow, $tCell;
1878         $('#logTable').html($table);
1880         var tempPushKey = function (key, value) {
1881             cols.push(key);
1882         };
1884         var formatValue = function (name, value) {
1885             if (name == 'user_host') {
1886                 return value.replace(/(\[.*?\])+/g, '');
1887             }
1888             return escapeHtml(value);
1889         };
1891         for (var i = 0, l = rows.length; i < l; i++) {
1892             if (i === 0) {
1893                 $.each(rows[0], tempPushKey);
1894                 $table.append('<thead>' +
1895                               '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1896                               '</thead>'
1897                 );
1899                 $table.append($tBody = $('<tbody></tbody>'));
1900             }
1902             $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1903             var cl = '';
1904             for (var j = 0, ll = cols.length; j < ll; j++) {
1905                 // Assuming the query column is the second last
1906                 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1907                     $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1908                     $tCell.click(openQueryAnalyzer);
1909                 } else {
1910                     $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1911                 }
1913                 $tRow.data('query', rows[i]);
1914             }
1915         }
1917         $table.append('<tfoot>' +
1918                     '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1919                     ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
1920                     '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1922         // Append a tooltip to the count column, if there exist one
1923         if ($('#logTable').find('tr:first th:last').text().indexOf("#") > -1) {
1924             $('#logTable').find('tr:first th:last').append('&nbsp;' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
1926             var tooltipContent = PMA_messages.strCountColumnExplanation;
1927             if (groupInserts) {
1928                 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1929             }
1931             PMA_tooltip(
1932                 $('img.qroupedQueryInfoIcon'),
1933                 'img',
1934                 tooltipContent
1935             );
1936         }
1938         $('#logTable').find('table').tablesorter({
1939             sortList: [[cols.length - 1, 1]],
1940             widgets: ['fast-zebra']
1941         });
1943         $('#logTable').find('table thead th')
1944             .append('<div class="sorticon"></div>');
1946         return cols;
1947     }
1949     /* Opens the query analyzer dialog */
1950     function openQueryAnalyzer() {
1951         var rowData = $(this).parent().data('query');
1952         var query = rowData.argument || rowData.sql_text;
1954         if (codemirror_editor) {
1955             //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1956             //query = PMA_SQLPrettyPrint(query);
1957             codemirror_editor.setValue(query);
1958             // Codemirror is bugged, it doesn't refresh properly sometimes.
1959             // Following lines seem to fix that
1960             setTimeout(function () {
1961                 codemirror_editor.refresh();
1962             }, 50);
1963         }
1964         else {
1965             $('#sqlquery').val(query);
1966         }
1968         var profilingChart = null;
1969         var dlgBtns = {};
1971         dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1972             loadQueryAnalysis(rowData);
1973         };
1974         dlgBtns[PMA_messages.strClose] = function () {
1975             $(this).dialog('close');
1976         };
1978         $('#queryAnalyzerDialog').dialog({
1979             width: 'auto',
1980             height: 'auto',
1981             resizable: false,
1982             buttons: dlgBtns,
1983             close: function () {
1984                 if (profilingChart !== null) {
1985                     profilingChart.destroy();
1986                 }
1987                 $('#queryAnalyzerDialog').find('div.placeHolder').html('');
1988                 if (codemirror_editor) {
1989                     codemirror_editor.setValue('');
1990                 } else {
1991                     $('#sqlquery').val('');
1992                 }
1993             }
1994         });
1995     }
1997     /* Loads and displays the analyzed query data */
1998     function loadQueryAnalysis(rowData) {
1999         var db = rowData.db || '';
2001         $('#queryAnalyzerDialog').find('div.placeHolder').html(
2002             PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
2003             pmaThemeImage + 'ajax_clock_small.gif" alt="">');
2005         $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
2006             ajax_request: true,
2007             query_analyzer: true,
2008             query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
2009             database: db
2010         }, function (data) {
2011             var i, l;
2012             if (typeof data !== 'undefined' && data.success === true) {
2013                 data = data.message;
2014             }
2015             if (data.error) {
2016                 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
2017                     data.error = PMA_messages.strServerLogError;
2018                 }
2019                 $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
2020                 return;
2021             }
2022             var totalTime = 0;
2023             // Float sux, I'll use table :(
2024             $('#queryAnalyzerDialog').find('div.placeHolder')
2025                 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
2027             var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2028             if (data.explain.length > 1) {
2029                 explain += ' (';
2030                 for (i = 0; i < data.explain.length; i++) {
2031                     if (i > 0) {
2032                         explain += ', ';
2033                     }
2034                     explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2035                 }
2036                 explain += ')';
2037             }
2038             explain += '<p></p>';
2040             var tempExplain = function (key, value) {
2041                 value = (value === null) ? 'null' : escapeHtml(value);
2043                 if (key == 'type' && value.toLowerCase() == 'all') {
2044                     value = '<span class="attention">' + value + '</span>';
2045                 }
2046                 if (key == 'Extra') {
2047                     value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2048                 }
2049                 explain += key + ': ' + value + '<br />';
2050             };
2052             for (i = 0, l = data.explain.length; i < l; i++) {
2053                 explain += '<div class="explain-' + i + '"' + (i > 0 ?  'style="display:none;"' : '') + '>';
2054                 $.each(data.explain[i], tempExplain);
2055                 explain += '</div>';
2056             }
2058             explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2060             $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
2062             $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
2063                 var id = $(this).attr('href').split('-')[1];
2064                 $(this).parent().find('div[class*="explain"]').hide();
2065                 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2066             });
2068             if (data.profiling) {
2069                 var chartData = [];
2070                 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2071                 var duration;
2072                 var otherTime = 0;
2074                 for (i = 0, l = data.profiling.length; i < l; i++) {
2075                     duration = parseFloat(data.profiling[i].duration);
2077                     totalTime += duration;
2079                     numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2080                 }
2082                 // Only put those values in the pie which are > 2%
2083                 for (i = 0, l = data.profiling.length; i < l; i++) {
2084                     duration = parseFloat(data.profiling[i].duration);
2086                     if (duration / totalTime > 0.02) {
2087                         chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2088                     } else {
2089                         otherTime += duration;
2090                     }
2091                 }
2093                 if (otherTime > 0) {
2094                     chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2095                 }
2097                 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2098                 numberTable += '</tbody></table>';
2100                 $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
2101                     '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2102                     '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2103                     numberTable + ' <div id="queryProfiling"></div>');
2105                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
2106                     $('#queryAnalyzerDialog').find('#queryProfiling').hide();
2107                     $('#queryAnalyzerDialog').find('table.queryNums').show();
2108                     return false;
2109                 });
2111                 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
2112                     $('#queryAnalyzerDialog').find('#queryProfiling').show();
2113                     $('#queryAnalyzerDialog').find('table.queryNums').hide();
2114                     return false;
2115                 });
2117                 profilingChart = PMA_createProfilingChartJqplot(
2118                     'queryProfiling',
2119                     chartData
2120                 );
2122                 //$('#queryProfiling').resizable();
2123             }
2124         });
2125     }
2127     /* Saves the monitor to localstorage */
2128     function saveMonitor() {
2129         var gridCopy = {};
2131         $.each(runtime.charts, function (key, elem) {
2132             gridCopy[key] = {};
2133             gridCopy[key].nodes = elem.nodes;
2134             gridCopy[key].settings = elem.settings;
2135             gridCopy[key].title = elem.title;
2136             gridCopy[key].series = elem.series;
2137             gridCopy[key].maxYLabel = elem.maxYLabel;
2138         });
2140         if (isStorageSupported('localStorage')) {
2141             window.localStorage.monitorCharts = JSON.stringify(gridCopy);
2142             window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
2143             window.localStorage.monitorVersion = monitorProtocolVersion;
2144         }
2146         $('a[href="#clearMonitorConfig"]').show();
2147     }
2150 // Run the monitor once loaded
2151 AJAX.registerOnload('server_status_monitor.js', function () {
2152     $('a[href="#pauseCharts"]').trigger('click');
2155 function serverResponseError() {
2156     var btns = {};
2157     btns[PMA_messages.strReloadPage] = function () {
2158         window.location.reload();
2159     };
2160     $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2161     $('#emptyDialog').html(
2162         PMA_getImage('s_attention.png') +
2163         PMA_messages.strInvalidResponseExplanation
2164     );
2165     $('#emptyDialog').dialog({ buttons: btns });
2168 /* Destroys all monitor related resources */
2169 function destroyGrid() {
2170     if (runtime.charts) {
2171         $.each(runtime.charts, function (key, value) {
2172             try {
2173                 value.chart.destroy();
2174             } catch (err) {}
2175         });
2176     }
2178     try {
2179         runtime.refreshRequest.abort();
2180     } catch (err) {}
2181     try {
2182         clearTimeout(runtime.refreshTimeout);
2183     } catch (err) {}
2184     $('#chartGrid').html('');
2185     runtime.charts = null;
2186     runtime.chartAI = 0;
2187     monitorSettings = null; //TODO:this not global variable