1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * @fileoverview functions used in server status pages
8 * @requires jQueryCookie
9 * @requires jQueryTablesorter
10 * @requires Highcharts
12 * @requires js/functions.js
16 // Add a tablesorter parser to properly handle thousands seperated numbers and SI prefixes
18 jQuery
.tablesorter
.addParser({
21 return /^[0-9]?[0-9,\.]*\s?(k|M|G|T|%)?$/.test(s
);
24 var num
= jQuery
.tablesorter
.formatFloat(
25 s
.replace(PMA_messages
['strThousandsSeperator'],'')
26 .replace(PMA_messages
['strDecimalSeperator'],'.')
30 switch (s
.charAt(s
.length
- 1)) {
31 case '%': factor
= -2; break;
32 // Todo: Complete this list (as well as in the regexp a few lines up)
33 case 'k': factor
= 3; break;
34 case 'M': factor
= 6; break;
35 case 'G': factor
= 9; break;
36 case 'T': factor
= 12; break;
39 return num
* Math
.pow(10,factor
);
46 $('a[rel="popupLink"]').click( function() {
49 $('.' + $link
.attr('href').substr(1))
51 .offset({ top
: $link
.offset().top
+ $link
.height() + 5, left
: $link
.offset().left
})
52 .addClass('openedPopup');
57 $(document
).click( function(event
) {
58 $('.openedPopup').each(function() {
60 var pos
= $(this).offset();
62 // Hide if the mouseclick is outside the popupcontent
63 if(event
.pageX
< pos
.left
|| event
.pageY
< pos
.top
|| event
.pageX
> pos
.left
+ $cnt
.outerWidth() || event
.pageY
> pos
.top
+ $cnt
.outerHeight())
64 $cnt
.hide().removeClass('openedPopup');
70 // Filters for status variables
72 var alertFilter
= false;
73 var categoryFilter
='';
75 var text
=''; // Holds filter text
76 var queryPieChart
= null;
78 /* Chart configuration */
79 // Defines what the tabs are currently displaying (realtime or data)
80 var tabStatus
= new Object();
81 // Holds the current chart instances for each tab
82 var tabChart
= new Object();
85 /*** Table sort tooltip ***/
87 var $tableSortHint
= $('<div class="dHint" style="display:none;">' + 'Click to sort' + '</div>');
88 $('body').append($tableSortHint
);
90 $('table.sortable thead th').live('mouseover mouseout',function(e
) {
91 if(e
.type
== 'mouseover') {
103 .hide(300,function() {
104 $(this).data('shown',false);
109 $(document
).mousemove(function(e
) {
110 if($tableSortHint
.data('shown') == true)
118 // Tell highcarts not to use UTC dates (global setting)
119 Highcharts
.setOptions({
130 $('#serverStatusTabs').tabs({
132 cookie
: { name
: 'pma_serverStatusTabs', expires
: 1 },
133 // Fixes line break in the menu bar when the page overflows and scrollbar appears
134 show: function() { menuResize(); }
137 // Fixes wrong tab height with floated elements. See also http://bugs.jqueryui.com/ticket/5601
138 $(".ui-widget-content:not(.ui-tabs):not(.ui-helper-clearfix)").addClass("ui-helper-clearfix");
140 // Initialize each tab
141 $('div.ui-tabs-panel').each(function() {
142 initTab($(this),null);
143 tabStatus
[$(this).attr('id')] = 'static';
146 // Display button links
147 $('div.buttonlinks').show();
149 // Handles refresh rate changing
150 $('.buttonlinks select').change(function() {
151 var chart
=tabChart
[$(this).parents('div.ui-tabs-panel').attr('id')];
153 // Clear current timeout and set timeout with the new refresh rate
154 clearTimeout(chart_activeTimeouts
[chart
.options
.chart
.renderTo
]);
155 if(chart
.options
.realtime
.postRequest
)
156 chart
.options
.realtime
.postRequest
.abort();
158 chart
.options
.realtime
.refreshRate
= 1000*parseInt(this.value
);
160 chart
.xAxis
[0].setExtremes(
161 new Date().getTime() - server_time_diff
- chart
.options
.realtime
.numMaxPoints
* chart
.options
.realtime
.refreshRate
,
162 new Date().getTime() - server_time_diff
,
166 chart_activeTimeouts
[chart
.options
.chart
.renderTo
] = setTimeout(
167 chart
.options
.realtime
.timeoutCallBack
,
168 chart
.options
.realtime
.refreshRate
172 // Ajax refresh of variables (always the first element in each tab)
173 $('.buttonlinks a.tabRefresh').click(function() {
174 // ui-tabs-panel class is added by the jquery tabs feature
175 var tab
=$(this).parents('div.ui-tabs-panel');
178 // Show ajax load icon
179 $(this).find('img').show();
181 $.get($(this).attr('href'),{ajax_request
:1},function(data
) {
182 $(that
).find('img').hide();
186 tabStatus
[tab
.attr('id')]='data';
192 /** Realtime charting of variables **/
194 // Live traffic charting
195 $('.buttonlinks a.livetrafficLink').click(function() {
196 // ui-tabs-panel class is added by the jquery tabs feature
197 var $tab
=$(this).parents('div.ui-tabs-panel');
198 var tabstat
= tabStatus
[$tab
.attr('id')];
200 if(tabstat
=='static' || tabstat
=='liveconnections') {
203 { name
: PMA_messages
['strChartKBSent'], data
: [] },
204 { name
: PMA_messages
['strChartKBReceived'], data
: [] }
206 title
: { text
: PMA_messages
['strChartServerTraffic'] },
207 realtime
: { url
:'server_status.php?' + url_query
,
209 callback: function(chartObj
, curVal
, lastVal
, numLoadedPoints
) {
210 if(lastVal
==null) return;
211 chartObj
.series
[0].addPoint(
212 { x
: curVal
.x
, y
: (curVal
.y_sent
- lastVal
.y_sent
) / 1024 },
214 numLoadedPoints
>= chartObj
.options
.realtime
.numMaxPoints
216 chartObj
.series
[1].addPoint(
217 { x
: curVal
.x
, y
: (curVal
.y_received
- lastVal
.y_received
) / 1024 },
219 numLoadedPoints
>= chartObj
.options
.realtime
.numMaxPoints
222 error: function() { serverResponseError(); }
226 setupLiveChart($tab
,this,settings
);
227 if(tabstat
== 'liveconnections')
228 $tab
.find('.buttonlinks a.liveconnectionsLink').html(PMA_messages
['strLiveConnChart']);
229 tabStatus
[$tab
.attr('id')]='livetraffic';
231 $(this).html(PMA_messages
['strLiveTrafficChart']);
232 setupLiveChart($tab
,this,null);
238 // Live connection/process charting
239 $('.buttonlinks a.liveconnectionsLink').click(function() {
240 var $tab
=$(this).parents('div.ui-tabs-panel');
241 var tabstat
= tabStatus
[$tab
.attr('id')];
243 if(tabstat
== 'static' || tabstat
== 'livetraffic') {
246 { name
: PMA_messages
['strChartConnections'], data
: [] },
247 { name
: PMA_messages
['strChartProcesses'], data
: [] }
249 title
: { text
: PMA_messages
['strChartConnectionsTitle'] },
250 realtime
: { url
:'server_status.php?'+url_query
,
252 callback: function(chartObj
, curVal
, lastVal
,numLoadedPoints
) {
253 if(lastVal
==null) return;
254 chartObj
.series
[0].addPoint(
255 { x
: curVal
.x
, y
: curVal
.y_conn
- lastVal
.y_conn
},
257 numLoadedPoints
>= chartObj
.options
.realtime
.numMaxPoints
259 chartObj
.series
[1].addPoint(
260 { x
: curVal
.x
, y
: curVal
.y_proc
},
262 numLoadedPoints
>= chartObj
.options
.realtime
.numMaxPoints
265 error: function() { serverResponseError(); }
269 setupLiveChart($tab
,this,settings
);
270 if(tabstat
== 'livetraffic')
271 $tab
.find('.buttonlinks a.livetrafficLink').html(PMA_messages
['strLiveTrafficChart']);
272 tabStatus
[$tab
.attr('id')]='liveconnections';
274 $(this).html(PMA_messages
['strLiveConnChart']);
275 setupLiveChart($tab
,this,null);
281 // Live query statistics
282 $('.buttonlinks a.livequeriesLink').click(function() {
283 var $tab
= $(this).parents('div.ui-tabs-panel');
286 if(tabStatus
[$tab
.attr('id')] == 'static') {
288 series
: [ { name
: PMA_messages
['strChartIssuedQueries'], data
: [] } ],
289 title
: { text
: PMA_messages
['strChartIssuedQueriesTitle'] },
290 tooltip
: { formatter:function() { return this.point
.name
; } },
291 realtime
: { url
:'server_status.php?'+url_query
,
293 callback: function(chartObj
, curVal
, lastVal
,numLoadedPoints
) {
294 if(lastVal
== null) return;
295 chartObj
.series
[0].addPoint(
296 { x
: curVal
.x
, y
: curVal
.y
- lastVal
.y
, name
: sortedQueriesPointInfo(curVal
,lastVal
) },
298 numLoadedPoints
>= chartObj
.options
.realtime
.numMaxPoints
301 error: function() { serverResponseError(); }
305 $(this).html(PMA_messages
['strLiveQueryChart']);
308 setupLiveChart($tab
,this,settings
);
309 tabStatus
[$tab
.attr('id')] = 'livequeries';
313 function setupLiveChart($tab
,link
,settings
) {
314 if(settings
!= null) {
315 // Loading a chart with existing chart => remove old chart first
316 if(tabStatus
[$tab
.attr('id')] != 'static') {
317 clearTimeout(chart_activeTimeouts
[$tab
.attr('id') + "_chart_cnt"]);
318 chart_activeTimeouts
[$tab
.attr('id')+"_chart_cnt"] = null;
319 tabChart
[$tab
.attr('id')].destroy();
320 // Also reset the select list
321 $tab
.find('.buttonlinks select').get(0).selectedIndex
= 2;
324 if(! settings
.chart
) settings
.chart
= {};
325 settings
.chart
.renderTo
= $tab
.attr('id') + "_chart_cnt";
327 $tab
.find('.tabInnerContent')
329 .after('<div class="liveChart" id="' + $tab
.attr('id') + '_chart_cnt"></div>');
330 tabChart
[$tab
.attr('id')] = PMA_createChart(settings
);
331 $(link
).html(PMA_messages
['strStaticData']);
332 $tab
.find('.buttonlinks a.tabRefresh').hide();
333 $tab
.find('.buttonlinks .refreshList').show();
335 clearTimeout(chart_activeTimeouts
[$tab
.attr('id') + "_chart_cnt"]);
336 chart_activeTimeouts
[$tab
.attr('id') + "_chart_cnt"]=null;
337 $tab
.find('.tabInnerContent').show();
338 $tab
.find('div#'+$tab
.attr('id') + '_chart_cnt').remove();
339 tabStatus
[$tab
.attr('id')]='static';
340 tabChart
[$tab
.attr('id')].destroy();
341 $tab
.find('.buttonlinks a.tabRefresh').show();
342 $tab
.find('.buttonlinks select').get(0).selectedIndex
=2;
343 $tab
.find('.buttonlinks .refreshList').hide();
347 /* 3 Filtering functions */
348 $('#filterAlert').change(function() {
349 alertFilter
= this.checked
;
353 $('#filterText').keyup(function(e
) {
354 word
= $(this).val().replace('_',' ');
356 if(word
.length
== 0) textFilter
= null;
357 else textFilter
= new RegExp("(^|_)" + word
,'i');
364 $('#filterCategory').change(function() {
365 categoryFilter
= $(this).val();
369 /* Adjust DOM / Add handlers to the tabs */
370 function initTab(tab
,data
) {
371 switch(tab
.attr('id')) {
372 case 'statustabs_traffic':
373 if(data
!= null) tab
.find('.tabInnerContent').html(data
);
374 PMA_convertFootnotesToTooltips();
376 case 'statustabs_queries':
378 queryPieChart
.destroy();
379 tab
.find('.tabInnerContent').html(data
);
382 // Build query statistics chart
383 var cdata
= new Array();
384 $.each(jQuery
.parseJSON($('#serverstatusquerieschart span').html()),function(key
,value
) {
385 cdata
.push([key
,parseInt(value
)]);
388 queryPieChart
= PMA_createChart({
390 renderTo
: 'serverstatusquerieschart'
398 name
: PMA_messages
['strChartQueryPie'],
403 allowPointSelect
: true,
407 formatter: function() {
408 return '<b>'+ this.point
.name
+'</b><br/> ' + Highcharts
.numberFormat(this.percentage
, 2) + ' %';
414 formatter: function() {
415 return '<b>' + this.point
.name
+ '</b><br/>' + Highcharts
.numberFormat(this.y
, 2) + '<br/>(' + Highcharts
.numberFormat(this.percentage
, 2) + ' %)';
421 case 'statustabs_allvars':
423 tab
.find('.tabInnerContent').html(data
);
429 initTableSorter(tab
.attr('id'));
432 function initTableSorter(tabid
) {
434 case 'statustabs_queries':
435 $('#serverstatusqueriesdetails').tablesorter({
439 1: { sorter
: 'fancyNumber' },
440 2: { sorter
: 'fancyNumber' }
444 $('#serverstatusqueriesdetails tr:first th')
445 .append('<img class="icon sortableIcon" src="themes/dot.gif" alt="">');
449 case 'statustabs_allvars':
450 $('#serverstatusvariables').tablesorter({
454 1: { sorter
: 'fancyNumber' }
458 $('#serverstatusvariables tr:first th')
459 .append('<img class="icon sortableIcon" src="themes/dot.gif" alt="">');
465 /* Filters the status variables by name/category/alert in the variables tab */
466 function filterVariables() {
467 var useful_links
= 0;
470 if(categoryFilter
.length
> 0) section
= categoryFilter
;
472 if(section
.length
> 1) {
473 $('#linkSuggestions span').each(function() {
474 if($(this).attr('class').indexOf('status_'+section
) != -1) {
476 $(this).css('display','');
478 $(this).css('display','none');
486 $('#linkSuggestions').css('display','');
487 else $('#linkSuggestions').css('display','none');
490 $('#serverstatusvariables th.name').each(function() {
491 if((textFilter
== null || textFilter
.exec($(this).text()))
492 && (! alertFilter
|| $(this).next().find('span.attention').length
>0)
493 && (categoryFilter
.length
== 0 || $(this).parent().hasClass('s_'+categoryFilter
))) {
495 $(this).parent().css('display','');
497 $(this).parent().addClass('odd');
498 $(this).parent().removeClass('even');
500 $(this).parent().addClass('even');
501 $(this).parent().removeClass('odd');
504 $(this).parent().css('display','none');
509 // Provides a nicely formatted and sorted tooltip of each datapoint of the query statistics
510 function sortedQueriesPointInfo(queries
, lastQueries
){
511 var max
, maxIdx
, num
=0;
512 var queryKeys
= new Array();
513 var queryValues
= new Array();
517 // Separate keys and values, then sort them
518 $.each(queries
.pointInfo
, function(key
,value
) {
519 if(value
-lastQueries
.pointInfo
[key
] > 0) {
521 queryValues
.push(value
-lastQueries
.pointInfo
[key
]);
522 sumTotal
+= value
-lastQueries
.pointInfo
[key
];
525 var numQueries
= queryKeys
.length
;
526 var pointInfo
= '<b>' + PMA_messages
['strTotal'] + ': ' + sumTotal
+ '</b><br>';
528 while(queryKeys
.length
> 0) {
530 for(var i
=0; i
< queryKeys
.length
; i
++) {
531 if(queryValues
[i
] > max
) {
532 max
= queryValues
[i
];
536 if(numQueries
> 8 && num
>= 6)
537 sumOther
+= queryValues
[maxIdx
];
538 else pointInfo
+= queryKeys
[maxIdx
].substr(4).replace('_',' ') + ': ' + queryValues
[maxIdx
] + '<br>';
540 queryKeys
.splice(maxIdx
,1);
541 queryValues
.splice(maxIdx
,1);
546 pointInfo
+= PMA_messages
['strOther'] + ': ' + sumOther
;
554 /**** Monitor charting implementation ****/
555 /* Saves the previous ajax response for differential values */
556 var oldChartData
= null;
557 // Holds about to created chart
561 // Runtime parameter of the monitor
563 // Holds all visible charts in the grid
565 // Current max points per chart (needed for auto calculation)
567 // displayed time frame
570 // Stores the timeout handler so it can be cleared
571 refreshTimeout
: null,
572 // Stores the GET request to refresh the charts
573 refreshRequest
: null,
574 // Chart auto increment
576 // To play/pause the monitor
578 // Object that contains a list of nodes that need to be retrieved from the server for chart updates
582 var monitorSettings
= null;
584 var defaultMonitorSettings
= {
586 chartSize
: { width
: 295, height
: 250 },
587 // Max points in each chart. Settings it to 'auto' sets gridMaxPoints to (chartwidth - 40) / 12
588 gridMaxPoints
: 'auto',
589 /* Refresh rate of all grid charts in ms */
593 // Allows drag and drop rearrange and print/edit icons on charts
594 var editMode
= false;
598 title
: PMA_messages
['strSystemCPUUsage'],
599 nodes
: [{ dataType
: 'cpu', name
: 'loadavg', unit
: '%'}]
602 title
: PMA_messages
['strSystemMemory'],
604 { dataType
: 'memory', name
: 'MemTotal', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
605 { dataType
: 'memory', name
: 'MemUsed', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
609 title
: PMA_messages
['strSystemSwap'],
611 { dataType
: 'memory', name
: 'SwapTotal', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
612 { dataType
: 'memory', name
: 'SwapUsed', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
616 title
: PMA_messages
['strSystemCPUUsage'],
619 name
: PMA_messages
['strAverageLoad'],
621 // Needs to be string so it is not ignored by $.toJSON()
623 'if(prev == null) return undefined;' +
624 'var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);' +
625 'var diff_idle = cur.idle - prev.idle;' +
626 'return 100*(diff_total - diff_idle) / diff_total;'
631 title
: PMA_messages
['strSystemMemory'],
633 { dataType
: 'memory', name
: 'MemUsed', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
634 { dataType
: 'memory', name
: 'Cached', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
635 { dataType
: 'memory', name
: 'Buffers', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
636 { dataType
: 'memory', name
: 'MemFree', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
651 title
: PMA_messages
['strSystemSwap'],
653 { dataType
: 'memory', name
: 'SwapUsed', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
654 { dataType
: 'memory', name
: 'SwapCached', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
655 { dataType
: 'memory', name
: 'SwapFree', valueDivisor
: 1024, unit
: PMA_messages
['strMiB'] },
673 'c0': { title
: PMA_messages
['strQuestions'],
674 nodes
: [{ dataType
: 'statusvar', name
: 'Questions', display
: 'differential' }]
677 title
: PMA_messages
['strChartConnectionsTitle'],
678 nodes
: [ { dataType
: 'statusvar', name
: 'Connections', display
: 'differential' },
679 { dataType
: 'proc', name
: 'Processes'} ]
682 title
: PMA_messages
['strTraffic'],
684 { dataType
: 'statusvar', name
: 'Bytes_sent', display
: 'differential', valueDivisor
: 1024, unit
: PMA_messages
['strKiB'] },
685 { dataType
: 'statusvar', name
: 'Bytes_received', display
: 'differential', valueDivisor
: 1024, unit
: PMA_messages
['strKiB'] }
690 // Server is localhost => We can add cpu/memory/swap
691 if(server_db_isLocal
) {
692 defaultChartGrid
['c3'] = presetCharts
['cpu-' + server_os
];
693 defaultChartGrid
['c4'] = presetCharts
['memory-' + server_os
];
694 defaultChartGrid
['c5'] = presetCharts
['swap-' + server_os
];
700 symbol
: 'url(' + pmaThemeImage
+ 's_cog.png)',
702 symbolFill
: '#B5C9DF',
703 hoverSymbolFill
: '#779ABF',
704 _titleKey
: 'settings',
705 menuName
: 'gridsettings',
707 textKey
: 'editChart',
708 onclick: function() {
712 textKey
: 'removeChart',
713 onclick: function() {
720 Highcharts
.setOptions({
722 settings
: PMA_messages
['strSettings'],
723 removeChart
: PMA_messages
['strRemoveChart'],
724 editChart
: PMA_messages
['strEditChart']
728 $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').click(function() {
729 editMode
= !editMode
;
730 if($(this).attr('href') == '#endChartEditMode') editMode
= false;
732 // Icon graphics have zIndex 19,20 and 21. Let's just hope nothing else has the same zIndex
733 $('table#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode
)
735 $('a[href="#endChartEditMode"]').toggle(editMode
);
738 // Close the settings popup
739 $('#statustabs_charting .popupContent').hide().removeClass('openedPopup');
741 $("#chartGrid").sortableTable({
744 left
: chartSize().width
- 63,
750 // console.log('start.');
752 // Drop event. The drag child element is moved into the drop element
753 // and vice versa. So the parameters are switched.
754 drop: function(drag
, drop
, pos
) {
755 var dragKey
, dropKey
, dropRender
;
756 var dragRender
= $(drag
).children().first().attr('id');
758 if($(drop
).children().length
> 0)
759 dropRender
= $(drop
).children().first().attr('id');
761 // Find the charts in the array
762 $.each(runtime
.charts
, function(key
, value
) {
763 if(value
.chart
.options
.chart
.renderTo
== dragRender
)
765 if(dropRender
&& value
.chart
.options
.chart
.renderTo
== dropRender
)
769 // Case 1: drag and drop are charts -> Switch keys
772 dragChart
= runtime
.charts
[dragKey
];
773 runtime
.charts
[dragKey
] = runtime
.charts
[dropKey
];
774 runtime
.charts
[dropKey
] = dragChart
;
776 // Case 2: drop is a empty cell => just completely rebuild the ids
778 var dropKeyNum
= parseInt(dropKey
.substr(1));
779 var insertBefore
= pos
.col
+ pos
.row
* monitorSettings
.columns
;
781 var newChartList
= {};
784 $.each(runtime
.charts
, function(key
, value
) {
791 // Rebuilds all ids, with the dragged chart correctly inserted
792 for(var i
=0; i
<keys
.length
; i
++) {
793 if(keys
[i
] == insertBefore
) {
794 newChartList
['c' + (c
++)] = runtime
.charts
[dropKey
];
795 insertBefore
= -1; // Insert ok
797 newChartList
['c' + (c
++)] = runtime
.charts
[keys
[i
]];
800 // Not inserted => put at the end
801 if(insertBefore
!= -1)
802 newChartList
['c' + (c
++)] = runtime
.charts
[dropKey
];
804 runtime
.charts
= newChartList
;
814 $("#chartGrid").sortableTable('destroy');
815 saveMonitor(); // Save settings
822 $('div#statustabs_charting div.popupContent select[name="chartColumns"]').change(function() {
823 monitorSettings
.columns
= parseInt(this.value
);
825 var newSize
= chartSize();
827 // Empty cells should keep their size so you can drop onto them
828 $('table#chartGrid tr td').css('width',newSize
.width
+ 'px');
830 /* Reorder all charts that it fills all column cells */
832 var $tr
= $('table#chartGrid tr:first');
834 while($tr
.length
!= 0) {
836 // To many cells in one row => put into next row
837 $tr
.find('td').each(function() {
838 if(numColumns
> monitorSettings
.columns
) {
839 if($tr
.next().length
== 0) $tr
.after('<tr></tr>');
840 $tr
.next().prepend($(this));
845 // To little cells in one row => for each cell to little, move all cells backwards by 1
846 if($tr
.next().length
> 0) {
847 var cnt
= monitorSettings
.columns
- $tr
.find('td').length
;
848 for(var i
=0; i
< cnt
; i
++) {
849 $tr
.append($tr
.next().find('td:first'));
850 $tr
.nextAll().each(function() {
851 if($(this).next().length
!= 0)
852 $(this).append($(this).next().find('td:first'));
861 /* Apply new chart size to all charts */
862 $.each(runtime
.charts
, function(key
, value
) {
870 if(monitorSettings
.gridMaxPoints
== 'auto')
871 runtime
.gridMaxPoints
= Math
.round((newSize
.width
- 40) / 12);
873 runtime
.xmin
= new Date().getTime() - server_time_diff
- runtime
.gridMaxPoints
* monitorSettings
.gridRefresh
;
874 runtime
.xmax
= new Date().getTime() - server_time_diff
+ monitorSettings
.gridRefresh
;
877 $("#chartGrid").sortableTable('refresh');
879 saveMonitor(); // Save settings
882 $('div#statustabs_charting div.popupContent select[name="gridChartRefresh"]').change(function() {
883 monitorSettings
.gridRefresh
= parseInt(this.value
) * 1000;
884 clearTimeout(runtime
.refreshTimeout
);
886 if(runtime
.refreshRequest
)
887 runtime
.refreshRequest
.abort();
889 runtime
.xmin
= new Date().getTime() - server_time_diff
- runtime
.gridMaxPoints
* monitorSettings
.gridRefresh
;
890 runtime
.xmax
= new Date().getTime() - server_time_diff
+ monitorSettings
.gridRefresh
;
892 $.each(runtime
.charts
, function(key
, value
) {
893 value
.chart
.xAxis
[0].setExtremes(runtime
.xmin
, runtime
.xmax
, false);
896 runtime
.refreshTimeout
= setTimeout(refreshChartGrid
, monitorSettings
.gridRefresh
);
898 saveMonitor(); // Save settings
901 $('a[href="#addNewChart"]').click(function() {
902 var dlgButtons
= { };
904 dlgButtons
[PMA_messages
['strAddChart']] = function() {
905 var type
= $('input[name="chartType"]:checked').val();
907 if(type
== 'cpu' || type
== 'memory' || type
=='swap')
908 newChart
= presetCharts
[type
+ '-' + server_os
];
910 if(! newChart
|| ! newChart
.nodes
|| newChart
.nodes
.length
== 0) {
911 alert(PMA_messages
['strAddOneSeriesWarning']);
916 newChart
.title
= $('input[name="chartTitle"]').attr('value');
917 // Add a cloned object to the chart grid
918 addChart($.extend(true, {}, newChart
));
922 saveMonitor(); // Save settings
924 $(this).dialog("close");
927 dlgButtons
[PMA_messages
['strClose']] = function() {
929 $('span#clearSeriesLink').hide();
930 $('#seriesPreview').html('');
931 $(this).dialog("close");
934 $('div#addChartDialog').dialog({
940 $('div#addChartDialog #seriesPreview').html('<i>' + PMA_messages
['strNone'] + '</i>');
945 $('a[href="#pauseCharts"]').click(function() {
946 runtime
.redrawCharts
= ! runtime
.redrawCharts
;
947 if(! runtime
.redrawCharts
)
948 $(this).html('<img src="themes/dot.gif" class="icon ic_play" alt="" /> ' + PMA_messages
['strResumeMonitor']);
950 $(this).html('<img src="themes/dot.gif" class="icon ic_pause" alt="" /> ' + PMA_messages
['strPauseMonitor']);
951 if(runtime
.charts
== null) {
953 $('a[href="#settingsPopup"]').show();
959 $('a[href="#monitorInstructionsDialog"]').click(function() {
960 var $dialog
= $('div#monitorInstructionsDialog');
965 }).find('img.ajaxIcon').show();
967 var loadLogVars = function(getvars
) {
968 vars
= { ajax_request
: true, logging_vars
: true };
969 if(getvars
) $.extend(vars
,getvars
);
971 $.get('server_status.php?' + url_query
, vars
,
973 var logVars
= $.parseJSON(data
),
974 icon
= 'ic_s_success', msg
='', str
='';
976 if(logVars
['general_log'] == 'ON') {
977 if(logVars
['slow_query_log'] == 'ON')
978 msg
= PMA_messages
['strBothLogOn'];
980 msg
= PMA_messages
['strGenLogOn'];
983 if(msg
.length
== 0 && logVars
['slow_query_log'] == 'ON') {
984 msg
= PMA_messages
['strSlowLogOn'];
987 if(msg
.length
== 0) {
989 msg
= PMA_messages
['strBothLogOff'];
992 str
= '<b>' + PMA_messages
['strCurrentSettings'] + '</b><br><div class="smallIndent">';
993 str
+= '<img src="themes/dot.gif" class="icon ' + icon
+ '" alt=""/> ' + msg
+ '<br />';
995 if(logVars
['log_output'] != 'TABLE')
996 str
+= '<img src="themes/dot.gif" class="icon ic_s_error" alt=""/> ' + PMA_messages
['strLogOutNotTable'] + '<br />';
998 str
+= '<img src="themes/dot.gif" class="icon ic_s_success" alt=""/> ' + PMA_messages
['strLogOutIsTable'] + '<br />';
1000 if(logVars
['slow_query_log'] == 'ON') {
1001 if(logVars
['long_query_time'] > 2)
1002 str
+= '<img src="themes/dot.gif" class="icon ic_s_attention" alt=""/> '
1003 + $.sprintf(PMA_messages
['strSmallerLongQueryTimeAdvice'], logVars
['long_query_time'])
1006 if(logVars
['long_query_time'] < 2)
1007 str
+= '<img src="themes/dot.gif" class="icon ic_s_success" alt=""/> '
1008 + $.sprintf(PMA_messages
['strLongQueryTimeSet'], logVars
['long_query_time'])
1015 str
+= '<p></p><b>Change settings</b>';
1016 str
+= '<div class="smallIndent">';
1017 str
+= PMA_messages
['strSettingsAppliedGlobal'] + '<br/>';
1019 var varValue
= 'TABLE';
1020 if(logVars
['log_output'] == 'TABLE') varValue
= 'FILE';
1022 str
+= '- <a class="set" href="#log_output-' + varValue
+ '">'
1023 + $.sprintf(PMA_messages
['strSetLogOutput'], varValue
)
1026 if(logVars
['general_log'] != 'ON')
1027 str
+= '- <a class="set" href="#general_log-ON">'
1028 + $.sprintf(PMA_messages
['strEnableVar'], 'general_log')
1031 str
+= '- <a class="set" href="#general_log-OFF">'
1032 + $.sprintf(PMA_messages
['strDisableVar'], 'general_log')
1035 if(logVars
['slow_query_log'] != 'ON')
1036 str
+= '- <a class="set" href="#slow_query_log-ON">'
1037 + $.sprintf(PMA_messages
['strEnableVar'], 'slow_query_log')
1040 str
+= '- <a class="set" href="#slow_query_log-OFF">'
1041 + $.sprintf(PMA_messages
['strDisableVar'], 'slow_query_log')
1046 if(logVars
['long_query_time'] > 2) varValue
= 1;
1048 str
+= '- <a class="set" href="#long_query_time-' + varValue
+ '">'
1049 + $.sprintf(PMA_messages
['setSetLongQueryTime'], varValue
)
1053 str
+= PMA_messages
['strNoSuperUser'] + '<br/>';
1057 $dialog
.find('div.monitorUse').toggle(
1058 logVars
['log_output'] == 'TABLE' && (logVars
['slow_query_log'] == 'ON' || logVars
['general_log'] == 'ON')
1061 $dialog
.find('div.ajaxContent').html(str
);
1062 $dialog
.find('img.ajaxIcon').hide();
1063 $dialog
.find('a.set').click(function() {
1064 var nameValue
= $(this).attr('href').split('-');
1065 loadLogVars({ varName
: nameValue
[0].substr(1), varValue
: nameValue
[1]});
1066 $dialog
.find('img.ajaxIcon').show();
1078 $('input[name="chartType"]').change(function() {
1079 $('#chartVariableSettings').toggle(this.checked
&& this.value
== 'variable');
1080 var title
= $('input[name="chartTitle"]').attr('value');
1081 if(title
== PMA_messages
['strChartTitle'] || title
== $('label[for="'+$('input[name="chartTitle"]').data('lastRadio')+'"]').text()) {
1082 $('input[name="chartTitle"]').data('lastRadio',$(this).attr('id'));
1083 $('input[name="chartTitle"]').attr('value',$('label[for="'+$(this).attr('id')+'"]').text());
1088 $('input[name="useDivisor"]').change(function() {
1089 $('span.divisorInput').toggle(this.checked
);
1091 $('input[name="useUnit"]').change(function() {
1092 $('span.unitInput').toggle(this.checked
);
1095 $('select[name="varChartList"]').change(function () {
1096 if(this.selectedIndex
!=0)
1097 $('#variableInput').attr('value',this.value
);
1100 $('a[href="#kibDivisor"]').click(function() {
1101 $('input[name="valueDivisor"]').attr('value',1024);
1102 $('input[name="valueUnit"]').attr('value',PMA_messages
['strKiB']);
1103 $('span.unitInput').toggle(true);
1104 $('input[name="useUnit"]').prop('checked',true);
1108 $('a[href="#mibDivisor"]').click(function() {
1109 $('input[name="valueDivisor"]').attr('value',1024*1024);
1110 $('input[name="valueUnit"]').attr('value',PMA_messages
['strMiB']);
1111 $('span.unitInput').toggle(true);
1112 $('input[name="useUnit"]').prop('checked',true);
1116 $('a[href="#submitClearSeries"]').click(function() {
1117 $('#seriesPreview').html('<i>' + PMA_messages
['strNone'] + '</i>');
1119 $('span#clearSeriesLink').hide();
1122 $('a[href="#submitAddSeries"]').click(function() {
1123 if($('input#variableInput').attr('value').length
== 0) return false;
1125 if(newChart
== null) {
1126 $('#seriesPreview').html('');
1129 title
: $('input[name="chartTitle"]').attr('value'),
1135 dataType
:'statusvar',
1136 name
: $('input#variableInput').attr('value'),
1137 display
: $('input[name="differentialValue"]').attr('checked') ? 'differential' : ''
1140 if(serie
.name
== 'Processes') serie
.dataType
='proc';
1142 if($('input[name="useDivisor"]').attr('checked'))
1143 serie
.valueDivisor
= parseInt($('input[name="valueDivisor"]').attr('value'));
1145 if($('input[name="useUnit"]').attr('checked'))
1146 serie
.unit
= $('input[name="valueUnit"]').attr('value');
1150 var str
= serie
.display
== 'differential' ? ', ' + PMA_messages
['strDifferential'] : '';
1151 str
+= serie
.valueDivisor
? (', ' + $.sprintf(PMA_messages
['strDividedBy'], serie
.valueDivisor
)) : '';
1153 $('#seriesPreview').append('- ' + serie
.name
+ str
+ '<br>');
1155 newChart
.nodes
.push(serie
);
1157 $('input#variableInput').attr('value','');
1158 $('input[name="differentialValue"]').attr('checked',true);
1159 $('input[name="useDivisor"]').attr('checked',false);
1160 $('input[name="useUnit"]').attr('checked',false);
1161 $('input[name="useDivisor"]').trigger('change');
1162 $('input[name="useUnit"]').trigger('change');
1163 $('select[name="varChartList"]').get(0).selectedIndex
=0;
1165 $('span#clearSeriesLink').show();
1170 $("input#variableInput").autocomplete({
1171 source
: variableNames
1175 function initGrid() {
1179 /* Apply default values & config */
1180 if(window
.localStorage
) {
1181 if(window
.localStorage
['monitorCharts'])
1182 runtime
.charts
= $.parseJSON(window
.localStorage
['monitorCharts']);
1183 if(window
.localStorage
['monitorSettings'])
1184 monitorSettings
= $.parseJSON(window
.localStorage
['monitorSettings']);
1186 $('a[href="#clearMonitorConfig"]').toggle(runtime
.charts
!= null);
1189 if(runtime
.charts
== null)
1190 runtime
.charts
= defaultChartGrid
;
1191 if(monitorSettings
== null)
1192 monitorSettings
= defaultMonitorSettings
;
1194 $('select[name="gridChartRefresh"]').attr('value',monitorSettings
.gridRefresh
/ 1000);
1195 $('select[name="chartColumns"]').attr('value',monitorSettings
.columns
);
1197 if(monitorSettings
.gridMaxPoints
== 'auto')
1198 runtime
.gridMaxPoints
= Math
.round((monitorSettings
.chartSize
.width
- 40) / 12);
1200 runtime
.gridMaxPoints
= monitorSettings
.gridMaxPoints
;
1202 runtime
.xmin
= new Date().getTime() - server_time_diff
- runtime
.gridMaxPoints
* monitorSettings
.gridRefresh
;
1203 runtime
.xmax
= new Date().getTime() - server_time_diff
+ monitorSettings
.gridRefresh
;
1205 /* Calculate how much spacing there is between each chart */
1206 $('table#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
1208 width
: $('table#chartGrid td:nth-child(2)').offset().left
- $('table#chartGrid td:nth-child(1)').offset().left
,
1209 height
: $('table#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top
- $('table#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top
1211 $('table#chartGrid').html('');
1213 /* Add all charts - in correct order */
1215 $.each(runtime
.charts
, function(key
, value
) {
1219 for(var i
=0; i
<keys
.length
; i
++)
1220 addChart(runtime
.charts
[keys
[i
]],true);
1222 /* Fill in missing cells */
1223 var numCharts
= $('table#chartGrid .monitorChart').length
;
1224 var numMissingCells
= (monitorSettings
.columns
- numCharts
% monitorSettings
.columns
) % monitorSettings
.columns
;
1225 for(var i
=0; i
< numMissingCells
; i
++) {
1226 $('table#chartGrid tr:last').append('<td></td>');
1229 // Empty cells should keep their size so you can drop onto them
1230 $('table#chartGrid tr td').css('width',chartSize().width
+ 'px');
1233 buildRequiredDataList();
1237 function chartSize() {
1238 var wdt
= $('div#logTable').innerWidth() / monitorSettings
.columns
- (monitorSettings
.columns
- 1) * chartSpacing
.width
;
1245 function addChart(chartObj
, initialize
) {
1247 for(var j
=0; j
<chartObj
.nodes
.length
; j
++)
1248 series
.push(chartObj
.nodes
[j
]);
1252 renderTo
: 'gridchart' + runtime
.chartAI
,
1253 width
: chartSize().width
,
1254 height
: chartSize().height
,
1258 selection: function(event
) {
1259 if(editMode
) return false;
1261 var extremesObject
= event
.xAxis
[0],
1262 min
= extremesObject
.min
,
1263 max
= extremesObject
.max
;
1265 $('#logAnalyseDialog input[name="dateStart"]')
1266 .attr('value', Highcharts
.dateFormat('%Y-%m-%d %H:%M:%S', new Date(min
)));
1267 $('#logAnalyseDialog input[name="dateEnd"]')
1268 .attr('value', Highcharts
.dateFormat('%Y-%m-%d %H:%M:%S', new Date(max
)));
1272 dlgBtns
[PMA_messages
['strFromSlowLog']] = function() {
1273 var dateStart
= Date
.parse($('#logAnalyseDialog input[name="dateStart"]').attr('value')) || min
;
1274 var dateEnd
= Date
.parse($('#logAnalyseDialog input[name="dateEnd"]').attr('value')) || max
;
1280 removeVariables
: $('input#removeVariables').prop('checked'),
1281 limitTypes
: $('input#limitTypes').prop('checked')
1284 $('#logAnalyseDialog').find('dateStart,dateEnd').datepicker('destroy');
1286 $(this).dialog("close");
1289 dlgBtns
[PMA_messages
['strFromGeneralLog']] = function() {
1290 var dateStart
= Date
.parse($('#logAnalyseDialog input[name="dateStart"]').attr('value')) || min
;
1291 var dateEnd
= Date
.parse($('#logAnalyseDialog input[name="dateEnd"]').attr('value')) || max
;
1297 removeVariables
: $('input#removeVariables').prop('checked'),
1298 limitTypes
: $('input#limitTypes').prop('checked')
1301 $('#logAnalyseDialog').find('dateStart,dateEnd').datepicker('destroy');
1303 $(this).dialog("close");
1306 $('#logAnalyseDialog').dialog({
1327 formatter: function() {
1328 var s
= '<b>'+Highcharts
.dateFormat('%H:%M:%S', this.x
)+'</b>';
1330 $.each(this.points
, function(i
, point
) {
1331 s
+= '<br/><span style="color:'+point
.series
.color
+'">'+ point
.series
.name
+':</span> '+
1332 ((parseInt(point
.y
) == point
.y
) ? point
.y
: Highcharts
.numberFormat(this.y
, 2)) + ' ' + (point
.series
.options
.unit
|| '');
1343 buttons
: gridbuttons
,
1344 title
: { text
: chartObj
.title
}
1347 if(chartObj
.settings
)
1348 $.extend(true,settings
,chartObj
.settings
);
1350 if($('#'+settings
.chart
.renderTo
).length
==0) {
1351 var numCharts
= $('table#chartGrid .monitorChart').length
;
1353 if(numCharts
== 0 || !( numCharts
% monitorSettings
.columns
))
1354 $('table#chartGrid').append('<tr></tr>');
1356 $('table#chartGrid tr:last').append('<td><div class="ui-state-default monitorChart" id="'+settings
.chart
.renderTo
+'"></div></td>');
1359 chartObj
.chart
= PMA_createChart(settings
);
1360 chartObj
.numPoints
= 0;
1362 if(initialize
!= true) {
1363 runtime
.charts
['c'+runtime
.chartAI
] = chartObj
;
1364 buildRequiredDataList();
1367 // Edit,Print icon only in edit mode
1368 $('table#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode
)
1373 function removeChart(chartObj
) {
1374 var htmlnode
= chartObj
.options
.chart
.renderTo
;
1375 if(! htmlnode
) return;
1377 $.each(runtime
.charts
, function(key
, value
) {
1378 if(value
.chart
.options
.chart
.renderTo
== htmlnode
) {
1379 delete runtime
.charts
[key
];
1384 buildRequiredDataList();
1386 // Using settimeout() because clicking the remove link fires an onclick event
1387 // which throws an error when the chart is destroyed
1388 setTimeout(function() {
1390 $('div#' + htmlnode
).remove();
1393 saveMonitor(); // Save settings
1396 function refreshChartGrid() {
1397 /* Send to server */
1398 runtime
.refreshRequest
= $.post('server_status.php?'+url_query
, { ajax_request
: true, chart_data
: 1, type
: 'chartgrid', requiredData
: $.toJSON(runtime
.dataList
) },function(data
) {
1401 chartData
= $.parseJSON(data
);
1403 return serverResponseError();
1408 /* Update values in each graph */
1409 $.each(runtime
.charts
, function(orderKey
, elem
) {
1410 var key
= elem
.chartID
;
1411 // If newly added chart, we have no data for it yet
1412 if(! chartData
[key
]) return;
1414 for(var j
=0; j
< elem
.nodes
.length
; j
++) {
1415 value
= chartData
[key
][j
].y
;
1418 if(oldChartData
==null) diff
= chartData
.x
- runtime
.xmax
;
1419 else diff
= parseInt(chartData
.x
- oldChartData
.x
);
1421 runtime
.xmin
+= diff
;
1422 runtime
.xmax
+= diff
;
1425 elem
.chart
.xAxis
[0].setExtremes(runtime
.xmin
, runtime
.xmax
, false);
1427 if(elem
.nodes
[j
].display
== 'differential') {
1428 if(oldChartData
== null || oldChartData
[key
] == null) continue;
1429 value
-= oldChartData
[key
][j
].y
;
1432 if(elem
.nodes
[j
].valueDivisor
)
1433 value
= value
/ elem
.nodes
[j
].valueDivisor
;
1435 if(elem
.nodes
[j
].transformFn
) {
1436 value
= eval('(function(cur, prev) { ' + elem
.nodes
[j
].transformFn
+ '})(' +
1437 'chartData[key][j],' + (oldChartData
== null ? 'null' : 'oldChartData[key][j]') + ')');
1441 if(value
!= undefined)
1442 elem
.chart
.series
[j
].addPoint(
1443 { x
: chartData
.x
, y
: value
},
1445 elem
.numPoints
>= runtime
.gridMaxPoints
1451 runtime
.charts
[orderKey
].numPoints
++;
1452 if(runtime
.redrawCharts
)
1453 elem
.chart
.redraw();
1456 oldChartData
= chartData
;
1458 runtime
.refreshTimeout
= setTimeout(refreshChartGrid
, monitorSettings
.gridRefresh
);
1462 /* Build list of nodes that need to be retrieved */
1463 function buildRequiredDataList() {
1464 runtime
.dataList
= {};
1465 // Store an own id, because the property name is subject of reordering, thus destroying our mapping with runtime.charts <=> runtime.dataList
1467 $.each(runtime
.charts
, function(key
, chart
) {
1468 runtime
.dataList
[chartID
] = chart
.nodes
;
1469 runtime
.charts
[key
].chartID
= chartID
;
1474 function loadLogStatistics(opts
) {
1476 var logRequest
= null;
1478 if(! opts
.removeVariables
)
1479 opts
.removeVariables
= false;
1480 if(! opts
.limitTypes
)
1481 opts
.limitTypes
= false;
1483 $('#emptyDialog').html(PMA_messages
['strAnalysingLogs'] + ' <img class="ajaxIcon" src="' + pmaThemeImage
+ 'ajax_clock_small.gif" alt="">');
1485 $('#emptyDialog').dialog({
1489 'Cancel request': function() {
1490 if(logRequest
!= null)
1493 $(this).dialog("close");
1499 logRequest
= $.get('server_status.php?'+url_query
,
1500 { ajax_request
: true,
1503 time_start
: Math
.round(opts
.start
/ 1000),
1504 time_end
: Math
.round(opts
.end
/ 1000),
1505 removeVariables
: opts
.removeVariables
,
1506 limitTypes
: opts
.limitTypes
1511 logData
= $.parseJSON(data
);
1513 return serverResponseError();
1516 if(logData
.rows
.length
!= 0) {
1517 runtime
.logDataCols
= buildLogTable(logData
);
1519 /* Show some stats in the dialog */
1520 $('#emptyDialog').attr('title', PMA_messages
['strLoadingLogs']);
1521 $('#emptyDialog').html('<p>' + PMA_messages
['strLogDataLoaded'] + '</p>');
1522 $.each(logData
.sum
, function(key
, value
) {
1523 key
= key
.charAt(0).toUpperCase() + key
.slice(1).toLowerCase();
1524 if(key
== 'Total') key
= '<b>' + key
+ '</b>';
1525 $('#emptyDialog').append(key
+ ': ' + value
+ '<br/>');
1528 /* Add filter options if more than a bunch of rows there to filter */
1529 if(logData
.numRows
> 12) {
1530 $('div#logTable').prepend(
1531 '<fieldset id="logDataFilter">' +
1532 ' <legend>' + PMA_messages
['strFilters'] + '</legend>' +
1533 ' <div class="formelement">' +
1534 ' <label for="filterQueryText">' + PMA_messages
['strFilterByWordRegexp'] + '</label>' +
1535 ' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1537 ((logData
.numRows
> 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages
['strFilter'] + '</button></div>' : '') +
1538 ' <div class="formelement">' +
1539 ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1540 ' <label for="noWHEREData"> ' + PMA_messages
['strIgnoreWhereAndGroup'] + '</label>' +
1545 $('div#logTable input#noWHEREData').change(function() {
1546 filterQueries(true);
1549 //preg_replace('/\s+([^=]+)=(\d+|((\'|"|)(?U)(.+)(?<!\\\)\4(\s+|$)))/i',' $1={} ',$str);
1551 if(logData
.numRows
> 250) {
1552 $('div#logTable button#startFilterQueryText').click(filterQueries
);
1554 $('div#logTable input#filterQueryText').keyup(filterQueries
);
1560 dlgBtns
[PMA_messages
['strJumpToTable']] = function() {
1561 $(this).dialog("close");
1562 $(document
).scrollTop($('div#logTable').offset().top
);
1565 $('#emptyDialog').dialog( "option", "buttons", dlgBtns
);
1568 $('#emptyDialog').html('<p>' + PMA_messages
['strNoDataFound'] + '</p>');
1571 dlgBtns
[PMA_messages
['strClose']] = function() {
1572 $(this).dialog("close");
1575 $('#emptyDialog').dialog( "option", "buttons", dlgBtns
);
1580 function filterQueries(varFilterChange
) {
1581 var odd_row
=false, cell
, textFilter
;
1582 var val
= $('div#logTable input#filterQueryText').val();
1584 if(val
.length
== 0) textFilter
= null;
1585 else textFilter
= new RegExp(val
, 'i');
1587 var rowSum
= 0, totalSum
= 0, i
=0, q
;
1588 var noVars
= $('div#logTable input#noWHEREData').attr('checked');
1589 var equalsFilter
= /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1590 var functionFilter
= /([a-z0-9_]+)\(.+?\)/gi;
1591 var filteredQueries
= {};
1592 var filteredQueriesLines
= {};
1593 var hide
= false, rowData
;
1594 var queryColumnName
= runtime
.logDataCols
[runtime
.logDataCols
.length
- 2];
1595 var sumColumnName
= runtime
.logDataCols
[runtime
.logDataCols
.length
- 1];
1597 var isSlowLog
= opts
.src
== 'slow';
1598 var columnSums
= {};
1600 var countRow = function(query
, row
) {
1601 var cells
= row
.match(/<td>(.*?)<\/td>/gi);
1602 if(!columnSums
[query
]) columnSums
[query
] = [0,0,0,0];
1604 columnSums
[query
][0] += timeToSec(cells
[2].replace(/(<td>|<\/td>)/gi,''));
1605 columnSums
[query
][1] += timeToSec(cells
[3].replace(/(<td>|<\/td>)/gi,''));
1606 columnSums
[query
][2] += parseInt(cells
[4].replace(/(<td>|<\/td>)/gi,''));
1607 columnSums
[query
][3] += parseInt(cells
[5].replace(/(<td>|<\/td>)/gi,''));
1610 // We just assume the sql text is always in the second last column, and that the total count is right of it
1611 $('div#logTable table tbody tr td:nth-child(' + (runtime
.logDataCols
.length
- 1) + ')').each(function() {
1612 if(varFilterChange
&& $(this).html().match(/^SELECT/i)) {
1614 q
= $(this).text().replace(equalsFilter
, '$1=...$6').trim();
1615 q
= q
.replace(functionFilter
, ' $1(...)');
1617 // Js does not specify a limit on property name length, so we can abuse it as index :-)
1618 if(filteredQueries
[q
]) {
1619 filteredQueries
[q
] += parseInt($(this).next().text());
1620 totalSum
+= parseInt($(this).next().text());
1623 filteredQueries
[q
] = parseInt($(this).next().text());;
1624 filteredQueriesLines
[q
] = i
;
1627 if(isSlowLog
) countRow(q
, $(this).parent().html());
1629 // Restore original columns
1631 rowData
= $(this).parent().data('query');
1634 $(this).text(rowData
[queryColumnName
]);
1636 $(this).next().text(rowData
[sumColumnName
]);
1639 $(this).parent().children('td:nth-child(3)').text(rowData
['query_time']);
1640 $(this).parent().children('td:nth-child(4)').text(rowData
['lock_time']);
1641 $(this).parent().children('td:nth-child(5)').text(rowData
['rows_sent']);
1642 $(this).parent().children('td:nth-child(6)').text(rowData
['rows_examined']);
1647 if(! hide
&& (textFilter
!= null && ! textFilter
.exec($(this).text()))) hide
= true;
1650 $(this).parent().css('display','none');
1652 totalSum
+= parseInt($(this).next().text());
1655 odd_row
= ! odd_row
;
1656 $(this).parent().css('display','');
1658 $(this).parent().addClass('odd');
1659 $(this).parent().removeClass('even');
1661 $(this).parent().addClass('even');
1662 $(this).parent().removeClass('odd');
1670 // Update count values of grouped entries
1671 if(varFilterChange
) {
1673 var numCol
, row
, $table
= $('div#logTable table tbody');
1674 $.each(filteredQueriesLines
, function(key
,value
) {
1675 if(filteredQueries
[key
] <= 1) return;
1677 row
= $table
.children('tr:nth-child(' + (value
+1) + ')');
1678 numCol
= row
.children(':nth-child(' + (runtime
.logDataCols
.length
) + ')');
1679 numCol
.text(filteredQueries
[key
]);
1682 row
.children('td:nth-child(3)').text(secToTime(columnSums
[key
][0]));
1683 row
.children('td:nth-child(4)').text(secToTime(columnSums
[key
][1]));
1684 row
.children('td:nth-child(5)').text(columnSums
[key
][2]);
1685 row
.children('td:nth-child(6)').text(columnSums
[key
][3]);
1690 $('div#logTable table').trigger("update");
1691 setTimeout(function() {
1692 $('div#logTable table').trigger('sorton',[[[runtime
.logDataCols
.length
- 1,1]]]);
1696 $('div#logTable table tfoot tr')
1697 .html('<th colspan="' + (runtime
.logDataCols
.length
- 1) + '">' +
1698 PMA_messages
['strSumRows'] + ' '+ rowSum
+'<span style="float:right">' +
1699 PMA_messages
['strTotal'] + '</span></th><th align="right">' + totalSum
+ '</th>');
1703 /*loadLogStatistics({
1705 start:1311076210*1000,
1706 end:1311162689*1000,
1707 removeVariables: true,
1711 function timeToSec(timeStr
) {
1712 var time
= timeStr
.split(':');
1713 return parseInt(time
[0]*3600) + parseInt(time
[1]*60) + parseInt(time
[2]);
1716 function secToTime(timeInt
) {
1717 hours
= Math
.floor(timeInt
/ 3600);
1718 timeInt
-= hours
*3600;
1719 minutes
= Math
.floor(timeInt
/ 60);
1720 timeInt
-= minutes
*60;
1722 if(hours
< 10) hours
= '0' + hours
;
1723 if(minutes
< 10) minutes
= '0' + minutes
;
1724 if(timeInt
< 10) timeInt
= '0' + timeInt
;
1726 return hours
+ ':' + minutes
+ ':' + timeInt
;
1729 function buildLogTable(data
) {
1730 var rows
= data
.rows
;
1731 var cols
= new Array();
1732 var $table
= $('<table border="0" class="sortable"></table>');
1733 var $tBody
, $tRow
, $tCell
;
1735 $('#logTable').html($table
);
1737 var formatValue = function(name
, value
) {
1740 return value
.replace(/(\[.*?\])+/g,'');
1745 for(var i
=0; i
< rows
.length
; i
++) {
1747 $.each(rows
[0],function(key
, value
) {
1750 $table
.append( '<thead>' +
1751 '<tr><th class="nowrap">' + cols
.join('</th><th class="nowrap">') + '</th></tr>' +
1754 $table
.append($tBody
= $('<tbody></tbody>'));
1757 $tBody
.append($tRow
= $('<tr class="noclick"></tr>'));
1759 for(var j
=0; j
< cols
.length
; j
++) {
1760 // Assuming the query column is the second last
1761 if(j
== cols
.length
- 2 && rows
[i
][cols
[j
]].match(/^SELECT/i)) {
1762 $tRow
.append($tCell
=$('<td class="analyzableQuery">' + formatValue(cols
[j
], rows
[i
][cols
[j
]]) + '</td>'));
1763 $tCell
.click(queryAnalyzer
);
1765 $tRow
.append('<td>' + formatValue(cols
[j
], rows
[i
][cols
[j
]]) + '</td>');
1768 $tRow
.data('query',rows
[i
]);
1772 $table
.append('<tfoot>' +
1773 '<tr><th colspan="' + (cols
.length
- 1) + '">' + PMA_messages
['strSumRows'] +
1774 ' '+ data
.numRows
+'<span style="float:right">' + PMA_messages
['strTotal'] +
1775 '</span></th><th align="right">' + data
.sum
.TOTAL
+ '</th></tr></tfoot>');
1778 function queryAnalyzer() {
1779 var query
= $(this).parent().data('query')[cols
[cols
.length
-2]];
1781 /* A very basic SQL Formatter. Totally fails in the cases of
1782 - Any string appearance containing a MySQL Keyword, surrounded by whitespaces
1783 - Subqueries too probably
1785 // .* selector doesn't includde whitespace, [^] doesn't work in IE8, thus we use [^\0] since the zero-byte char (hopefully) doesn't appear in table names ;)
1786 var sLists
= query
.match(/SELECT\s+[^\0]+\s+FROM\s+/gi);
1788 for(var i
=0; i
< sLists
.length
; i
++) {
1789 query
= query
.replace(sLists
[i
],sLists
[i
].replace(/\s*((`|'|"|).*?\1,)\s*/gi,'$1\n\t'));
1792 .replace(/(\s+|^)(SELECT|FROM|WHERE|GROUP BY|HAVING|ORDER BY|LIMIT)(\s+|$)/gi,'\n$2\n\t')
1793 .replace(/\s+UNION\s+/gi,'\n\nUNION\n\n')
1794 .replace(/\s+(AND)\s+/gi,' $1\n\t')
1798 codemirror_editor
.setValue(query
);
1800 var profilingChart
= null;
1802 $('div#queryAnalyzerDialog').dialog({
1807 'Analyse Query' : function() {
1808 $('div#queryAnalyzerDialog div.placeHolder').html('Analyzing... ' + '<img class="ajaxIcon" src="' + pmaThemeImage
+ 'ajax_clock_small.gif" alt="">');
1810 $.post('server_status.php?'+url_query
, {
1812 query_analyzer
: true,
1813 query
: codemirror_editor
.getValue()
1815 data
= $.parseJSON(data
);
1819 $('div#queryAnalyzerDialog div.placeHolder').html('<div class="error">' + data
.error
+ '</div>');
1823 // Float sux, I'll use table :(
1824 $('div#queryAnalyzerDialog div.placeHolder')
1825 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
1827 var explain
= '<b>Explain output</b><p></p>';
1828 $.each(data
.explain
, function(key
,value
) {
1829 value
= (value
==null)?'null':value
;
1831 explain
+= key
+': ' + value
+ '<br />';
1833 $('div#queryAnalyzerDialog div.placeHolder td.explain').append(explain
);
1835 if(data
.profiling
) {
1837 var numberTable
= '<table class="queryNums"><thead><tr><th>Status</th><th>Time</th></tr></thead><tbody>';
1840 for(var i
=0; i
< data
.profiling
.length
; i
++) {
1841 duration
= parseFloat(data
.profiling
[i
].duration
);
1843 chartData
.push([data
.profiling
[i
].state
, duration
]);
1844 totalTime
+=duration
;
1846 numberTable
+= '<tr><td>' + data
.profiling
[i
].state
+ ' </td><td> ' + PMA_prettyProfilingNum(duration
,2) + '</td></tr>';
1848 numberTable
+= '<tr><td><b>Total time:</b></td><td>' + PMA_prettyProfilingNum(totalTime
,2) + '</td></tr>';
1849 numberTable
+= '</tbody></table>';
1851 $('div#queryAnalyzerDialog div.placeHolder td.chart').append('<b>Profiling results</b> (<a href="#showNums">Table</a> | <a href="#showChart">Chart</a>)<br/>' + numberTable
+ ' <div id="queryProfiling"></div>');
1853 $('div#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function() {
1854 $('div#queryAnalyzerDialog div#queryProfiling').hide();
1855 $('div#queryAnalyzerDialog table.queryNums').show();
1859 $('div#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function() {
1860 $('div#queryAnalyzerDialog div#queryProfiling').show();
1861 $('div#queryAnalyzerDialog table.queryNums').hide();
1865 profilingChart
= PMA_createProfilingChart(chartData
, {
1867 renderTo
: 'queryProfiling'
1877 $('div#queryProfiling').resizable();
1882 'Close' : function() {
1883 if(profilingChart
!= null) {
1884 profilingChart
.destroy();
1886 $('div#queryAnalyzerDialog div.placeHolder').html('');
1887 codemirror_editor
.setValue('');
1889 $(this).dialog("close");
1895 // Append a tooltip to the count column, if there exist one
1896 if($('#logTable th:last').html() == '#') {
1897 $('#logTable th:last').append(' <img class="qroupedQueryInfoIcon icon ic_b_docs" src="themes/dot.gif" alt="" />');
1899 var qtipContent
= PMA_messages
['strCountColumnExplanation'];
1900 if(groupInserts
) qtipContent
+= '<p>' + PMA_messages
['strMoreCountColumnExplanation'] + '</p>';
1902 $('img.qroupedQueryInfoIcon').qtip({
1903 content
: qtipContent
,
1906 target
: 'bottomMiddle',
1911 hide
: { delay
: 1000 }
1915 $('div#logTable table').tablesorter({
1916 sortList
: [[cols
.length
- 1,1]],
1920 $('div#logTable table thead th')
1921 .append('<img class="icon sortableIcon" src="themes/dot.gif" alt="">');
1926 function saveMonitor() {
1929 $.each(runtime
.charts
, function(key
, elem
) {
1931 gridCopy
[key
].nodes
= elem
.nodes
;
1932 gridCopy
[key
].settings
= elem
.settings
;
1933 gridCopy
[key
].title
= elem
.title
;
1936 if(window
.localStorage
) {
1937 window
.localStorage
['monitorCharts'] = $.toJSON(gridCopy
);
1938 window
.localStorage
['monitorSettings'] = $.toJSON(monitorSettings
);
1941 $('a[href="#clearMonitorConfig"]').show();
1944 $('a[href="#clearMonitorConfig"]').click(function() {
1945 window
.localStorage
.removeItem('monitorCharts');
1946 window
.localStorage
.removeItem('monitorSettings');
1950 function serverResponseError() {
1952 btns
[PMA_messages
['strReloadPage']] = function() {
1953 window
.location
.reload();
1955 $('#emptyDialog').attr('title',PMA_messages
['strRefreshFailed']);
1956 $('#emptyDialog').html('<img class="icon ic_s_attention" src="themes/dot.gif" alt=""> ' + PMA_messages
['strInvalidResponseExplanation'])
1957 $('#emptyDialog').dialog({ buttons
: btns
});