From d7cffc5dbde68342d46e891ea2c8bd72de134f43 Mon Sep 17 00:00:00 2001 From: Herman van Rink Date: Sat, 2 Jul 2011 23:43:25 +0200 Subject: [PATCH 001/206] Reverted some missing special chars in Changelog --- ChangeLog | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ChangeLog b/ChangeLog index fe7103128a..350b7ab299 100644 --- a/ChangeLog +++ b/ChangeLog @@ -95,7 +95,7 @@ phpMyAdmin - ChangeLog + patch #2974341 [structure] Clicking on table name in db Structure should Browse the table if possible, thanks to bhdouglass - dougboybhd + patch #2975533 [search] New search operators, thanks to - Martynas Mickevičius + Martynas Mickevičius + patch #2967320 [designer] Colored relations based on the primary key, thanks to GreenRover - greenrover - [core] Provide way for vendors to easily change paths to config files. @@ -249,7 +249,7 @@ phpMyAdmin - ChangeLog 3.3.7.0 (2010-09-07) - patch #3050492 [PDF scratchboard] Cannot drag table box to the edge after - a page size increase, thanks to Martin Schönberger - mad05 + a page size increase, thanks to Martin Schönberger - mad05 3.3.6.0 (2010-08-28) - bug #3033063 [core] Navi gets wrong db name @@ -270,7 +270,7 @@ phpMyAdmin - ChangeLog 3.3.5.0 (2010-07-26) - patch #2932113 [information_schema] Slow export when having lots of - databases, thanks to Stéphane Pontier - shadow_walker + databases, thanks to Stéphane Pontier - shadow_walker - bug #3022705 [import] Import button does not work in Catalan when there is no progress bar possible - bug [replication] Do not offer information_schema in the list of databases @@ -310,9 +310,9 @@ phpMyAdmin - ChangeLog - patch #2984893 [engines] InnoDB storage page emits a warning, thanks to Madhura Jayaratne - madhuracj - bug #2974687, bug #2974692 [compatibility] PHPExcel : IBM AIX iconv() does not work, - thanks to Björn Wiberg - bwiberg + thanks to Björn Wiberg - bwiberg - bug #2983066 [interface] Flush table on table operations shows the query twice, - thanks to Martynas Mickevičius - BlinK_ + thanks to Martynas Mickevičius - BlinK_ - bug #2983060, patch #2987900 [interface] Fix initial state of tables in designer, thanks to Sutharshan Balachandren. - bug #2983062, patch #2989408 [engines] Fix warnings when changing table @@ -391,7 +391,7 @@ phpMyAdmin - ChangeLog + rfe #2839504 [engines] Support InnoDB plugin's new row formats + [core] Added ability for synchronizing databases among servers. + [lang] #2843101 Dutch update, thanks to scavenger2008 -+ [lang] Galician update, thanks to Xosé Calvo - xosecalvo ++ [lang] Galician update, thanks to Xosé Calvo - xosecalvo + [export] Added MediaWiki export module, thanks to Derek Schaefer - drummingds1 + [lang] Turkish update, thanks to Burak Yavuz From a0823be05aa5835f207c0838b9cca67d2d9a050a Mon Sep 17 00:00:00 2001 From: Marc Delisle Date: Thu, 7 Jul 2011 14:39:09 -0400 Subject: [PATCH 002/206] XSS on table Print view --- tbl_printview.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tbl_printview.php b/tbl_printview.php index 74b6818e4b..8e8ce24d47 100644 --- a/tbl_printview.php +++ b/tbl_printview.php @@ -84,7 +84,7 @@ foreach ($the_tables as $key => $table) { } $counter++; echo '' . "\n"; - echo '

' . $table . '

' . "\n"; + echo '

' . htmlspecialchars($table) . '

' . "\n"; /** * Gets table informations From 4bd27166c314faa37cada91533b86377f4d4d214 Mon Sep 17 00:00:00 2001 From: Herman van Rink Date: Thu, 7 Jul 2011 14:43:45 -0400 Subject: [PATCH 003/206] Another case of XSS --- tbl_printview.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tbl_printview.php b/tbl_printview.php index 8e8ce24d47..ce007d1632 100644 --- a/tbl_printview.php +++ b/tbl_printview.php @@ -69,7 +69,7 @@ if ($multi_tables) { $tbl_list .= (empty($tbl_list) ? '' : ', ') . PMA_backquote($table); } - echo ''. __('Show tables') . ': ' . $tbl_list . '' . "\n"; + echo ''. __('Show tables') . ': ' . htmlspecialchars($tbl_list) . '' . "\n"; echo '
' . "\n"; } // end if From 951fb4dd79253a3aca8b6e386db77c1affcfc3a9 Mon Sep 17 00:00:00 2001 From: Marc Delisle Date: Thu, 7 Jul 2011 14:46:33 -0400 Subject: [PATCH 004/206] ChangeLog for PMASA-2011-9 --- ChangeLog | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ChangeLog b/ChangeLog index fe7103128a..49bb8947fb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,6 +1,9 @@ phpMyAdmin - ChangeLog ====================== +3.4.3.2 (2011-07-XX) +- [security] Fixed XSS vulnerability, see PMASA-2011-9 + 3.4.3.1 (2011-07-02) - [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-5 - [security] Fixed possible code injection incase session variables are compromised, see PMASA-2011-6 From f63e1bb42a37401b2fdfcd2e66cce92b7ea2025c Mon Sep 17 00:00:00 2001 From: Marc Delisle Date: Thu, 7 Jul 2011 14:50:37 -0400 Subject: [PATCH 005/206] Local file inclusion vulnerability --- ChangeLog | 1 + sql.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 49bb8947fb..065f8411b1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,7 @@ phpMyAdmin - ChangeLog 3.4.3.2 (2011-07-XX) - [security] Fixed XSS vulnerability, see PMASA-2011-9 +- [security] Fixed local file inclusion vulnerability, see PMASA-2011-10 3.4.3.1 (2011-07-02) - [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-5 diff --git a/sql.php b/sql.php index 9b19174a44..eb9254ffdd 100644 --- a/sql.php +++ b/sql.php @@ -719,7 +719,7 @@ if (0 == $num_rows || $is_affected) { parse_str($_REQUEST['transform_fields_list'], $edited_values); foreach($mime_map as $transformation) { - $include_file = $transformation['transformation']; + $include_file = PMA_securePath($transformation['transformation']); $column_name = $transformation['column_name']; $column_data = $edited_values[$column_name]; From 3ae58f0cd6b89ad4767920f9b214c38d3f6d4393 Mon Sep 17 00:00:00 2001 From: Herman van Rink Date: Fri, 8 Jul 2011 21:41:05 +0200 Subject: [PATCH 006/206] [security] Fixed local file inclusion vulnerability and code execution, see PMASA-2011-11 --- ChangeLog | 13 +++++++------ libraries/schema/User_Schema.class.php | 7 +++++-- schema_export.php | 4 +++- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/ChangeLog b/ChangeLog index d4d4f1bf4b..232d499451 100644 --- a/ChangeLog +++ b/ChangeLog @@ -4,6 +4,7 @@ phpMyAdmin - ChangeLog 3.4.3.2 (2011-07-XX) - [security] Fixed XSS vulnerability, see PMASA-2011-9 - [security] Fixed local file inclusion vulnerability, see PMASA-2011-10 +- [security] Fixed local file inclusion vulnerability and code execution, see PMASA-2011-11 3.4.3.1 (2011-07-02) - [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-5 @@ -99,7 +100,7 @@ phpMyAdmin - ChangeLog + patch #2974341 [structure] Clicking on table name in db Structure should Browse the table if possible, thanks to bhdouglass - dougboybhd + patch #2975533 [search] New search operators, thanks to - Martynas Mickevičius + Martynas Mickevičius + patch #2967320 [designer] Colored relations based on the primary key, thanks to GreenRover - greenrover - [core] Provide way for vendors to easily change paths to config files. @@ -253,7 +254,7 @@ phpMyAdmin - ChangeLog 3.3.7.0 (2010-09-07) - patch #3050492 [PDF scratchboard] Cannot drag table box to the edge after - a page size increase, thanks to Martin Schönberger - mad05 + a page size increase, thanks to Martin Schönberger - mad05 3.3.6.0 (2010-08-28) - bug #3033063 [core] Navi gets wrong db name @@ -274,7 +275,7 @@ phpMyAdmin - ChangeLog 3.3.5.0 (2010-07-26) - patch #2932113 [information_schema] Slow export when having lots of - databases, thanks to Stéphane Pontier - shadow_walker + databases, thanks to Stéphane Pontier - shadow_walker - bug #3022705 [import] Import button does not work in Catalan when there is no progress bar possible - bug [replication] Do not offer information_schema in the list of databases @@ -314,9 +315,9 @@ phpMyAdmin - ChangeLog - patch #2984893 [engines] InnoDB storage page emits a warning, thanks to Madhura Jayaratne - madhuracj - bug #2974687, bug #2974692 [compatibility] PHPExcel : IBM AIX iconv() does not work, - thanks to Björn Wiberg - bwiberg + thanks to Björn Wiberg - bwiberg - bug #2983066 [interface] Flush table on table operations shows the query twice, - thanks to Martynas Mickevičius - BlinK_ + thanks to Martynas Mickevičius - BlinK_ - bug #2983060, patch #2987900 [interface] Fix initial state of tables in designer, thanks to Sutharshan Balachandren. - bug #2983062, patch #2989408 [engines] Fix warnings when changing table @@ -395,7 +396,7 @@ phpMyAdmin - ChangeLog + rfe #2839504 [engines] Support InnoDB plugin's new row formats + [core] Added ability for synchronizing databases among servers. + [lang] #2843101 Dutch update, thanks to scavenger2008 -+ [lang] Galician update, thanks to Xosé Calvo - xosecalvo ++ [lang] Galician update, thanks to Xosé Calvo - xosecalvo + [export] Added MediaWiki export module, thanks to Derek Schaefer - drummingds1 + [lang] Turkish update, thanks to Burak Yavuz diff --git a/libraries/schema/User_Schema.class.php b/libraries/schema/User_Schema.class.php index fbec138de0..cb42dde2c2 100644 --- a/libraries/schema/User_Schema.class.php +++ b/libraries/schema/User_Schema.class.php @@ -567,10 +567,13 @@ class PMA_User_Schema require_once './libraries/transformations.lib.php'; require_once './libraries/Index.class.php'; /** - * default is PDF + * default is PDF, otherwise validate it's only letters a-z */ global $db,$export_type; - $export_type = isset($export_type) ? $export_type : 'pdf'; + if (!isset($export_type) || !preg_match('/^[a-zA-Z]+$/', $export_type)) { + $export_type = 'pdf'; + } + PMA_DBI_select_db($db); include("./libraries/schema/".ucfirst($export_type)."_Relation_Schema.class.php"); diff --git a/schema_export.php b/schema_export.php index 0a21d3296c..3e1067d55e 100644 --- a/schema_export.php +++ b/schema_export.php @@ -37,7 +37,9 @@ include_once("./libraries/schema/Export_Relation_Schema.class.php"); * default is PDF */ global $db,$export_type; -$export_type = isset($export_type) ? $export_type : 'pdf'; +if (!isset($export_type) || !preg_match('/^[a-zA-Z]+$/', $export_type)) { + $export_type = 'pdf'; +} PMA_DBI_select_db($db); $path = PMA_securePath(ucfirst($export_type)); From e7bb42c002885c2aca7aba4d431b8c63ae4de9b7 Mon Sep 17 00:00:00 2001 From: Herman van Rink Date: Sat, 9 Jul 2011 23:10:23 +0200 Subject: [PATCH 007/206] [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-12 --- ChangeLog | 1 + libraries/auth/swekey/swekey.auth.lib.php | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 232d499451..c076772bb2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -5,6 +5,7 @@ phpMyAdmin - ChangeLog - [security] Fixed XSS vulnerability, see PMASA-2011-9 - [security] Fixed local file inclusion vulnerability, see PMASA-2011-10 - [security] Fixed local file inclusion vulnerability and code execution, see PMASA-2011-11 +- [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-12 3.4.3.1 (2011-07-02) - [security] Fixed possible session manipulation in swekey authentication, see PMASA-2011-5 diff --git a/libraries/auth/swekey/swekey.auth.lib.php b/libraries/auth/swekey/swekey.auth.lib.php index c5f613bbd3..01f2dcc4c4 100644 --- a/libraries/auth/swekey/swekey.auth.lib.php +++ b/libraries/auth/swekey/swekey.auth.lib.php @@ -143,7 +143,9 @@ function Swekey_auth_error() return "Internal Error: CA File $caFile not found"; $result = null; - parse_str($_SERVER['QUERY_STRING']); + $swekey_id = $_GET['swekey_id']; + $swekey_otp = $_GET['swekey_otp']; + if (isset($swekey_id)) { unset($_SESSION['SWEKEY']['AUTHENTICATED_SWEKEY']); if (! isset($_SESSION['SWEKEY']['RND_TOKEN'])) { @@ -166,7 +168,7 @@ function Swekey_auth_error() $result = __('No valid authentication key plugged'); if ($_SESSION['SWEKEY']['CONF_DEBUG']) { - $result .= "
".$swekey_id; + $result .= "
" . htmlspecialchars($swekey_id); } unset($_SESSION['SWEKEY']['CONF_LOADED']); // reload the conf file } From 571cdc6ff4bf375871b594f4e06f8ad3159d1754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20=C4=8Ciha=C5=99?= Date: Mon, 11 Jul 2011 14:15:19 +0200 Subject: [PATCH 008/206] Pass token along with swekey auth requests --- libraries/auth/swekey/swekey.auth.lib.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/auth/swekey/swekey.auth.lib.php b/libraries/auth/swekey/swekey.auth.lib.php index 01f2dcc4c4..8ec5ab4f14 100644 --- a/libraries/auth/swekey/swekey.auth.lib.php +++ b/libraries/auth/swekey/swekey.auth.lib.php @@ -188,16 +188,16 @@ function Swekey_auth_error() Date: Mon, 11 Jul 2011 21:24:06 -0400 Subject: [PATCH 009/206] Fix broken characters --- ChangeLog | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ChangeLog b/ChangeLog index c076772bb2..dc2956f208 100644 --- a/ChangeLog +++ b/ChangeLog @@ -101,7 +101,7 @@ phpMyAdmin - ChangeLog + patch #2974341 [structure] Clicking on table name in db Structure should Browse the table if possible, thanks to bhdouglass - dougboybhd + patch #2975533 [search] New search operators, thanks to - Martynas Mickevičius + Martynas Mickevičius + patch #2967320 [designer] Colored relations based on the primary key, thanks to GreenRover - greenrover - [core] Provide way for vendors to easily change paths to config files. @@ -255,7 +255,7 @@ phpMyAdmin - ChangeLog 3.3.7.0 (2010-09-07) - patch #3050492 [PDF scratchboard] Cannot drag table box to the edge after - a page size increase, thanks to Martin Schönberger - mad05 + a page size increase, thanks to Martin Schönberger - mad05 3.3.6.0 (2010-08-28) - bug #3033063 [core] Navi gets wrong db name @@ -276,7 +276,7 @@ phpMyAdmin - ChangeLog 3.3.5.0 (2010-07-26) - patch #2932113 [information_schema] Slow export when having lots of - databases, thanks to Stéphane Pontier - shadow_walker + databases, thanks to Stéphane Pontier - shadow_walker - bug #3022705 [import] Import button does not work in Catalan when there is no progress bar possible - bug [replication] Do not offer information_schema in the list of databases @@ -316,9 +316,9 @@ phpMyAdmin - ChangeLog - patch #2984893 [engines] InnoDB storage page emits a warning, thanks to Madhura Jayaratne - madhuracj - bug #2974687, bug #2974692 [compatibility] PHPExcel : IBM AIX iconv() does not work, - thanks to Björn Wiberg - bwiberg + thanks to Björn Wiberg - bwiberg - bug #2983066 [interface] Flush table on table operations shows the query twice, - thanks to Martynas Mickevičius - BlinK_ + thanks to Martynas Mickevičius - BlinK_ - bug #2983060, patch #2987900 [interface] Fix initial state of tables in designer, thanks to Sutharshan Balachandren. - bug #2983062, patch #2989408 [engines] Fix warnings when changing table @@ -397,7 +397,7 @@ phpMyAdmin - ChangeLog + rfe #2839504 [engines] Support InnoDB plugin's new row formats + [core] Added ability for synchronizing databases among servers. + [lang] #2843101 Dutch update, thanks to scavenger2008 -+ [lang] Galician update, thanks to Xosé Calvo - xosecalvo ++ [lang] Galician update, thanks to Xosé Calvo - xosecalvo + [export] Added MediaWiki export module, thanks to Derek Schaefer - drummingds1 + [lang] Turkish update, thanks to Burak Yavuz From 5022829ae64d9f72726a9d73ba2f2e51de2b2837 Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Wed, 20 Jul 2011 12:08:05 +0300 Subject: [PATCH 010/206] Monitor Logs Feature: Grouping of Queries, ignoring variable data in WHERE Statements --- js/messages.php | 12 +- js/server_status.js | 358 ++++++++++++++++++++++++++------------------ server_status.php | 88 +++++++---- 3 files changed, 282 insertions(+), 176 deletions(-) diff --git a/js/messages.php b/js/messages.php index 2ab89ddef3..b12a5e6565 100644 --- a/js/messages.php +++ b/js/messages.php @@ -135,9 +135,6 @@ $js_messages['strChartTitle'] = __('Chart Title'); $js_messages['strDifferential'] = __('Differential'); $js_messages['strDividedBy'] = __('Divided by %s:'); -$js_messages['strSelectedTimeRange'] = __('Selected time range:'); -$js_messages['strGroupInserts'] = __('Group together INSERTs into same table'); -$js_messages['strLogAnalyseInfo'] = __('

Choose from which log you want the statistics to be generated from.

Results are grouped by query text.'); $js_messages['strFromSlowLog'] = __('From slow log'); $js_messages['strFromGeneralLog'] = __('From general log'); $js_messages['strAnalysingLogs'] = __('Analysing & loading logs. This may take a while.'); @@ -148,6 +145,15 @@ $js_messages['strLogDataLoaded'] = __('Log data loaded. Queries executed in this $js_messages['strJumpToTable'] = __('Jump to Log table'); $js_messages['strNoDataFound'] = __('Log analysed, but not data found in this time span.'); +/* l10n: A collection of available filters */ +$js_messages['strFilters'] = __('Filters'); +/* l10n: Filter as in "Start Filtering" */ +$js_messages['strFilter'] = __('Filter'); +$js_messages['strFilterByWordRegexp'] = __('Filter queries by word/regexp:'); +$js_messages['strIgnoreWhereAndGroup'] = __('Group queries, ignoring variable data in WHERE statements'); +$js_messages['strSumRows'] = __('Sum of grouped rows:'); +$js_messages['strTotal'] = __('Total:'); + /* For inline query editing */ $js_messages['strGo'] = __('Go'); $js_messages['strCancel'] = __('Cancel'); diff --git a/js/server_status.js b/js/server_status.js index ac4071c3f6..3e0fd6ed82 100644 --- a/js/server_status.js +++ b/js/server_status.js @@ -574,7 +574,7 @@ $(function() { redrawCharts: false, // Object that contains a list of nodes that need to be retrieved from the server for chart updates dataList: [] - } + }; var monitorSettings = null; @@ -585,7 +585,7 @@ $(function() { gridMaxPoints: 'auto', /* Refresh rate of all grid charts in ms */ gridRefresh: 5000 - } + }; // Allows drag and drop rearrange and print/edit icons on charts var editMode = false; @@ -663,7 +663,7 @@ $(function() { } } } - } + }; // Default setting defaultChartGrid = { @@ -691,7 +691,7 @@ $(function() { defaultChartGrid['c5'] = presetCharts['swap-' + server_os]; } - var gridbuttons = { + var gridbuttons = { cogButton: { //enabled: true, symbol: 'url(' + pmaThemeImage + 's_cog.png)', @@ -1259,24 +1259,10 @@ $(function() { min = extremesObject.min, max = extremesObject.max; - $('#logAnalyseDialog').html( - '

' + PMA_messages['strSelectedTimeRange'] - + ' - ' - + '

' - + '' - + '' - + PMA_messages['strLogAnalyseInfo'] - ); - - PMA_addDatepicker($('#logAnalyseDialog').find('input[name="dateStart"],input[name="dateEnd"]'), { - showOn: 'focus', - beforeShow: function() { - // Fix wrong timepicker z-index, doesn't work without timeout - setTimeout(function() { - $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index')) - },0); - } - }); + $('#logAnalyseDialog input[name="dateStart"]') + .attr('value', Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', new Date(min))); + $('#logAnalyseDialog input[name="dateEnd"]') + .attr('value', Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', new Date(max))); var dlgBtns = { }; @@ -1284,9 +1270,13 @@ $(function() { var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').attr('value')) || min; var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').attr('value')) || max; - loadLogStatistics( - { src: 'slow', start: dateStart, end: dateEnd, groupInserts: $('input#groupInserts').attr('checked') } - ); + loadLogStatistics({ + src: 'slow', + start: dateStart, + end: dateEnd, + removeVariables: $('input#removeVariables').prop('checked'), + limitTypes: $('input#limitTypes').prop('checked') + }); $('#logAnalyseDialog').find('dateStart,dateEnd').datepicker('destroy'); @@ -1297,9 +1287,13 @@ $(function() { var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').attr('value')) || min; var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').attr('value')) || max; - loadLogStatistics( - { src: 'general', start: dateStart, end: dateEnd, groupInserts: $('input#groupInserts').attr('checked') } - ); + loadLogStatistics({ + src: 'general', + start: dateStart, + end: dateEnd, + removeVariables: $('input#removeVariables').prop('checked'), + limitTypes: $('input#limitTypes').prop('checked') + }); $('#logAnalyseDialog').find('dateStart,dateEnd').datepicker('destroy'); @@ -1474,10 +1468,11 @@ $(function() { function loadLogStatistics(opts) { var tableStr = ''; var logRequest = null; - var groupInsert = false; - if(opts.groupInserts) - groupInserts = true; + if(! opts.removeVariables) + opts.removeVariables = false; + if(! opts.limitTypes) + opts.limitTypes = false; $('#loadingLogsDialog').html(PMA_messages['strAnalysingLogs'] + ' '); @@ -1495,140 +1490,58 @@ $(function() { }); - var formatValue = function(name, value) { - switch(name) { - case 'user_host': - return value.replace(/(\[.*?\])+/g,''); - } - return value; - } - logRequest = $.get('server_status.php?'+url_query, - { ajax_request: true, log_data: 1, type: opts.src, time_start: Math.round(opts.start / 1000), time_end: Math.round(opts.end / 1000), groupInserts: groupInserts }, + { ajax_request: true, + log_data: 1, + type: opts.src, + time_start: Math.round(opts.start / 1000), + time_end: Math.round(opts.end / 1000), + removeVariables: opts.removeVariables, + limitTypes: opts.limitTypes + }, function(data) { - var data = $.parseJSON(data); - var rows = data.rows; - var cols = new Array(); + runtime.logData = $.parseJSON(data); - if(rows.length != 0) { - tableStr = ''; - - for(var i=0; i < rows.length; i++) { - if(i == 0) { - tableStr += ''; - $.each(rows[0],function(key, value) { - cols.push(key); - }); - tableStr += ''; - tableStr += ''; - } - - tableStr += ''; - for(var j=0; j < cols.length; j++) - tableStr += ''; - tableStr += ''; - } - - tableStr += ''; - tableStr += ''; - tableStr += '
' + cols.join('') + '
' + formatValue(cols[j], rows[i][cols[j]]) + '
Sum of grouped rows: '+ data.numRows +'Total:' + data.sum.TOTAL + '
'; - - $('#logTable').html(tableStr); - - // Append a tooltip to the count column, if there exist one - if($('#logTable th:last').html() == '#') { - $('#logTable th:last').append(' '); - - var qtipContent = PMA_messages['strCountColumnExplanation']; - if(groupInserts) qtipContent += '

' + PMA_messages['strMoreCountColumnExplanation'] + '

'; - - $('img.qroupedQueryInfoIcon').qtip({ - content: qtipContent, - position: { - corner: { - target: 'bottomMiddle', - tooltip: 'topRight' - } - - }, - hide: { delay: 1000 } - }) - } - - - - $('div#logTable table').tablesorter({ - sortList: [[0,1]], - widgets: ['zebra'] - }); - - $('div#logTable table thead th') - .append(''); - + if(runtime.logData.rows.length != 0) { + runtime.logDataCols = buildLogTable(runtime.logData); + /* Show some stats in the dialog */ $('#loadingLogsDialog').html('

' + PMA_messages['strLogDataLoaded'] + '

'); - $.each(data.sum, function(key, value) { + $.each(runtime.logData.sum, function(key, value) { key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase(); if(key == 'Total') key = '' + key + ''; $('#loadingLogsDialog').append(key + ': ' + value + '
'); }); - if(data.numRows > 12) { + /* Add filter options if more than a bunch of rows there to filter */ + if(runtime.logData.numRows > 12) { $('div#logTable').prepend( '
' + - ' Filters' + + ' ' + PMA_messages['strFilters'] + '' + '
' + - ' ' + + ' ' + ' ' + - ((data.numRows > 250) ? ' ' : '') + '
' + + ((runtime.logData.numRows > 250) ? '
' : '') + + '
' + + ' ' + + ' ' + + ' ' ); - if(data.numRows > 250) { + $('div#logTable input#noWHEREData').change(function() { + filterQueries(true); + }); + + //preg_replace('/\s+([^=]+)=(\d+|((\'|"|)(?U)(.+)(? 250) { $('div#logTable button#startFilterQueryText').click(filterQueries); } else { $('div#logTable input#filterQueryText').keyup(filterQueries); } - function filterQueries() { - var odd_row=false, cell, textFilter; - var val = $('div#logTable input#filterQueryText').val(); - - if(val.length == 0) textFilter = null; - else textFilter = new RegExp(val, 'i'); - - var rowSum = 0, totalSum = 0; - - $('div#logTable table tbody tr').each(function() { - // We just assume the sql text is always in the second last column - cell = $(this).children(':nth-child(' + (cols.length - 1) + ')'); - - if(textFilter==null || textFilter.exec(cell.text())) { - // And that total count is right of the sql text - totalSum += parseInt(cell.next().text()); - rowSum ++; - - odd_row = !odd_row; - $(this).css('display',''); - if(odd_row) { - $(this).addClass('odd'); - $(this).removeClass('even'); - } else { - $(this).addClass('even'); - $(this).removeClass('odd'); - } - } else { - $(this).css('display','none'); - } - }); - - - $('div#logTable table tfoot tr') - .html('Sum of grouped rows: '+ rowSum +'Total:' + - totalSum + ''); - }; } var dlgBtns = {}; @@ -1651,6 +1564,167 @@ $(function() { } } ); + + function filterQueries(varFilterChange) { + var odd_row=false, cell, textFilter; + var val = $('div#logTable input#filterQueryText').val(); + + if(val.length == 0) textFilter = null; + else textFilter = new RegExp(val, 'i'); + + var rowSum = 0, totalSum = 0; + + var i=0, q; + var noVars = $('div#logTable input#noWHEREData').attr('checked'); + var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi; + var functionFilter = /([a-z0-9_]+)\(.+?\)/gi; + var filteredQueries = {}; + var filteredQueriesLines = {}; + var hide = false; + var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2]; + var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1]; + + // We just assume the sql text is always in the second last column, and that the total count is right of it + $('div#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function() { + if(varFilterChange && $(this).html().match(/^SELECT/i)) { + if(noVars) { + q = $(this).text().replace(equalsFilter, '$1=...$6').trim(); + q = q.replace(functionFilter, ' $1(...)'); + + // Js does not specify a limit on property name length, so we can abuse it as index :-) + if(filteredQueries[q]) { + filteredQueries[q] += parseInt($(this).next().text()); + totalSum += parseInt($(this).next().text()); + rowSum ++; + hide = true; + } else { + filteredQueries[q] = parseInt($(this).next().text());; + filteredQueriesLines[q] = i; + $(this).text(q); + } + + } else { + $(this).text(runtime.logData.rows[i][queryColumnName]); + $(this).next().text('' + runtime.logData.rows[i][sumColumnName]); + } + } + + if(! hide && (textFilter != null && ! textFilter.exec($(this).text()))) hide = true; + + if(hide) { + $(this).parent().css('display','none'); + } else { + totalSum += parseInt($(this).next().text()); + rowSum ++; + + odd_row = ! odd_row; + $(this).parent().css('display',''); + if(odd_row) { + $(this).parent().addClass('odd'); + $(this).parent().removeClass('even'); + } else { + $(this).parent().addClass('even'); + $(this).parent().removeClass('odd'); + } + } + + hide = false; + i++; + }); + + if(varFilterChange) { + if(noVars) { + $.each(filteredQueriesLines, function(key,value) { + if(filteredQueries[value] <= 1) return; + + var numCol = $('div#logTable table tbody tr:nth-child(' + (value+1) + ')') + .children(':nth-child(' + (runtime.logDataCols.length) + ')'); + + numCol.text(filteredQueries[key]); + }); + } + + $('div#logTable table').trigger("update"); + setTimeout(function() { + + $('div#logTable table').trigger('sorton',[[[runtime.logDataCols.length - 1,1]]]); + }, 0); + } + + $('div#logTable table tfoot tr') + .html('' + + PMA_messages['strSumRows'] + ' '+ rowSum +'' + + PMA_messages['strTotal'] + ':' + totalSum + ''); + } + } + + function buildLogTable(data) { + var rows = data.rows; + var cols = new Array(); + + var tableStr = ''; + + var formatValue = function(name, value) { + switch(name) { + case 'user_host': + return value.replace(/(\[.*?\])+/g,''); + } + return value; + } + + for(var i=0; i < rows.length; i++) { + if(i == 0) { + tableStr += ''; + $.each(rows[0],function(key, value) { + cols.push(key); + }); + tableStr += ''; + tableStr += ''; + } + + tableStr += ''; + for(var j=0; j < cols.length; j++) + tableStr += ''; + tableStr += ''; + } + + tableStr += ''; + tableStr += ''; + tableStr += '
' + cols.join('') + '
' + formatValue(cols[j], rows[i][cols[j]]) + '
' + PMA_messages['strSumRows'] + + ' '+ data.numRows +'' + PMA_messages['strTotal'] + + '' + data.sum.TOTAL + '
'; + + $('#logTable').html(tableStr); + + // Append a tooltip to the count column, if there exist one + if($('#logTable th:last').html() == '#') { + $('#logTable th:last').append(' '); + + var qtipContent = PMA_messages['strCountColumnExplanation']; + if(groupInserts) qtipContent += '

' + PMA_messages['strMoreCountColumnExplanation'] + '

'; + + $('img.qroupedQueryInfoIcon').qtip({ + content: qtipContent, + position: { + corner: { + target: 'bottomMiddle', + tooltip: 'topRight' + } + + }, + hide: { delay: 1000 } + }) + } + + $('div#logTable table').tablesorter({ + sortList: [[cols.length - 1,1]], + widgets: ['zebra'] + }); + + $('div#logTable table thead th') + .append(''); + + return cols; } function saveMonitor() { diff --git a/server_status.php b/server_status.php index b6324b7967..e14467a45a 100644 --- a/server_status.php +++ b/server_status.php @@ -194,9 +194,13 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { } if($_REQUEST['type'] == 'general') { - $q = 'SELECT TIME(event_time) as event_time, user_host, thread_id, server_id, argument, count(argument) as \'#\' FROM `mysql`.`general_log` WHERE command_type=\'Query\' '. + $limitTypes = (isset($_REQUEST['limitTypes']) && $_REQUEST['limitTypes']) + ? 'AND argument REGEXP \'^(INSERT|SELECT|UPDATE|DELETE)\' ' : ''; + + $q = 'SELECT TIME(event_time) as event_time, user_host, thread_id, server_id, argument, count(argument) as \'#\' '. + 'FROM `mysql`.`general_log` WHERE command_type=\'Query\' '. 'AND event_time > FROM_UNIXTIME('.$start.') AND event_time < FROM_UNIXTIME('.$end.') '. - 'AND argument REGEXP \'^(INSERT|SELECT|UPDATE|DELETE)\' GROUP by argument'; // HAVING count > 1'; + $limitTypes . 'GROUP by argument'; // HAVING count > 1'; $result = PMA_DBI_try_query($q); @@ -205,43 +209,52 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { $insertTables = array(); $insertTablesFirst = -1; $i = 0; + $removeVars = isset($_REQUEST['removeVariables']) && $_REQUEST['removeVariables']; while ($row = PMA_DBI_fetch_assoc($result)) { preg_match('/^(\w+)\s/',$row['argument'],$match); $type = strtolower($match[1]); // Ignore undefined index warning, just increase counter by one @$return['sum'][$type] += $row['#']; - - if($type=='insert' || $type=='update') { - // Group inserts if selected - if($type=='insert' && isset($_REQUEST['groupInserts']) && $_REQUEST['groupInserts'] && preg_match('/^INSERT INTO (`|\'|"|)([^\s\\1]+)\\1/i',$row['argument'],$matches)) { - $insertTables[$matches[2]]++; - if ($insertTables[$matches[2]] > 1) { - $return['rows'][$insertTablesFirst]['#'] = $insertTables[$matches[2]]; - - // Add a ... to the end of this query to indicate that there's been other queries - if($return['rows'][$insertTablesFirst]['argument'][strlen($return['rows'][$insertTablesFirst]['argument'])-1] != '.') - $return['rows'][$insertTablesFirst]['argument'] .= '
...'; + + switch($type) { + case 'insert': + // Group inserts if selected + if($removeVars && preg_match('/^INSERT INTO (`|\'|"|)([^\s\\1]+)\\1/i',$row['argument'],$matches)) { + $insertTables[$matches[2]]++; + if ($insertTables[$matches[2]] > 1) { + $return['rows'][$insertTablesFirst]['#'] = $insertTables[$matches[2]]; - // Group this value, thus do not add to the result list - continue; - } else { - $insertTablesFirst = $i; - $insertTables[$matches[2]] += $row['#'] - 1; + // Add a ... to the end of this query to indicate that there's been other queries + if($return['rows'][$insertTablesFirst]['argument'][strlen($return['rows'][$insertTablesFirst]['argument'])-1] != '.') + $return['rows'][$insertTablesFirst]['argument'] .= '
...'; + + // Group this value, thus do not add to the result list + continue; + } else { + $insertTablesFirst = $i; + $insertTables[$matches[2]] += $row['#'] - 1; + } } - } + // No break here - // Cut off big selects, but append byte count therefor - if(strlen($row['argument']) > 180) - $row['argument'] = substr($row['argument'],0,160) . '... [' . - PMA_formatByteDown(strlen($row['argument']), 2).']'; + case 'update': + // Cut off big inserts and updates, but append byte count therefor + if(strlen($row['argument']) > 180) + $row['argument'] = substr($row['argument'],0,160) . '... [' . + PMA_formatByteDown(strlen($row['argument']), 2).']'; + + break; + + default: break; } + $return['rows'][] = $row; $i++; } $return['sum']['TOTAL'] = array_sum($return['sum']); - $return['numRows'] = count($return['rows']); + $return['numRows'] = count($return['rows']); PMA_DBI_free_result($result); @@ -1323,7 +1336,7 @@ function printMonitor() { @@ -1416,8 +1429,21 @@ function printMonitor() { -
+ From c30d209146d9d7c2f840cb8fb14de8840dccd54e Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Thu, 21 Jul 2011 13:38:51 +0300 Subject: [PATCH 011/206] Query Analyzer Dialog v0.1 --- js/functions.js | 188 +++++++++++++++--------- js/jquery/jquery.sortableTable.js | 32 ++-- js/messages.php | 1 + js/server_status.js | 181 ++++++++++++++++++++--- js/sql.js | 35 +---- server_status.php | 78 ++++++---- sql.php | 2 +- themes/pmahomme/css/theme_right.css.php | 31 +++- 8 files changed, 382 insertions(+), 166 deletions(-) diff --git a/js/functions.js b/js/functions.js index f74f685fde..ce2c867bc3 100644 --- a/js/functions.js +++ b/js/functions.js @@ -140,8 +140,8 @@ function PMA_addDatepicker($this_element, options) { if ($this_element.is('.datetimefield')) { showTimeOption = true; } - - var defaultOptions = { + + var defaultOptions = { showOn: 'button', buttonImage: themeCalendarImage, // defined in js/messages.php buttonImageOnly: true, @@ -163,7 +163,7 @@ function PMA_addDatepicker($this_element, options) { },0); }, constrainInput: false - }; + }; $this_element.datepicker($.extend(defaultOptions, options)); } @@ -1455,12 +1455,13 @@ function PMA_createTableDialog( div, url , target) { * - the current response value of the GET request, JSON parsed * - the previous response value of the GET request, JSON parsed * - the number of added points + * } * * @return object The created highcharts instance */ function PMA_createChart(passedSettings) { var container = passedSettings.chart.renderTo; - + var settings = { chart: { type: 'spline', @@ -1576,6 +1577,53 @@ function PMA_createChart(passedSettings) { return new Highcharts.Chart(settings); } + +/* + * Creates a Profiling Chart. Used in sql.php and server_status.js + */ +function PMA_createProfilingChart(data, options) { + return PMA_createChart($.extend(true, { + chart: { + renderTo: 'profilingchart', + type: 'pie' + }, + title: { text:'', margin:0 }, + series: [{ + type: 'pie', + name: PMA_messages['strQueryExecutionTime'], + data: data + }], + plotOptions: { + pie: { + allowPointSelect: true, + cursor: 'pointer', + dataLabels: { + enabled: true, + distance: 35, + formatter: function() { + return ''+ this.point.name +'
'+ Highcharts.numberFormat(this.percentage, 2) +' %'; + } + } + } + }, + tooltip: { + formatter: function() { + return ''+ this.point.name +'
'+PMA_prettyProfilingNum(this.y)+'
('+Highcharts.numberFormat(this.percentage, 2) +' %)'; + } + } + },options)); +} + +// Formats a profiling duration nicely. Used in PMA_createProfilingChart() and server_status.js +function PMA_prettyProfilingNum(num, acc) { + if(!acc) acc = 1; + acc = Math.pow(10,acc); + if(num*1000 < 0.1) num = Math.round(acc*(num*1000*1000))/acc + 'µ' + else if(num < 0.1) num = Math.round(acc*(num*1000))/acc + 'm' + + return num + 's'; +} + /** * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not * return a jQuery object yet and hence cannot be chained @@ -2455,65 +2503,65 @@ var toggleButton = function ($obj) { } else { var right = 'left'; } - /** - * var h Height of the button, used to scale the - * background image and position the layers - */ - var h = $obj.height(); - $('img', $obj).height(h); - $('table', $obj).css('bottom', h-1); - /** - * var on Width of the "ON" part of the toggle switch - * var off Width of the "OFF" part of the toggle switch - */ - var on = $('.toggleOn', $obj).width(); - var off = $('.toggleOff', $obj).width(); - // Make the "ON" and "OFF" parts of the switch the same size - $('.toggleOn > div', $obj).width(Math.max(on, off)); - $('.toggleOff > div', $obj).width(Math.max(on, off)); - /** - * var w Width of the central part of the switch - */ - var w = parseInt(($('img', $obj).height() / 16) * 22, 10); - // Resize the central part of the switch on the top - // layer to match the background - $('table td:nth-child(2) > div', $obj).width(w); - /** - * var imgw Width of the background image - * var tblw Width of the foreground layer - * var offset By how many pixels to move the background - * image, so that it matches the top layer - */ - var imgw = $('img', $obj).width(); - var tblw = $('table', $obj).width(); - var offset = parseInt(((imgw - tblw) / 2), 10); - // Move the background to match the layout of the top layer - $obj.find('img').css(right, offset); - /** - * var offw Outer width of the "ON" part of the toggle switch - * var btnw Outer width of the central part of the switch - */ - var offw = $('.toggleOff', $obj).outerWidth(); - var btnw = $('table td:nth-child(2)', $obj).outerWidth(); - // Resize the main div so that exactly one side of - // the switch plus the central part fit into it. - $obj.width(offw + btnw + 2); - /** - * var move How many pixels to move the - * switch by when toggling - */ - var move = $('.toggleOff', $obj).outerWidth(); - // If the switch is initialized to the - // OFF state we need to move it now. - if ($('.container', $obj).hasClass('off')) { + /** + * var h Height of the button, used to scale the + * background image and position the layers + */ + var h = $obj.height(); + $('img', $obj).height(h); + $('table', $obj).css('bottom', h-1); + /** + * var on Width of the "ON" part of the toggle switch + * var off Width of the "OFF" part of the toggle switch + */ + var on = $('.toggleOn', $obj).width(); + var off = $('.toggleOff', $obj).width(); + // Make the "ON" and "OFF" parts of the switch the same size + $('.toggleOn > div', $obj).width(Math.max(on, off)); + $('.toggleOff > div', $obj).width(Math.max(on, off)); + /** + * var w Width of the central part of the switch + */ + var w = parseInt(($('img', $obj).height() / 16) * 22, 10); + // Resize the central part of the switch on the top + // layer to match the background + $('table td:nth-child(2) > div', $obj).width(w); + /** + * var imgw Width of the background image + * var tblw Width of the foreground layer + * var offset By how many pixels to move the background + * image, so that it matches the top layer + */ + var imgw = $('img', $obj).width(); + var tblw = $('table', $obj).width(); + var offset = parseInt(((imgw - tblw) / 2), 10); + // Move the background to match the layout of the top layer + $obj.find('img').css(right, offset); + /** + * var offw Outer width of the "ON" part of the toggle switch + * var btnw Outer width of the central part of the switch + */ + var offw = $('.toggleOff', $obj).outerWidth(); + var btnw = $('table td:nth-child(2)', $obj).outerWidth(); + // Resize the main div so that exactly one side of + // the switch plus the central part fit into it. + $obj.width(offw + btnw + 2); + /** + * var move How many pixels to move the + * switch by when toggling + */ + var move = $('.toggleOff', $obj).outerWidth(); + // If the switch is initialized to the + // OFF state we need to move it now. + if ($('.container', $obj).hasClass('off')) { if (right == 'right') { - $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0); + $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0); } else { - $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0); + $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0); } - } - // Attach an 'onclick' event to the switch - $('.container', $obj).click(function () { + } + // Attach an 'onclick' event to the switch + $('.container', $obj).click(function () { if ($(this).hasClass('isActive')) { return false; } else { @@ -2522,8 +2570,8 @@ var toggleButton = function ($obj) { var $msg = PMA_ajaxShowMessage(PMA_messages['strLoading']); var $container = $(this); var callback = $('.callback', this).text(); - // Perform the actual toggle - if ($(this).hasClass('on')) { + // Perform the actual toggle + if ($(this).hasClass('on')) { if (right == 'right') { var operator = '-='; } else { @@ -2532,7 +2580,7 @@ var toggleButton = function ($obj) { var url = $(this).find('.toggleOff > span').text(); var removeClass = 'on'; var addClass = 'off'; - } else { + } else { if (right == 'right') { var operator = '+='; } else { @@ -2545,10 +2593,10 @@ var toggleButton = function ($obj) { $.post(url, {'ajax_request': true}, function(data) { if(data.success == true) { PMA_ajaxRemoveMessage($msg); - $container - .removeClass(removeClass) - .addClass(addClass) - .animate({'left': operator + move + 'px'}, function () { + $container + .removeClass(removeClass) + .addClass(addClass) + .animate({'left': operator + move + 'px'}, function () { $container.removeClass('isActive'); }); eval(callback); @@ -2557,7 +2605,7 @@ var toggleButton = function ($obj) { $container.removeClass('isActive'); } }); - }); + }); }; /** @@ -2568,8 +2616,8 @@ $(window).load(function () { $(this) .show() .find('.toggleButton') - toggleButton($(this)); - }); + toggleButton($(this)); + }); }); /** diff --git a/js/jquery/jquery.sortableTable.js b/js/jquery/jquery.sortableTable.js index 8fa6eb66c3..2dd1ede1e2 100644 --- a/js/jquery/jquery.sortableTable.js +++ b/js/jquery/jquery.sortableTable.js @@ -10,21 +10,31 @@ */ /* Options: - $('table').sortableTable({ - ignoreRect: { top, left, width, height } - relative coordinates on each element. If the user clicks - in this area, it is not seen as a drag&drop request. Useful for toolbars etc. - events: { - start: callback function when the user starts dragging - drop: callback function after an element has been dropped - } - }) + +$('table').sortableTable({ + ignoreRect: { top, left, width, height } - relative coordinates on each element. If the user clicks + in this area, it is not seen as a drag&drop request. Useful for toolbars etc. + events: { + start: callback function when the user starts dragging + drop: callback function after an element has been dropped + } +}) */ /* Commands: - $('table').sortableTable('init') - equivalent to $('table').sortableTable() - $('table').sortableTable('refresh') - if the table has been changed, refresh correctly assigns all events again - $('table').sortableTable('destroy') - removes all events from the table + +$('table').sortableTable('init') - equivalent to $('table').sortableTable() +$('table').sortableTable('refresh') - if the table has been changed, refresh correctly assigns all events again +$('table').sortableTable('destroy') - removes all events from the table + */ + +/* Setup: + + Can be applied on any table, there is just one convention. + Each cell (
'); - $('#logTable').html(tableStr); + + function queryAnalyzer() { + var query = $(this).parent().data('query')[cols[cols.length-2]]; + + /* A very basic SQL Formatter. Totally fails in the cases of + - Any string appearance containing a MySQL Keyword, surrounded by whitespaces + - Subqueries too probably + */ + var sLists = query.match(/SELECT\s+[^]+\s+FROM\s+/gi); + if(sLists) { + for(var i=0; i < sLists.length; i++) { + query = query.replace(sLists[i],sLists[i].replace(/\s*((`|'|"|).*?\1,)\s*/gi,'$1\n\t')); + } + query = query + .replace(/(\s+|^)(SELECT|FROM|WHERE|GROUP BY|HAVING|ORDER BY|LIMIT)(\s+|$)/gi,'\n$2\n\t') + .replace(/\s+UNION\s+/gi,'\n\nUNION\n\n') + .replace(/\s+(AND)\s+/gi,' $1\n\t') + .trim(); + } + + codemirror_editor.setValue(query); + + var profilingChart = null; + + $('div#queryAnalyzerDialog').dialog({ + width: 'auto', + height: 'auto', + resizable: false, + buttons: { + 'Analyse Query' : function() { + $('div#queryAnalyzerDialog div.placeHolder').html('Analyzing... ' + ''); + + $.post('server_status.php?'+url_query, { + ajax_request: true, + query_analyzer: true, + query: codemirror_editor.getValue() + }, function(data) { + data = $.parseJSON(data); + var totalTime = 0; + + if(data.error) { + $('div#queryAnalyzerDialog div.placeHolder').html('
' + data.error + '
'); + return; + } + + // Float sux, I'll use table :( + $('div#queryAnalyzerDialog div.placeHolder') + .html('
) has to contain one and only one element (preferably div or span) + which is the actually draggable element. +*/ (function($) { jQuery.fn.sortableTable = function(method) { diff --git a/js/messages.php b/js/messages.php index b12a5e6565..7d7d786140 100644 --- a/js/messages.php +++ b/js/messages.php @@ -203,6 +203,7 @@ $js_messages['strSave'] = __('Save'); $js_messages['strHide'] = __('Hide'); $js_messages['strNoRowSelected'] = __('No rows selected'); $js_messages['strChangeTbl'] = __('Change'); +$js_messages['strQueryExecutionTime'] = __('Query execution time'); /* For tbl_select.js */ $js_messages['strHideSearchCriteria'] = __('Hide search criteria'); diff --git a/js/server_status.js b/js/server_status.js index 3e0fd6ed82..f06ecdf32e 100644 --- a/js/server_status.js +++ b/js/server_status.js @@ -1500,21 +1500,21 @@ $(function() { limitTypes: opts.limitTypes }, function(data) { - runtime.logData = $.parseJSON(data); + var logData = $.parseJSON(data); - if(runtime.logData.rows.length != 0) { - runtime.logDataCols = buildLogTable(runtime.logData); + if(logData.rows.length != 0) { + runtime.logDataCols = buildLogTable(logData); /* Show some stats in the dialog */ $('#loadingLogsDialog').html('

' + PMA_messages['strLogDataLoaded'] + '

'); - $.each(runtime.logData.sum, function(key, value) { + $.each(logData.sum, function(key, value) { key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase(); if(key == 'Total') key = '' + key + ''; $('#loadingLogsDialog').append(key + ': ' + value + '
'); }); /* Add filter options if more than a bunch of rows there to filter */ - if(runtime.logData.numRows > 12) { + if(logData.numRows > 12) { $('div#logTable').prepend( '
' + ' ' + PMA_messages['strFilters'] + '' + @@ -1522,7 +1522,7 @@ $(function() { ' ' + ' ' + ' ' + - ((runtime.logData.numRows > 250) ? '
' : '') + + ((logData.numRows > 250) ? '
' : '') + '
' + ' ' + ' ' + @@ -1536,7 +1536,7 @@ $(function() { //preg_replace('/\s+([^=]+)=(\d+|((\'|"|)(?U)(.+)(? 250) { + if(logData.numRows > 250) { $('div#logTable button#startFilterQueryText').click(filterQueries); } else { $('div#logTable input#filterQueryText').keyup(filterQueries); @@ -1604,8 +1604,8 @@ $(function() { } } else { - $(this).text(runtime.logData.rows[i][queryColumnName]); - $(this).next().text('' + runtime.logData.rows[i][sumColumnName]); + $(this).text($(this).parent().data('query')[queryColumnName]); + $(this).next().text($(this).parent().data('query')[sumColumnName]); } } @@ -1658,11 +1658,21 @@ $(function() { } } + loadLogStatistics({ + src: 'general', + start:1311076210*1000, + end:1311162689*1000, + removeVariables: true, + limitTypes: true + }); + function buildLogTable(data) { var rows = data.rows; var cols = new Array(); + var $table = $('
'); + var $tBody, $tRow, $tCell; - var tableStr = ''; + $('#logTable').html($table); var formatValue = function(name, value) { switch(name) { @@ -1674,27 +1684,152 @@ $(function() { for(var i=0; i < rows.length; i++) { if(i == 0) { - tableStr += ''; $.each(rows[0],function(key, value) { cols.push(key); }); - tableStr += ''; - tableStr += ''; + $table.append( '' + + '' + + ''); + + $table.append($tBody = $('')); } - tableStr += ''; - for(var j=0; j < cols.length; j++) - tableStr += ''; - tableStr += ''; + $tBody.append($tRow = $('')); + var cl='' + for(var j=0; j < cols.length; j++) { + // Assuming the query column is the second last + if(j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) { + $tRow.append($tCell=$('')); + $tCell.click(queryAnalyzer); + } else + $tRow.append(''); + + + $tRow.data('query',rows[i]); + } } - tableStr += ''; - tableStr += '' + + ''; - tableStr += '
' + cols.join('') + '
' + cols.join('') + '
' + formatValue(cols[j], rows[i][cols[j]]) + '
' + formatValue(cols[j], rows[i][cols[j]]) + '' + formatValue(cols[j], rows[i][cols[j]]) + '
' + PMA_messages['strSumRows'] + + $table.append('
' + PMA_messages['strSumRows'] + ' '+ data.numRows +'' + PMA_messages['strTotal'] + - '' + data.sum.TOTAL + '
'; + '
' + data.sum.TOTAL + '
'); + + var explain = 'Explain output

'; + $.each(data.explain, function(key,value) { + value = (value==null)?'null':value; + + explain += key+': ' + value + '
'; + }); + $('div#queryAnalyzerDialog div.placeHolder td.explain').append(explain); + + if(data.profiling) { + var chartData = []; + var numberTable = ''; + var duration; + + for(var i=0; i < data.profiling.length; i++) { + duration = parseFloat(data.profiling[i].duration); + + chartData.push([data.profiling[i].state, duration]); + totalTime+=duration; + + numberTable += ''; + } + numberTable += ''; + numberTable += '
StatusTime
' + data.profiling[i].state + ' ' + PMA_prettyProfilingNum(duration,2) + '
Total time:' + PMA_prettyProfilingNum(totalTime,2) + '
'; + + $('div#queryAnalyzerDialog div.placeHolder td.chart').append('Profiling results (Table | Chart)
' + numberTable + '
'); + + $('div#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function() { + $('div#queryAnalyzerDialog div#queryProfiling').hide(); + $('div#queryAnalyzerDialog table.queryNums').show(); + return false; + }); + + $('div#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function() { + $('div#queryAnalyzerDialog div#queryProfiling').show(); + $('div#queryAnalyzerDialog table.queryNums').hide(); + return false; + }); + + profilingChart = PMA_createProfilingChart(chartData, { + chart: { + renderTo: 'queryProfiling' + }, + plotOptions: { + pie: { + size: '50%' + } + } + }); + + + $('div#queryProfiling').resizable(); + } + + }); + }, + 'Close' : function() { + if(profilingChart != null) { + profilingChart.destroy(); + } + $('div#queryAnalyzerDialog div.placeHolder').html(''); + codemirror_editor.setValue(''); + + $(this).dialog("close"); + } + } + }); + } // Append a tooltip to the count column, if there exist one if($('#logTable th:last').html() == '#') { @@ -1715,7 +1850,7 @@ $(function() { hide: { delay: 1000 } }) } - + $('div#logTable table').tablesorter({ sortList: [[cols.length - 1,1]], widgets: ['zebra'] diff --git a/js/sql.js b/js/sql.js index 04267994c7..168fcdeab7 100644 --- a/js/sql.js +++ b/js/sql.js @@ -1227,45 +1227,18 @@ $(document).ready(function() { /* * Profiling Chart */ -function createProfilingChart() { +function makeProfilingChart() { if($('#profilingchart').length==0) return; - var cdata = new Array(); + var data = new Array(); $.each(jQuery.parseJSON($('#profilingchart').html()),function(key,value) { - cdata.push([key,parseFloat(value)]); + data.push([key,parseFloat(value)]); }); // Prevent the user from seeing the JSON code $('div#profilingchart').html('').show(); - PMA_createChart({ - chart: { - renderTo: 'profilingchart', - backgroundColor: $('#sqlqueryresults fieldset').css('background-color') - }, - title: { text:'', margin:0 }, - series: [{ - type:'pie', - name: 'Query execution time', - data: cdata - }], - plotOptions: { - pie: { - allowPointSelect: true, - cursor: 'pointer', - dataLabels: { - enabled: true, - distance: 35, - formatter: function() { - return ''+ this.point.name +'
'+ Highcharts.numberFormat(this.percentage, 2) +' %'; - } - } - } - }, - tooltip: { - formatter: function() { return ''+ this.point.name +'
'+this.y+'s
('+Highcharts.numberFormat(this.percentage, 2) +' %)'; } - } - }); + PMA_createProfilingChart(data); } diff --git a/server_status.php b/server_status.php index e14467a45a..4883ff494f 100644 --- a/server_status.php +++ b/server_status.php @@ -20,21 +20,6 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) require_once './libraries/common.inc.php'; -/** - * Function to output refresh rate selection. - */ -function PMA_choose_refresh_rate() { - echo ''; - foreach (array(1, 2, 5, 20, 40, 60, 120, 300, 600) as $rate) { - if ($rate % 60 == 0) { - $minrate = $rate / 60; - echo ''; - } else { - echo ''; - } - } -} - /** * Ajax request */ @@ -43,20 +28,6 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { // Send with correct charset header('Content-Type: text/html; charset=UTF-8'); - if (isset($_REQUEST['logging_vars'])) { - if(isset($_REQUEST['varName']) && isset($_REQUEST['varValue'])) { - $value = PMA_sqlAddslashes($_REQUEST['varValue']); - if(!is_numeric($value)) $value="'".$value."'"; - - if(! preg_match("/[^a-zA-Z0-9_]+/",$_REQUEST['varName'])) - PMA_DBI_query('SET GLOBAL '.$_REQUEST['varName'].' = '.$value); - - } - - $loggingVars = PMA_DBI_fetch_result('SHOW GLOBAL VARIABLES WHERE Variable_name IN ("general_log","slow_query_log","long_query_time","log_output")', 0, 1); - exit(json_encode($loggingVars)); - } - // real-time charting data if (isset($_REQUEST['chart_data'])) { switch($_REQUEST['type']) { @@ -261,6 +232,49 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { exit(json_encode($return)); } } + + if (isset($_REQUEST['logging_vars'])) { + if(isset($_REQUEST['varName']) && isset($_REQUEST['varValue'])) { + $value = PMA_sqlAddslashes($_REQUEST['varValue']); + if(!is_numeric($value)) $value="'".$value."'"; + + if(! preg_match("/[^a-zA-Z0-9_]+/",$_REQUEST['varName'])) + PMA_DBI_query('SET GLOBAL '.$_REQUEST['varName'].' = '.$value); + + } + + $loggingVars = PMA_DBI_fetch_result('SHOW GLOBAL VARIABLES WHERE Variable_name IN ("general_log","slow_query_log","long_query_time","log_output")', 0, 1); + exit(json_encode($loggingVars)); + } + + if(isset($_REQUEST['query_analyzer'])) { + $return = array(); + + if ($profiling = PMA_profilingSupported()) + PMA_DBI_query('SET PROFILING=1;'); + + // Do not cache query + $query = preg_replace('/^(\s*SELECT)/i','\\1 SQL_NO_CACHE',$_REQUEST['query']); + + $result = PMA_DBI_try_query('EXPLAIN ' . $query); + $return['explain'] = PMA_DBI_fetch_assoc($result); + + // In case an error happened + $return['error'] = PMA_DBI_getError(); + + PMA_DBI_free_result($result); + + if($profiling) { + $return['profiling'] = array(); + $result = PMA_DBI_try_query('SELECT seq,state,duration FROM INFORMATION_SCHEMA.PROFILING WHERE QUERY_ID=1 ORDER BY seq'); + while ($row = PMA_DBI_fetch_assoc($result)) { + $return['profiling'][]= $row; + } + PMA_DBI_free_result($result); + } + + exit(json_encode($return)); + } } @@ -1446,6 +1460,12 @@ function printMonitor() { Choose from which log you want the statistics to be generated from.

Results are grouped by query text.'); ?>
+ +
diff --git a/sql.php b/sql.php index a211042de6..96999011bd 100644 --- a/sql.php +++ b/sql.php @@ -932,7 +932,7 @@ else { ' . __('Profiling') . '' . "\n"; diff --git a/themes/pmahomme/css/theme_right.css.php b/themes/pmahomme/css/theme_right.css.php index 4707859b64..ef44841dd2 100644 --- a/themes/pmahomme/css/theme_right.css.php +++ b/themes/pmahomme/css/theme_right.css.php @@ -1308,6 +1308,12 @@ div#tablestatistics table { /* serverstatus */ +div#logTable table td.analyzableQuery:hover { + text-decoration: underline; + color: #235a81; + cursor: pointer; +} + h3#serverstatusqueries span { font-size:60%; display:inline; @@ -1316,7 +1322,7 @@ h3#serverstatusqueries span { img.sortableIcon { float:right; background-repeat:no-repeat; - margin:0; + margin:0; } .buttonlinks { @@ -1425,10 +1431,33 @@ div#logTable table { width:100%; } +div#queryAnalyzerDialog { + min-width: 700px; +} + +div#queryAnalyzerDialog div.CodeMirror-scroll { + height:auto; +} + +div#queryAnalyzerDialog div#queryProfiling { + height: 250px; +} + +div#queryAnalyzerDialog td.explain { + width: 250px; +} + +div#queryAnalyzerDialog table.queryNums { + display: none; + border:0; + text-align:left; +} + .smallIndent { padding-left: 7px; } + /* end serverstatus */ /* server variables */ From 64d2cb7e5ede1a62bfb66d1f32e9804c0fbed147 Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Thu, 21 Jul 2011 13:43:21 +0300 Subject: [PATCH 012/206] Removed debug code --- js/server_status.js | 8 -------- 1 file changed, 8 deletions(-) diff --git a/js/server_status.js b/js/server_status.js index f06ecdf32e..92cbda13ad 100644 --- a/js/server_status.js +++ b/js/server_status.js @@ -1658,14 +1658,6 @@ $(function() { } } - loadLogStatistics({ - src: 'general', - start:1311076210*1000, - end:1311162689*1000, - removeVariables: true, - limitTypes: true - }); - function buildLogTable(data) { var rows = data.rows; var cols = new Array(); From def2df01f303d17250f1854f079f0c0c95eee30c Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Thu, 21 Jul 2011 15:26:30 +0300 Subject: [PATCH 013/206] Fix: undefined index php notice Fix: INSERT queries not being grouped --- server_status.php | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/server_status.php b/server_status.php index 4883ff494f..3367dee26c 100644 --- a/server_status.php +++ b/server_status.php @@ -185,8 +185,9 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { while ($row = PMA_DBI_fetch_assoc($result)) { preg_match('/^(\w+)\s/',$row['argument'],$match); $type = strtolower($match[1]); - // Ignore undefined index warning, just increase counter by one - @$return['sum'][$type] += $row['#']; + + if(!isset($return['sum'][$type])) $return['sum'][$type] = 0; + $return['sum'][$type] += $row['#']; switch($type) { case 'insert': @@ -201,7 +202,7 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { $return['rows'][$insertTablesFirst]['argument'] .= '
...'; // Group this value, thus do not add to the result list - continue; + continue 2; } else { $insertTablesFirst = $i; $insertTables[$matches[2]] += $row['#'] - 1; @@ -253,23 +254,23 @@ if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) { if ($profiling = PMA_profilingSupported()) PMA_DBI_query('SET PROFILING=1;'); - // Do not cache query - $query = preg_replace('/^(\s*SELECT)/i','\\1 SQL_NO_CACHE',$_REQUEST['query']); - + // Do not cache query + $query = preg_replace('/^(\s*SELECT)/i','\\1 SQL_NO_CACHE',$_REQUEST['query']); + $result = PMA_DBI_try_query('EXPLAIN ' . $query); $return['explain'] = PMA_DBI_fetch_assoc($result); - - // In case an error happened - $return['error'] = PMA_DBI_getError(); - + + // In case an error happened + $return['error'] = PMA_DBI_getError(); + PMA_DBI_free_result($result); if($profiling) { - $return['profiling'] = array(); + $return['profiling'] = array(); $result = PMA_DBI_try_query('SELECT seq,state,duration FROM INFORMATION_SCHEMA.PROFILING WHERE QUERY_ID=1 ORDER BY seq'); - while ($row = PMA_DBI_fetch_assoc($result)) { - $return['profiling'][]= $row; - } + while ($row = PMA_DBI_fetch_assoc($result)) { + $return['profiling'][]= $row; + } PMA_DBI_free_result($result); } @@ -1462,8 +1463,8 @@ function printMonitor() { From 0530016f381c52f683b5a6a2d40e313ae7c427ed Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Thu, 21 Jul 2011 15:45:41 +0300 Subject: [PATCH 014/206] With backgroundColor: 'transparent' Opera and IE draw black background on all charts. Using 'none' seems to work well on all major browsers --- js/functions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/functions.js b/js/functions.js index ce2c867bc3..51b7ab8ea9 100644 --- a/js/functions.js +++ b/js/functions.js @@ -1466,7 +1466,7 @@ function PMA_createChart(passedSettings) { chart: { type: 'spline', marginRight: 10, - backgroundColor: 'transparent', + backgroundColor: 'none', events: { /* Live charting support */ load: function() { From bf20f06683000cb7a2f31184a61c6f57161924c7 Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Thu, 21 Jul 2011 17:46:03 +0300 Subject: [PATCH 015/206] Adjusted some places to adjust to current master changes, plus IE8 fix for Status page --- js/server_status.js | 8 ++++---- server_status.php | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/js/server_status.js b/js/server_status.js index 92cbda13ad..42e5734c65 100644 --- a/js/server_status.js +++ b/js/server_status.js @@ -368,7 +368,7 @@ $(function() { switch(tab.attr('id')) { case 'statustabs_traffic': if(data != null) tab.find('.tabInnerContent').html(data); - initTooltips(); + PMA_convertFootnotesToTooltips(); break; case 'statustabs_queries': if(data != null) { @@ -1595,7 +1595,6 @@ $(function() { if(filteredQueries[q]) { filteredQueries[q] += parseInt($(this).next().text()); totalSum += parseInt($(this).next().text()); - rowSum ++; hide = true; } else { filteredQueries[q] = parseInt($(this).next().text());; @@ -1654,7 +1653,7 @@ $(function() { $('div#logTable table tfoot tr') .html(''); + PMA_messages['strTotal'] + ''); } } @@ -1714,7 +1713,8 @@ $(function() { - Any string appearance containing a MySQL Keyword, surrounded by whitespaces - Subqueries too probably */ - var sLists = query.match(/SELECT\s+[^]+\s+FROM\s+/gi); + // .* 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 ;) + var sLists = query.match(/SELECT\s+[^\0]+\s+FROM\s+/gi); if(sLists) { for(var i=0; i < sLists.length; i++) { query = query.replace(sLists[i],sLists[i].replace(/\s*((`|'|"|).*?\1,)\s*/gi,'$1\n\t')); diff --git a/server_status.php b/server_status.php index b2206ce3f9..15dfb68882 100644 --- a/server_status.php +++ b/server_status.php @@ -312,6 +312,8 @@ $GLOBALS['js_include'][] = 'highcharts/exporting.js'; $GLOBALS['js_include'][] = 'canvg/flashcanvas.js'; $GLOBALS['js_include'][] = 'canvg/canvg.js'; $GLOBALS['js_include'][] = 'canvg/rgbcolor.js'; +$GLOBALS['js_include'][] = 'codemirror/lib/codemirror.js'; +$GLOBALS['js_include'][] = 'codemirror/mode/mysql/mysql.js'; /** * flush status variables if requested From 2689428b3866725a8de292ad3039efc78c86ea19 Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Fri, 22 Jul 2011 11:39:59 +0300 Subject: [PATCH 016/206] debug logging for linux cpu chart --- js/server_status.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/js/server_status.js b/js/server_status.js index 42e5734c65..42789ed4b0 100644 --- a/js/server_status.js +++ b/js/server_status.js @@ -616,6 +616,9 @@ $(function() { name: PMA_messages['strAverageLoad'], unit: '%', transformFn: function(cur, prev) { + console.log('cpu-linux chart, transformFn()'); + console.log(cur); + console.log(prev); if(prev == null) return undefined; var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle); var diff_idle = cur.idle - prev.idle; @@ -1131,7 +1134,7 @@ $(function() { var serie = { dataType:'statusvar', name: $('input#variableInput').attr('value'), - display: $('input[name="differentialValue"]').attr('checked') ? 'differential' : '', + display: $('input[name="differentialValue"]').attr('checked') ? 'differential' : '' }; if(serie.name == 'Processes') serie.dataType='proc'; @@ -1338,7 +1341,7 @@ $(function() { }, series: series, buttons: gridbuttons, - title: { text: chartObj.title }, + title: { text: chartObj.title } }; if(chartObj.settings) @@ -1656,6 +1659,14 @@ $(function() { PMA_messages['strTotal'] + ''); } } + + /*loadLogStatistics({ + src: 'general', + start:1311076210*1000, + end:1311162689*1000, + removeVariables: true, + limitTypes: true + });*/ function buildLogTable(data) { var rows = data.rows; From 9ee8ff38c3388dce4cbee016c278f0602601dc27 Mon Sep 17 00:00:00 2001 From: Tyron Madlener Date: Fri, 22 Jul 2011 11:41:13 +0300 Subject: [PATCH 017/206] Replaced qtTip js library with non-minified version. --- js/jquery/jquery.qtip-1.0.0-rc3.js | 2149 ++++++++++++++++++++++++++++ js/jquery/jquery.qtip-1.0.0.min.js | 15 - libraries/header_scripts.inc.php | 2 +- 3 files changed, 2150 insertions(+), 16 deletions(-) create mode 100644 js/jquery/jquery.qtip-1.0.0-rc3.js delete mode 100644 js/jquery/jquery.qtip-1.0.0.min.js diff --git a/js/jquery/jquery.qtip-1.0.0-rc3.js b/js/jquery/jquery.qtip-1.0.0-rc3.js new file mode 100644 index 0000000000..5b9c7e3064 --- /dev/null +++ b/js/jquery/jquery.qtip-1.0.0-rc3.js @@ -0,0 +1,2149 @@ +/*! + * jquery.qtip. The jQuery tooltip plugin + * + * Copyright (c) 2009 Craig Thompson + * http://craigsworks.com + * + * Licensed under MIT + * http://www.opensource.org/licenses/mit-license.php + * + * Launch : February 2009 + * Version : 1.0.0-rc3 + * Released: Tuesday 12th May, 2009 - 00:00 + * Debug: jquery.qtip.debug.js + */ +(function($) +{ + // Implementation + $.fn.qtip = function(options, blanket) + { + var i, id, interfaces, opts, obj, command, config, api; + + // Return API / Interfaces if requested + if(typeof options == 'string') + { + // Make sure API data exists if requested + if(typeof $(this).data('qtip') !== 'object') + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.NO_TOOLTIP_PRESENT, false); + + // Return requested object + if(options == 'api') + return $(this).data('qtip').interfaces[ $(this).data('qtip').current ]; + else if(options == 'interfaces') + return $(this).data('qtip').interfaces; + } + + // Validate provided options + else + { + // Set null options object if no options are provided + if(!options) options = {}; + + // Sanitize option data + if(typeof options.content !== 'object' || (options.content.jquery && options.content.length > 0)) options.content = { text: options.content }; + if(typeof options.content.title !== 'object') options.content.title = { text: options.content.title }; + if(typeof options.position !== 'object') options.position = { corner: options.position }; + if(typeof options.position.corner !== 'object') options.position.corner = { target: options.position.corner, tooltip: options.position.corner }; + if(typeof options.show !== 'object') options.show = { when: options.show }; + if(typeof options.show.when !== 'object') options.show.when = { event: options.show.when }; + if(typeof options.show.effect !== 'object') options.show.effect = { type: options.show.effect }; + if(typeof options.hide !== 'object') options.hide = { when: options.hide }; + if(typeof options.hide.when !== 'object') options.hide.when = { event: options.hide.when }; + if(typeof options.hide.effect !== 'object') options.hide.effect = { type: options.hide.effect }; + if(typeof options.style !== 'object') options.style = { name: options.style }; + options.style = sanitizeStyle(options.style); + + // Build main options object + opts = $.extend(true, {}, $.fn.qtip.defaults, options); + + // Inherit all style properties into one syle object and include original options + opts.style = buildStyle.call({ options: opts }, opts.style); + opts.user = $.extend(true, {}, options); + }; + + // Iterate each matched element + return $(this).each(function() // Return original elements as per jQuery guidelines + { + // Check for API commands + if(typeof options == 'string') + { + command = options.toLowerCase(); + interfaces = $(this).qtip('interfaces'); + + // Make sure API data exists$('.qtip').qtip('destroy') + if(typeof interfaces == 'object') + { + // Check if API call is a BLANKET DESTROY command + if(blanket === true && command == 'destroy') + while(interfaces.length > 0) interfaces[interfaces.length-1].destroy(); + + // API call is not a BLANKET DESTROY command + else + { + // Check if supplied command effects this tooltip only (NOT BLANKET) + if(blanket !== true) interfaces = [ $(this).qtip('api') ]; + + // Execute command on chosen qTips + for(i = 0; i < interfaces.length; i++) + { + // Destroy command doesn't require tooltip to be rendered + if(command == 'destroy') interfaces[i].destroy(); + + // Only call API if tooltip is rendered and it wasn't a destroy call + else if(interfaces[i].status.rendered === true) + { + if(command == 'show') interfaces[i].show(); + else if(command == 'hide') interfaces[i].hide(); + else if(command == 'focus') interfaces[i].focus(); + else if(command == 'disable') interfaces[i].disable(true); + else if(command == 'enable') interfaces[i].disable(false); + }; + }; + }; + }; + } + + // No API commands, continue with qTip creation + else + { + // Create unique configuration object + config = $.extend(true, {}, opts); + config.hide.effect.length = opts.hide.effect.length; + config.show.effect.length = opts.show.effect.length; + + // Sanitize target options + if(config.position.container === false) config.position.container = $(document.body); + if(config.position.target === false) config.position.target = $(this); + if(config.show.when.target === false) config.show.when.target = $(this); + if(config.hide.when.target === false) config.hide.when.target = $(this); + + // Determine tooltip ID (Reuse array slots if possible) + id = $.fn.qtip.interfaces.length; + for(i = 0; i < id; i++) + { + if(typeof $.fn.qtip.interfaces[i] == 'undefined'){ id = i; break; }; + }; + + // Instantiate the tooltip + obj = new qTip($(this), config, id); + + // Add API references + $.fn.qtip.interfaces[id] = obj; + + // Check if element already has qTip data assigned + if(typeof $(this).data('qtip') == 'object') + { + // Set new current interface id + if(typeof $(this).attr('qtip') === 'undefined') + $(this).data('qtip').current = $(this).data('qtip').interfaces.length; + + // Push new API interface onto interfaces array + $(this).data('qtip').interfaces.push(obj); + } + + // No qTip data is present, create now + else $(this).data('qtip', { current: 0, interfaces: [obj] }); + + // If prerendering is disabled, create tooltip on showEvent + if(config.content.prerender === false && config.show.when.event !== false && config.show.ready !== true) + { + config.show.when.target.bind(config.show.when.event+'.qtip-'+id+'-create', { qtip: id }, function(event) + { + // Retrieve API interface via passed qTip Id + api = $.fn.qtip.interfaces[ event.data.qtip ]; + + // Unbind show event and cache mouse coords + api.options.show.when.target.unbind(api.options.show.when.event+'.qtip-'+event.data.qtip+'-create'); + api.cache.mouse = { x: event.pageX, y: event.pageY }; + + // Render tooltip and start the event sequence + construct.call( api ); + api.options.show.when.target.trigger(api.options.show.when.event); + }); + } + + // Prerendering is enabled, create tooltip now + else + { + // Set mouse position cache to top left of the element + obj.cache.mouse = { + x: config.show.when.target.offset().left, + y: config.show.when.target.offset().top + }; + + // Construct the tooltip + construct.call(obj); + } + }; + }); + }; + + // Instantiator + function qTip(target, options, id) + { + // Declare this reference + var self = this; + + // Setup class attributes + self.id = id; + self.options = options; + self.status = { + animated: false, + rendered: false, + disabled: false, + focused: false + }; + self.elements = { + target: target.addClass(self.options.style.classes.target), + tooltip: null, + wrapper: null, + content: null, + contentWrapper: null, + title: null, + button: null, + tip: null, + bgiframe: null + }; + self.cache = { + mouse: {}, + position: {}, + toggle: 0 + }; + self.timers = {}; + + // Define exposed API methods + $.extend(self, self.options.api, + { + show: function(event) + { + var returned, solo; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'show'); + + // Only continue if element is visible + if(self.elements.tooltip.css('display') !== 'none') return self; + + // Clear animation queue + self.elements.tooltip.stop(true, false); + + // Call API method and if return value is false, halt + returned = self.beforeShow.call(self, event); + if(returned === false) return self; + + // Define afterShow callback method + function afterShow() + { + // Call API method and focus if it isn't static + if(self.options.position.type !== 'static') self.focus(); + self.onShow.call(self, event); + + // Prevent antialias from disappearing in IE7 by removing filter attribute + if($.browser.msie) self.elements.tooltip.get(0).style.removeAttribute('filter'); + }; + + // Maintain toggle functionality if enabled + self.cache.toggle = 1; + + // Update tooltip position if it isn't static + if(self.options.position.type !== 'static') + self.updatePosition(event, (self.options.show.effect.length > 0)); + + // Hide other tooltips if tooltip is solo + if(typeof self.options.show.solo == 'object') solo = $(self.options.show.solo); + else if(self.options.show.solo === true) solo = $('div.qtip').not(self.elements.tooltip); + if(solo) solo.each(function(){ if($(this).qtip('api').status.rendered === true) $(this).qtip('api').hide(); }); + + // Show tooltip + if(typeof self.options.show.effect.type == 'function') + { + self.options.show.effect.type.call(self.elements.tooltip, self.options.show.effect.length); + self.elements.tooltip.queue(function(){ afterShow(); $(this).dequeue(); }); + } + else + { + switch(self.options.show.effect.type.toLowerCase()) + { + case 'fade': + self.elements.tooltip.fadeIn(self.options.show.effect.length, afterShow); + break; + case 'slide': + self.elements.tooltip.slideDown(self.options.show.effect.length, function() + { + afterShow(); + if(self.options.position.type !== 'static') self.updatePosition(event, true); + }); + break; + case 'grow': + self.elements.tooltip.show(self.options.show.effect.length, afterShow); + break; + default: + self.elements.tooltip.show(null, afterShow); + break; + }; + + // Add active class to tooltip + self.elements.tooltip.addClass(self.options.style.classes.active); + }; + + // Log event and return + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_SHOWN, 'show'); + }, + + hide: function(event) + { + var returned; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'hide'); + + // Only continue if element is visible + else if(self.elements.tooltip.css('display') === 'none') return self; + + // Stop show timer and animation queue + clearTimeout(self.timers.show); + self.elements.tooltip.stop(true, false); + + // Call API method and if return value is false, halt + returned = self.beforeHide.call(self, event); + if(returned === false) return self; + + // Define afterHide callback method + function afterHide(){ self.onHide.call(self, event); }; + + // Maintain toggle functionality if enabled + self.cache.toggle = 0; + + // Hide tooltip + if(typeof self.options.hide.effect.type == 'function') + { + self.options.hide.effect.type.call(self.elements.tooltip, self.options.hide.effect.length); + self.elements.tooltip.queue(function(){ afterHide(); $(this).dequeue(); }); + } + else + { + switch(self.options.hide.effect.type.toLowerCase()) + { + case 'fade': + self.elements.tooltip.fadeOut(self.options.hide.effect.length, afterHide); + break; + case 'slide': + self.elements.tooltip.slideUp(self.options.hide.effect.length, afterHide); + break; + case 'grow': + self.elements.tooltip.hide(self.options.hide.effect.length, afterHide); + break; + default: + self.elements.tooltip.hide(null, afterHide); + break; + }; + + // Remove active class to tooltip + self.elements.tooltip.removeClass(self.options.style.classes.active); + }; + + // Log event and return + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_HIDDEN, 'hide'); + }, + + updatePosition: function(event, animate) + { + var i, target, tooltip, coords, mapName, imagePos, newPosition, ieAdjust, ie6Adjust, borderAdjust, mouseAdjust, offset, curPosition, returned + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'updatePosition'); + + // If tooltip is static, return + else if(self.options.position.type == 'static') + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.CANNOT_POSITION_STATIC, 'updatePosition'); + + // Define property objects + target = { + position: { left: 0, top: 0 }, + dimensions: { height: 0, width: 0 }, + corner: self.options.position.corner.target + }; + tooltip = { + position: self.getPosition(), + dimensions: self.getDimensions(), + corner: self.options.position.corner.tooltip + }; + + // Target is an HTML element + if(self.options.position.target !== 'mouse') + { + // If the HTML element is AREA, calculate position manually + if(self.options.position.target.get(0).nodeName.toLowerCase() == 'area') + { + // Retrieve coordinates from coords attribute and parse into integers + coords = self.options.position.target.attr('coords').split(','); + for(i = 0; i < coords.length; i++) coords[i] = parseInt(coords[i]); + + // Setup target position object + mapName = self.options.position.target.parent('map').attr('name'); + imagePos = $('img[usemap="#'+mapName+'"]:first').offset(); + target.position = { + left: Math.floor(imagePos.left + coords[0]), + top: Math.floor(imagePos.top + coords[1]) + }; + + // Determine width and height of the area + switch(self.options.position.target.attr('shape').toLowerCase()) + { + case 'rect': + target.dimensions = { + width: Math.ceil(Math.abs(coords[2] - coords[0])), + height: Math.ceil(Math.abs(coords[3] - coords[1])) + }; + break; + + case 'circle': + target.dimensions = { + width: coords[2] + 1, + height: coords[2] + 1 + }; + break; + + case 'poly': + target.dimensions = { + width: coords[0], + height: coords[1] + }; + + for(i = 0; i < coords.length; i++) + { + if(i % 2 == 0) + { + if(coords[i] > target.dimensions.width) + target.dimensions.width = coords[i]; + if(coords[i] < coords[0]) + target.position.left = Math.floor(imagePos.left + coords[i]); + } + else + { + if(coords[i] > target.dimensions.height) + target.dimensions.height = coords[i]; + if(coords[i] < coords[1]) + target.position.top = Math.floor(imagePos.top + coords[i]); + }; + }; + + target.dimensions.width = target.dimensions.width - (target.position.left - imagePos.left); + target.dimensions.height = target.dimensions.height - (target.position.top - imagePos.top); + break; + + default: + return $.fn.qtip.log.error.call(self, 4, $.fn.qtip.constants.INVALID_AREA_SHAPE, 'updatePosition'); + break; + }; + + // Adjust position by 2 pixels (Positioning bug?) + target.dimensions.width -= 2; target.dimensions.height -= 2; + } + + // Target is the document + else if(self.options.position.target.add(document.body).length === 1) + { + target.position = { left: $(document).scrollLeft(), top: $(document).scrollTop() }; + target.dimensions = { height: $(window).height(), width: $(window).width() }; + } + + // Target is a regular HTML element, find position normally + else + { + // Check if the target is another tooltip. If its animated, retrieve position from newPosition data + if(typeof self.options.position.target.attr('qtip') !== 'undefined') + target.position = self.options.position.target.qtip('api').cache.position; + else + target.position = self.options.position.target.offset(); + + // Setup dimensions objects + target.dimensions = { + height: self.options.position.target.outerHeight(), + width: self.options.position.target.outerWidth() + }; + }; + + // Calculate correct target corner position + newPosition = $.extend({}, target.position); + if(target.corner.search(/right/i) !== -1) + newPosition.left += target.dimensions.width; + + if(target.corner.search(/bottom/i) !== -1) + newPosition.top += target.dimensions.height; + + if(target.corner.search(/((top|bottom)Middle)|center/) !== -1) + newPosition.left += (target.dimensions.width / 2); + + if(target.corner.search(/((left|right)Middle)|center/) !== -1) + newPosition.top += (target.dimensions.height / 2); + } + + // Mouse is the target, set position to current mouse coordinates + else + { + // Setup target position and dimensions objects + target.position = newPosition = { left: self.cache.mouse.x, top: self.cache.mouse.y }; + target.dimensions = { height: 1, width: 1 }; + }; + + // Calculate correct target corner position + if(tooltip.corner.search(/right/i) !== -1) + newPosition.left -= tooltip.dimensions.width; + + if(tooltip.corner.search(/bottom/i) !== -1) + newPosition.top -= tooltip.dimensions.height; + + if(tooltip.corner.search(/((top|bottom)Middle)|center/) !== -1) + newPosition.left -= (tooltip.dimensions.width / 2); + + if(tooltip.corner.search(/((left|right)Middle)|center/) !== -1) + newPosition.top -= (tooltip.dimensions.height / 2); + + // Setup IE adjustment variables (Pixel gap bugs) + ieAdjust = ($.browser.msie) ? 1 : 0; // And this is why I hate IE... + ie6Adjust = ($.browser.msie && parseInt($.browser.version.charAt(0)) === 6) ? 1 : 0; // ...and even more so IE6! + + // Adjust for border radius + if(self.options.style.border.radius > 0) + { + if(tooltip.corner.search(/Left/) !== -1) + newPosition.left -= self.options.style.border.radius; + else if(tooltip.corner.search(/Right/) !== -1) + newPosition.left += self.options.style.border.radius; + + if(tooltip.corner.search(/Top/) !== -1) + newPosition.top -= self.options.style.border.radius; + else if(tooltip.corner.search(/Bottom/) !== -1) + newPosition.top += self.options.style.border.radius; + }; + + // IE only adjustments (Pixel perfect!) + if(ieAdjust) + { + if(tooltip.corner.search(/top/) !== -1) + newPosition.top -= ieAdjust + else if(tooltip.corner.search(/bottom/) !== -1) + newPosition.top += ieAdjust + + if(tooltip.corner.search(/left/) !== -1) + newPosition.left -= ieAdjust + else if(tooltip.corner.search(/right/) !== -1) + newPosition.left += ieAdjust + + if(tooltip.corner.search(/leftMiddle|rightMiddle/) !== -1) + newPosition.top -= 1 + }; + + // If screen adjustment is enabled, apply adjustments + if(self.options.position.adjust.screen === true) + newPosition = screenAdjust.call(self, newPosition, target, tooltip); + + // If mouse is the target, prevent tooltip appearing directly under the mouse + if(self.options.position.target === 'mouse' && self.options.position.adjust.mouse === true) + { + if(self.options.position.adjust.screen === true && self.elements.tip) + mouseAdjust = self.elements.tip.attr('rel'); + else + mouseAdjust = self.options.position.corner.tooltip; + + newPosition.left += (mouseAdjust.search(/right/i) !== -1) ? -6 : 6; + newPosition.top += (mouseAdjust.search(/bottom/i) !== -1) ? -6 : 6; + } + + // Initiate bgiframe plugin in IE6 if tooltip overlaps a select box or object element + if(!self.elements.bgiframe && $.browser.msie && parseInt($.browser.version.charAt(0)) == 6) + { + $('select, object').each(function() + { + offset = $(this).offset(); + offset.bottom = offset.top + $(this).height(); + offset.right = offset.left + $(this).width(); + + if(newPosition.top + tooltip.dimensions.height >= offset.top + && newPosition.left + tooltip.dimensions.width >= offset.left) + bgiframe.call(self); + }); + }; + + // Add user xy adjustments + newPosition.left += self.options.position.adjust.x; + newPosition.top += self.options.position.adjust.y; + + // Set new tooltip position if its moved, animate if enabled + curPosition = self.getPosition(); + if(newPosition.left != curPosition.left || newPosition.top != curPosition.top) + { + // Call API method and if return value is false, halt + returned = self.beforePositionUpdate.call(self, event); + if(returned === false) return self; + + // Cache new position + self.cache.position = newPosition; + + // Check if animation is enabled + if(animate === true) + { + // Set animated status + self.status.animated = true; + + // Animate and reset animated status on animation end + self.elements.tooltip.animate(newPosition, 200, 'swing', function(){ self.status.animated = false }); + } + + // Set new position via CSS + else self.elements.tooltip.css(newPosition); + + // Call API method and log event if its not a mouse move + self.onPositionUpdate.call(self, event); + if(typeof event !== 'undefined' && event.type && event.type !== 'mousemove') + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_POSITION_UPDATED, 'updatePosition'); + }; + + return self; + }, + + updateWidth: function(newWidth) + { + var hidden; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'updateWidth'); + + // Make sure supplied width is a number and if not, return + else if(newWidth && typeof newWidth !== 'number') + return $.fn.qtip.log.error.call(self, 2, 'newWidth must be of type number', 'updateWidth'); + + // Setup elements which must be hidden during width update + hidden = self.elements.contentWrapper.siblings().add(self.elements.tip).add(self.elements.button); + + // Calculate the new width if one is not supplied + if(!newWidth) + { + // Explicit width is set + if(typeof self.options.style.width.value == 'number') + newWidth = self.options.style.width.value; + + // No width is set, proceed with auto detection + else + { + // Set width to auto initally to determine new width and hide other elements + self.elements.tooltip.css({ width: 'auto' }); + hidden.hide(); + + // Set position and zoom to defaults to prevent IE hasLayout bug + if($.browser.msie) + self.elements.wrapper.add(self.elements.contentWrapper.children()).css({ zoom: 'normal' }); + + // Set the new width + newWidth = self.getDimensions().width + 1; + + // Make sure its within the maximum and minimum width boundries + if(!self.options.style.width.value) + { + if(newWidth > self.options.style.width.max) newWidth = self.options.style.width.max + if(newWidth < self.options.style.width.min) newWidth = self.options.style.width.min + }; + }; + }; + + // Adjust newWidth by 1px if width is odd (IE6 rounding bug fix) + if(newWidth % 2 !== 0) newWidth -= 1; + + // Set the new calculated width and unhide other elements + self.elements.tooltip.width(newWidth); + hidden.show(); + + // Set the border width, if enabled + if(self.options.style.border.radius) + { + self.elements.tooltip.find('.qtip-betweenCorners').each(function(i) + { + $(this).width(newWidth - (self.options.style.border.radius * 2)); + }) + }; + + // IE only adjustments + if($.browser.msie) + { + // Reset position and zoom to give the wrapper layout (IE hasLayout bug) + self.elements.wrapper.add(self.elements.contentWrapper.children()).css({ zoom: '1' }); + + // Set the new width + self.elements.wrapper.width(newWidth); + + // Adjust BGIframe height and width if enabled + if(self.elements.bgiframe) self.elements.bgiframe.width(newWidth).height(self.getDimensions.height); + }; + + // Log event and return + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_WIDTH_UPDATED, 'updateWidth'); + }, + + updateStyle: function(name) + { + var tip, borders, context, corner, coordinates; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'updateStyle'); + + // Return if style is not defined or name is not a string + else if(typeof name !== 'string' || !$.fn.qtip.styles[name]) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.STYLE_NOT_DEFINED, 'updateStyle'); + + // Set the new style object + self.options.style = buildStyle.call(self, $.fn.qtip.styles[name], self.options.user.style); + + // Update initial styles of content and title elements + self.elements.content.css( jQueryStyle(self.options.style) ); + if(self.options.content.title.text !== false) + self.elements.title.css( jQueryStyle(self.options.style.title, true) ); + + // Update CSS border colour + self.elements.contentWrapper.css({ borderColor: self.options.style.border.color }); + + // Update tip color if enabled + if(self.options.style.tip.corner !== false) + { + if($('').get(0).getContext) + { + // Retrieve canvas context and clear + tip = self.elements.tooltip.find('.qtip-tip canvas:first'); + context = tip.get(0).getContext('2d'); + context.clearRect(0,0,300,300); + + // Draw new tip + corner = tip.parent('div[rel]:first').attr('rel'); + coordinates = calculateTip(corner, self.options.style.tip.size.width, self.options.style.tip.size.height); + drawTip.call(self, tip, coordinates, self.options.style.tip.color || self.options.style.border.color); + } + else if($.browser.msie) + { + // Set new fillcolor attribute + tip = self.elements.tooltip.find('.qtip-tip [nodeName="shape"]'); + tip.attr('fillcolor', self.options.style.tip.color || self.options.style.border.color); + }; + }; + + // Update border colors if enabled + if(self.options.style.border.radius > 0) + { + self.elements.tooltip.find('.qtip-betweenCorners').css({ backgroundColor: self.options.style.border.color }); + + if($('').get(0).getContext) + { + borders = calculateBorders(self.options.style.border.radius) + self.elements.tooltip.find('.qtip-wrapper canvas').each(function() + { + // Retrieve canvas context and clear + context = $(this).get(0).getContext('2d'); + context.clearRect(0,0,300,300); + + // Draw new border + corner = $(this).parent('div[rel]:first').attr('rel') + drawBorder.call(self, $(this), borders[corner], + self.options.style.border.radius, self.options.style.border.color); + }); + } + else if($.browser.msie) + { + // Set new fillcolor attribute on each border corner + self.elements.tooltip.find('.qtip-wrapper [nodeName="arc"]').each(function() + { + $(this).attr('fillcolor', self.options.style.border.color) + }); + }; + }; + + // Log event and return + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_STYLE_UPDATED, 'updateStyle'); + }, + + updateContent: function(content, reposition) + { + var parsedContent, images, loadedImages; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'updateContent'); + + // Make sure content is defined before update + else if(!content) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.NO_CONTENT_PROVIDED, 'updateContent'); + + // Call API method and set new content if a string is returned + parsedContent = self.beforeContentUpdate.call(self, content); + if(typeof parsedContent == 'string') content = parsedContent; + else if(parsedContent === false) return; + + // Set position and zoom to defaults to prevent IE hasLayout bug + if($.browser.msie) self.elements.contentWrapper.children().css({ zoom: 'normal' }); + + // Append new content if its a DOM array and show it if hidden + if(content.jquery && content.length > 0) + content.clone(true).appendTo(self.elements.content).show(); + + // Content is a regular string, insert the new content + else self.elements.content.html(content); + + // Check if images need to be loaded before position is updated to prevent mis-positioning + images = self.elements.content.find('img[complete=false]'); + if(images.length > 0) + { + loadedImages = 0; + images.each(function(i) + { + $('') + .load(function(){ if(++loadedImages == images.length) afterLoad(); }); + }); + } + else afterLoad(); + + function afterLoad() + { + // Update the tooltip width + self.updateWidth(); + + // If repositioning is enabled, update positions + if(reposition !== false) + { + // Update position if tooltip isn't static + if(self.options.position.type !== 'static') + self.updatePosition(self.elements.tooltip.is(':visible'), true); + + // Reposition the tip if enabled + if(self.options.style.tip.corner !== false) + positionTip.call(self); + }; + }; + + // Call API method and log event + self.onContentUpdate.call(self); + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_CONTENT_UPDATED, 'loadContent'); + }, + + loadContent: function(url, data, method) + { + var returned; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'loadContent'); + + // Call API method and if return value is false, halt + returned = self.beforeContentLoad.call(self); + if(returned === false) return self; + + // Load content using specified request type + if(method == 'post') + $.post(url, data, setupContent); + else + $.get(url, data, setupContent); + + function setupContent(content) + { + // Call API method and log event + self.onContentLoad.call(self); + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_CONTENT_LOADED, 'loadContent'); + + // Update the content + self.updateContent(content); + }; + + return self; + }, + + updateTitle: function(content) + { + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'updateTitle'); + + // Make sure content is defined before update + else if(!content) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.NO_CONTENT_PROVIDED, 'updateTitle'); + + // Call API method and if return value is false, halt + returned = self.beforeTitleUpdate.call(self); + if(returned === false) return self; + + // Set the new content and reappend the button if enabled + if(self.elements.button) self.elements.button = self.elements.button.clone(true); + self.elements.title.html(content) + if(self.elements.button) self.elements.title.prepend(self.elements.button); + + // Call API method and log event + self.onTitleUpdate.call(self); + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_TITLE_UPDATED, 'updateTitle'); + }, + + focus: function(event) + { + var curIndex, newIndex, elemIndex, returned; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'focus'); + + else if(self.options.position.type == 'static') + return $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.CANNOT_FOCUS_STATIC, 'focus'); + + // Set z-index variables + curIndex = parseInt( self.elements.tooltip.css('z-index') ); + newIndex = 6000 + $('div.qtip[qtip]').length - 1; + + // Only update the z-index if it has changed and tooltip is not already focused + if(!self.status.focused && curIndex !== newIndex) + { + // Call API method and if return value is false, halt + returned = self.beforeFocus.call(self, event); + if(returned === false) return self; + + // Loop through all other tooltips + $('div.qtip[qtip]').not(self.elements.tooltip).each(function() + { + if($(this).qtip('api').status.rendered === true) + { + elemIndex = parseInt($(this).css('z-index')); + + // Reduce all other tooltip z-index by 1 + if(typeof elemIndex == 'number' && elemIndex > -1) + $(this).css({ zIndex: parseInt( $(this).css('z-index') ) - 1 }); + + // Set focused status to false + $(this).qtip('api').status.focused = false; + } + }) + + // Set the new z-index and set focus status to true + self.elements.tooltip.css({ zIndex: newIndex }); + self.status.focused = true; + + // Call API method and log event + self.onFocus.call(self, event); + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_FOCUSED, 'focus'); + }; + + return self; + }, + + disable: function(state) + { + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'disable'); + + if(state) + { + // Tooltip is not already disabled, proceed + if(!self.status.disabled) + { + // Set the disabled flag and log event + self.status.disabled = true; + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_DISABLED, 'disable'); + } + + // Tooltip is already disabled, inform user via log + else $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.TOOLTIP_ALREADY_DISABLED, 'disable'); + } + else + { + // Tooltip is not already enabled, proceed + if(self.status.disabled) + { + // Reassign events, set disable status and log + self.status.disabled = false; + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_ENABLED, 'disable'); + } + + // Tooltip is already enabled, inform the user via log + else $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.TOOLTIP_ALREADY_ENABLED, 'disable'); + }; + + return self; + }, + + destroy: function() + { + var i, returned, interfaces; + + // Call API method and if return value is false, halt + returned = self.beforeDestroy.call(self); + if(returned === false) return self; + + // Check if tooltip is rendered + if(self.status.rendered) + { + // Remove event handlers and remove element + self.options.show.when.target.unbind('mousemove.qtip', self.updatePosition); + self.options.show.when.target.unbind('mouseout.qtip', self.hide); + self.options.show.when.target.unbind(self.options.show.when.event + '.qtip'); + self.options.hide.when.target.unbind(self.options.hide.when.event + '.qtip'); + self.elements.tooltip.unbind(self.options.hide.when.event + '.qtip'); + self.elements.tooltip.unbind('mouseover.qtip', self.focus); + self.elements.tooltip.remove(); + } + + // Tooltip isn't yet rendered, remove render event + else self.options.show.when.target.unbind(self.options.show.when.event+'.qtip-create'); + + // Check to make sure qTip data is present on target element + if(typeof self.elements.target.data('qtip') == 'object') + { + // Remove API references from interfaces object + interfaces = self.elements.target.data('qtip').interfaces; + if(typeof interfaces == 'object' && interfaces.length > 0) + { + // Remove API from interfaces array + for(i = 0; i < interfaces.length - 1; i++) + if(interfaces[i].id == self.id) interfaces.splice(i, 1) + } + } + delete $.fn.qtip.interfaces[self.id]; + + // Set qTip current id to previous tooltips API if available + if(typeof interfaces == 'object' && interfaces.length > 0) + self.elements.target.data('qtip').current = interfaces.length -1; + else + self.elements.target.removeData('qtip'); + + // Call API method and log destroy + self.onDestroy.call(self); + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_DESTROYED, 'destroy'); + + return self.elements.target + }, + + getPosition: function() + { + var show, offset; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'getPosition'); + + show = (self.elements.tooltip.css('display') !== 'none') ? false : true; + + // Show and hide tooltip to make sure coordinates are returned + if(show) self.elements.tooltip.css({ visiblity: 'hidden' }).show(); + offset = self.elements.tooltip.offset(); + if(show) self.elements.tooltip.css({ visiblity: 'visible' }).hide(); + + return offset; + }, + + getDimensions: function() + { + var show, dimensions; + + // Make sure tooltip is rendered and if not, return + if(!self.status.rendered) + return $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.TOOLTIP_NOT_RENDERED, 'getDimensions'); + + show = (!self.elements.tooltip.is(':visible')) ? true : false; + + // Show and hide tooltip to make sure dimensions are returned + if(show) self.elements.tooltip.css({ visiblity: 'hidden' }).show(); + dimensions = { + height: self.elements.tooltip.outerHeight(), + width: self.elements.tooltip.outerWidth() + }; + if(show) self.elements.tooltip.css({ visiblity: 'visible' }).hide(); + + return dimensions; + } + }); + }; + + // Define priamry construct function + function construct() + { + var self, adjust, content, url, data, method, tempLength; + self = this; + + // Call API method + self.beforeRender.call(self); + + // Set rendered status to true + self.status.rendered = true; + + // Create initial tooltip elements + self.elements.tooltip = '
' + + '
' + + '
' + + '
' + + '
'; + + // Append to container element + self.elements.tooltip = $(self.elements.tooltip); + self.elements.tooltip.appendTo(self.options.position.container) + + // Setup tooltip qTip data + self.elements.tooltip.data('qtip', { current: 0, interfaces: [self] }); + + // Setup element references + self.elements.wrapper = self.elements.tooltip.children('div:first'); + self.elements.contentWrapper = self.elements.wrapper.children('div:first').css({ background: self.options.style.background }); + self.elements.content = self.elements.contentWrapper.children('div:first').css( jQueryStyle(self.options.style) ); + + // Apply IE hasLayout fix to wrapper and content elements + if($.browser.msie) self.elements.wrapper.add(self.elements.content).css({ zoom: 1 }); + + // Setup tooltip attributes + if(self.options.hide.when.event == 'unfocus') self.elements.tooltip.attr('unfocus', true); + + // If an explicit width is set, updateWidth prior to setting content to prevent dirty rendering + if(typeof self.options.style.width.value == 'number') self.updateWidth(); + + // Create borders and tips if supported by the browser + if($('').get(0).getContext || $.browser.msie) + { + // Create border + if(self.options.style.border.radius > 0) + createBorder.call(self); + else + self.elements.contentWrapper.css({ border: self.options.style.border.width+'px solid '+self.options.style.border.color }); + + // Create tip if enabled + if(self.options.style.tip.corner !== false) + createTip.call(self); + } + + // Neither canvas or VML is supported, tips and borders cannot be drawn! + else + { + // Set defined border width + self.elements.contentWrapper.css({ border: self.options.style.border.width+'px solid '+self.options.style.border.color }); + + // Reset border radius and tip + self.options.style.border.radius = 0; + self.options.style.tip.corner = false; + + // Inform via log + $.fn.qtip.log.error.call(self, 2, $.fn.qtip.constants.CANVAS_VML_NOT_SUPPORTED, 'render'); + }; + + // Use the provided content string or DOM array + if((typeof self.options.content.text == 'string' && self.options.content.text.length > 0) + || (self.options.content.text.jquery && self.options.content.text.length > 0)) + content = self.options.content.text; + + // Use title string for content if present + else if(typeof self.elements.target.attr('title') == 'string' && self.elements.target.attr('title').length > 0) + { + content = self.elements.target.attr('title').replace("\\n", '
'); + self.elements.target.attr('title', ''); // Remove title attribute to prevent default tooltip showing + } + + // No title is present, use alt attribute instead + else if(typeof self.elements.target.attr('alt') == 'string' && self.elements.target.attr('alt').length > 0) + { + content = self.elements.target.attr('alt').replace("\\n", '
'); + self.elements.target.attr('alt', ''); // Remove alt attribute to prevent default tooltip showing + } + + // No valid content was provided, inform via log + else + { + content = ' '; + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.NO_VALID_CONTENT, 'render'); + }; + + // Set the tooltips content and create title if enabled + if(self.options.content.title.text !== false) createTitle.call(self); + self.updateContent(content); + + // Assign events and toggle tooltip with focus + assignEvents.call(self); + if(self.options.show.ready === true) self.show(); + + // Retrieve ajax content if provided + if(self.options.content.url !== false) + { + url = self.options.content.url; + data = self.options.content.data; + method = self.options.content.method || 'get'; + self.loadContent(url, data, method); + }; + + // Call API method and log event + self.onRender.call(self); + $.fn.qtip.log.error.call(self, 1, $.fn.qtip.constants.EVENT_RENDERED, 'render'); + }; + + // Create borders using canvas and VML + function createBorder() + { + var self, i, width, radius, color, coordinates, containers, size, betweenWidth, betweenCorners, borderTop, borderBottom, borderCoord, sideWidth, vertWidth; + self = this; + + // Destroy previous border elements, if present + self.elements.wrapper.find('.qtip-borderBottom, .qtip-borderTop').remove(); + + // Setup local variables + width = self.options.style.border.width; + radius = self.options.style.border.radius; + color = self.options.style.border.color || self.options.style.tip.color; + + // Calculate border coordinates + coordinates = calculateBorders(radius); + + // Create containers for the border shapes + containers = {}; + for(i in coordinates) + { + // Create shape container + containers[i] = '
'; + + // Canvas is supported + if($('').get(0).getContext) + containers[i] += ''; + + // No canvas, but if it's IE use VML + else if($.browser.msie) + { + size = radius * 2 + 3; + containers[i] += ''; + + }; + + containers[i] += '
'; + }; + + // Create between corners elements + betweenWidth = self.getDimensions().width - (Math.max(width, radius) * 2); + betweenCorners = '
'; + + // Create top border container + borderTop = '
' + + containers['topLeft'] + containers['topRight'] + betweenCorners; + self.elements.wrapper.prepend(borderTop); + + // Create bottom border container + borderBottom = '
' + + containers['bottomLeft'] + containers['bottomRight'] + betweenCorners; + self.elements.wrapper.append(borderBottom); + + // Draw the borders if canvas were used (Delayed til after DOM creation) + if($('').get(0).getContext) + { + self.elements.wrapper.find('canvas').each(function() + { + borderCoord = coordinates[ $(this).parent('[rel]:first').attr('rel') ]; + drawBorder.call(self, $(this), borderCoord, radius, color); + }) + } + + // Create a phantom VML element (IE won't show the last created VML element otherwise) + else if($.browser.msie) self.elements.tooltip.append(''); + + // Setup contentWrapper border + sideWidth = Math.max(radius, (radius + (width - radius)) ) + vertWidth = Math.max(width - radius, 0); + self.elements.contentWrapper.css({ + border: '0px solid ' + color, + borderWidth: vertWidth + 'px ' + sideWidth + 'px' + }) + }; + + // Border canvas draw method + function drawBorder(canvas, coordinates, radius, color) + { + // Create corner + var context = canvas.get(0).getContext('2d'); + context.fillStyle = color; + context.beginPath(); + context.arc(coordinates[0], coordinates[1], radius, 0, Math.PI * 2, false); + context.fill(); + }; + + // Create tip using canvas and VML + function createTip(corner) + { + var self, color, coordinates, coordsize, path; + self = this; + + // Destroy previous tip, if there is one + if(self.elements.tip !== null) self.elements.tip.remove(); + + // Setup color and corner values + color = self.options.style.tip.color || self.options.style.border.color; + if(self.options.style.tip.corner === false) return; + else if(!corner) corner = self.options.style.tip.corner; + + // Calculate tip coordinates + coordinates = calculateTip(corner, self.options.style.tip.size.width, self.options.style.tip.size.height); + + // Create tip element + self.elements.tip = '
'; + + // Use canvas element if supported + if($('').get(0).getContext) + self.elements.tip += ''; + + // Canvas not supported - Use VML (IE) + else if($.browser.msie) + { + // Create coordize and tip path using tip coordinates + coordsize = self.options.style.tip.size.width + ',' + self.options.style.tip.size.height; + path = 'm' + coordinates[0][0] + ',' + coordinates[0][1]; + path += ' l' + coordinates[1][0] + ',' + coordinates[1][1]; + path += ' ' + coordinates[2][0] + ',' + coordinates[2][1]; + path += ' xe'; + + // Create VML element + self.elements.tip += ''; + + // Create a phantom VML element (IE won't show the last created VML element otherwise) + self.elements.tip += ''; + + // Prevent tooltip appearing above the content (IE z-index bug) + self.elements.contentWrapper.css('position', 'relative'); + }; + + // Attach new tip to tooltip element + self.elements.tooltip.prepend(self.elements.tip + '
'); + + // Create element reference and draw the canvas tip (Delayed til after DOM creation) + self.elements.tip = self.elements.tooltip.find('.'+self.options.style.classes.tip).eq(0); + if($('').get(0).getContext) + drawTip.call(self, self.elements.tip.find('canvas:first'), coordinates, color); + + // Fix IE small tip bug + if(corner.search(/top/) !== -1 && $.browser.msie && parseInt($.browser.version.charAt(0)) === 6) + self.elements.tip.css({ marginTop: -4 }); + + // Set the tip position + positionTip.call(self, corner); + }; + + // Canvas tip drawing method + function drawTip(canvas, coordinates, color) + { + // Setup properties + var context = canvas.get(0).getContext('2d'); + context.fillStyle = color; + + // Create tip + context.beginPath(); + context.moveTo(coordinates[0][0], coordinates[0][1]); + context.lineTo(coordinates[1][0], coordinates[1][1]); + context.lineTo(coordinates[2][0], coordinates[2][1]); + context.fill(); + }; + + function positionTip(corner) + { + var self, ieAdjust, paddingCorner, paddingSize, newMargin; + self = this; + + // Return if tips are disabled or tip is not yet rendered + if(self.options.style.tip.corner === false || !self.elements.tip) return; + if(!corner) corner = self.elements.tip.attr('rel'); + + // Setup adjustment variables + ieAdjust = positionAdjust = ($.browser.msie) ? 1 : 0; + + // Set initial position + self.elements.tip.css(corner.match(/left|right|top|bottom/)[0], 0); + + // Set position of tip to correct side + if(corner.search(/top|bottom/) !== -1) + { + // Adjustments for IE6 - 0.5px border gap bug + if($.browser.msie) + { + if(parseInt($.browser.version.charAt(0)) === 6) + positionAdjust = (corner.search(/top/) !== -1) ? -3 : 1; + else + positionAdjust = (corner.search(/top/) !== -1) ? 1 : 2; + }; + + if(corner.search(/Middle/) !== -1) + self.elements.tip.css({ left: '50%', marginLeft: -(self.options.style.tip.size.width / 2) }); + + else if(corner.search(/Left/) !== -1) + self.elements.tip.css({ left: self.options.style.border.radius - ieAdjust }); + + else if(corner.search(/Right/) !== -1) + self.elements.tip.css({ right: self.options.style.border.radius + ieAdjust }); + + if(corner.search(/top/) !== -1) + self.elements.tip.css({ top: -positionAdjust }); + else + self.elements.tip.css({ bottom: positionAdjust }); + + } + else if(corner.search(/left|right/) !== -1) + { + // Adjustments for IE6 - 0.5px border gap bug + if($.browser.msie) + positionAdjust = (parseInt($.browser.version.charAt(0)) === 6) ? 1 : ((corner.search(/left/) !== -1) ? 1 : 2); + + if(corner.search(/Middle/) !== -1) + self.elements.tip.css({ top: '50%', marginTop: -(self.options.style.tip.size.height / 2) }); + + else if(corner.search(/Top/) !== -1) + self.elements.tip.css({ top: self.options.style.border.radius - ieAdjust }); + + else if(corner.search(/Bottom/) !== -1) + self.elements.tip.css({ bottom: self.options.style.border.radius + ieAdjust }); + + if(corner.search(/left/) !== -1) + self.elements.tip.css({ left: -positionAdjust }); + else + self.elements.tip.css({ right: positionAdjust }); + }; + + // Adjust tooltip padding to compensate for tip + paddingCorner = 'padding-' + corner.match(/left|right|top|bottom/)[0]; + paddingSize = self.options.style.tip.size[ (paddingCorner.search(/left|right/) !== -1) ? 'width' : 'height' ]; + self.elements.tooltip.css('padding', 0); + self.elements.tooltip.css(paddingCorner, paddingSize); + + // Match content margin to prevent gap bug in IE6 ONLY + if($.browser.msie && parseInt($.browser.version.charAt(0)) == 6) + { + newMargin = parseInt(self.elements.tip.css('margin-top')) || 0; + newMargin += parseInt(self.elements.content.css('margin-top')) || 0; + + self.elements.tip.css({ marginTop: newMargin }); + }; + }; + + // Create title bar for content + function createTitle() + { + var self = this; + + // Destroy previous title element, if present + if(self.elements.title !== null) self.elements.title.remove(); + + // Create title element + self.elements.title = $('
') + .css( jQueryStyle(self.options.style.title, true) ) + .css({ zoom: ($.browser.msie) ? 1 : 0 }) + .prependTo(self.elements.contentWrapper); + + // Update title with contents if enabled + if(self.options.content.title.text) self.updateTitle.call(self, self.options.content.title.text); + + // Create title close buttons if enabled + if(self.options.content.title.button !== false + && typeof self.options.content.title.button == 'string') + { + self.elements.button = $('') + .css( jQueryStyle(self.options.style.button, true) ) + .html(self.options.content.title.button) + .prependTo(self.elements.title) + .click(function(event){ if(!self.status.disabled) self.hide(event) }); + }; + }; + + // Assign hide and show events + function assignEvents() + { + var self, showTarget, hideTarget, inactiveEvents; + self = this; + + // Setup event target variables + showTarget = self.options.show.when.target; + hideTarget = self.options.hide.when.target; + + // Add tooltip as a hideTarget is its fixed + if(self.options.hide.fixed) hideTarget = hideTarget.add(self.elements.tooltip); + + // Check if the hide event is special 'inactive' type + if(self.options.hide.when.event == 'inactive') + { + // Define events which reset the 'inactive' event handler + inactiveEvents = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', + 'mouseout', 'mouseenter', 'mouseleave', 'mouseover' ]; + + // Define 'inactive' event timer method + function inactiveMethod(event) + { + if(self.status.disabled === true) return; + + //Clear and reset the timer + clearTimeout(self.timers.inactive); + self.timers.inactive = setTimeout(function() + { + // Unassign 'inactive' events + $(inactiveEvents).each(function() + { + hideTarget.unbind(this+'.qtip-inactive'); + self.elements.content.unbind(this+'.qtip-inactive'); + }); + + // Hide the tooltip + self.hide(event); + } + , self.options.hide.delay); + }; + } + + // Check if the tooltip is 'fixed' + else if(self.options.hide.fixed === true) + { + self.elements.tooltip.bind('mouseover.qtip', function() + { + if(self.status.disabled === true) return; + + // Reset the hide timer + clearTimeout(self.timers.hide); + }); + }; + + // Define show event method + function showMethod(event) + { + if(self.status.disabled === true) return; + + // If set, hide tooltip when inactive for delay period + if(self.options.hide.when.event == 'inactive') + { + // Assign each reset event + $(inactiveEvents).each(function() + { + hideTarget.bind(this+'.qtip-inactive', inactiveMethod); + self.elements.content.bind(this+'.qtip-inactive', inactiveMethod); + }); + + // Start the inactive timer + inactiveMethod(); + }; + + // Clear hide timers + clearTimeout(self.timers.show); + clearTimeout(self.timers.hide); + + // Start show timer + self.timers.show = setTimeout(function(){ self.show(event); }, self.options.show.delay); + }; + + // Define hide event method + function hideMethod(event) + { + if(self.status.disabled === true) return; + + // Prevent hiding if tooltip is fixed and event target is the tooltip + if(self.options.hide.fixed === true + && self.options.hide.when.event.search(/mouse(out|leave)/i) !== -1 + && $(event.relatedTarget).parents('div.qtip[qtip]').length > 0) + { + // Prevent default and popagation + event.stopPropagation(); + event.preventDefault(); + + // Reset the hide timer + clearTimeout(self.timers.hide); + return false; + }; + + // Clear timers and stop animation queue + clearTimeout(self.timers.show); + clearTimeout(self.timers.hide); + self.elements.tooltip.stop(true, true); + + // If tooltip has displayed, start hide timer + self.timers.hide = setTimeout(function(){ self.hide(event); }, self.options.hide.delay); + }; + + // Both events and targets are identical, apply events using a toggle + if((self.options.show.when.target.add(self.options.hide.when.target).length === 1 + && self.options.show.when.event == self.options.hide.when.event + && self.options.hide.when.event !== 'inactive') + || self.options.hide.when.event == 'unfocus') + { + self.cache.toggle = 0; + // Use a toggle to prevent hide/show conflicts + showTarget.bind(self.options.show.when.event + '.qtip', function(event) + { + if(self.cache.toggle == 0) showMethod(event); + else hideMethod(event); + }); + } + + // Events are not identical, bind normally + else + { + showTarget.bind(self.options.show.when.event + '.qtip', showMethod); + + // If the hide event is not 'inactive', bind the hide method + if(self.options.hide.when.event !== 'inactive') + hideTarget.bind(self.options.hide.when.event + '.qtip', hideMethod); + }; + + // Focus the tooltip on mouseover + if(self.options.position.type.search(/(fixed|absolute)/) !== -1) + self.elements.tooltip.bind('mouseover.qtip', self.focus); + + // If mouse is the target, update tooltip position on mousemove + if(self.options.position.target === 'mouse' && self.options.position.type !== 'static') + { + showTarget.bind('mousemove.qtip', function(event) + { + // Set the new mouse positions if adjustment is enabled + self.cache.mouse = { x: event.pageX, y: event.pageY }; + + // Update the tooltip position only if the tooltip is visible and adjustment is enabled + if(self.status.disabled === false + && self.options.position.adjust.mouse === true + && self.options.position.type !== 'static' + && self.elements.tooltip.css('display') !== 'none') + self.updatePosition(event); + }); + }; + }; + + // Screen position adjustment + function screenAdjust(position, target, tooltip) + { + var self, adjustedPosition, adjust, newCorner, overflow, corner; + self = this; + + // Setup corner and adjustment variable + if(tooltip.corner == 'center') return target.position // TODO: 'center' corner adjustment + adjustedPosition = $.extend({}, position); + newCorner = { x: false, y: false }; + + // Define overflow properties + overflow = { + left: (adjustedPosition.left < $.fn.qtip.cache.screen.scroll.left), + right: (adjustedPosition.left + tooltip.dimensions.width + 2 >= $.fn.qtip.cache.screen.width + $.fn.qtip.cache.screen.scroll.left), + top: (adjustedPosition.top < $.fn.qtip.cache.screen.scroll.top), + bottom: (adjustedPosition.top + tooltip.dimensions.height + 2 >= $.fn.qtip.cache.screen.height + $.fn.qtip.cache.screen.scroll.top) + }; + + // Determine new positioning properties + adjust = { + left: (overflow.left && (tooltip.corner.search(/right/i) != -1 || (tooltip.corner.search(/right/i) == -1 && !overflow.right))), + right: (overflow.right && (tooltip.corner.search(/left/i) != -1 || (tooltip.corner.search(/left/i) == -1 && !overflow.left))), + top: (overflow.top && tooltip.corner.search(/top/i) == -1), + bottom: (overflow.bottom && tooltip.corner.search(/bottom/i) == -1) + }; + + // Tooltip overflows off the left side of the screen + if(adjust.left) + { + if(self.options.position.target !== 'mouse') + adjustedPosition.left = target.position.left + target.dimensions.width; + else + adjustedPosition.left = self.cache.mouse.x + + newCorner.x = 'Left'; + } + + // Tooltip overflows off the right side of the screen + else if(adjust.right) + { + if(self.options.position.target !== 'mouse') + adjustedPosition.left = target.position.left - tooltip.dimensions.width; + else + adjustedPosition.left = self.cache.mouse.x - tooltip.dimensions.width; + + newCorner.x = 'Right'; + }; + + // Tooltip overflows off the top of the screen + if(adjust.top) + { + if(self.options.position.target !== 'mouse') + adjustedPosition.top = target.position.top + target.dimensions.height; + else + adjustedPosition.top = self.cache.mouse.y + + newCorner.y = 'top'; + } + + // Tooltip overflows off the bottom of the screen + else if(adjust.bottom) + { + if(self.options.position.target !== 'mouse') + adjustedPosition.top = target.position.top - tooltip.dimensions.height; + else + adjustedPosition.top = self.cache.mouse.y - tooltip.dimensions.height; + + newCorner.y = 'bottom'; + }; + + // Don't adjust if resulting position is negative + if(adjustedPosition.left < 0) + { + adjustedPosition.left = position.left; + newCorner.x = false; + }; + if(adjustedPosition.top < 0) + { + adjustedPosition.top = position.top; + newCorner.y = false; + }; + + // Change tip corner if positioning has changed and tips are enabled + if(self.options.style.tip.corner !== false) + { + // Determine new corner properties + adjustedPosition.corner = new String(tooltip.corner); + if(newCorner.x !== false) adjustedPosition.corner = adjustedPosition.corner.replace(/Left|Right|Middle/, newCorner.x); + if(newCorner.y !== false) adjustedPosition.corner = adjustedPosition.corner.replace(/top|bottom/, newCorner.y); + + // Adjust tip if position has changed and tips are enabled + if(adjustedPosition.corner !== self.elements.tip.attr('rel')) + createTip.call(self, adjustedPosition.corner); + }; + + return adjustedPosition; + }; + + // Build a jQuery style object from supplied style object + function jQueryStyle(style, sub) + { + var styleObj, i; + + styleObj = $.extend(true, {}, style); + for(i in styleObj) + { + if(sub === true && i.search(/(tip|classes)/i) !== -1) + delete styleObj[i]; + else if(!sub && i.search(/(width|border|tip|title|classes|user)/i) !== -1) + delete styleObj[i]; + }; + + return styleObj; + }; + + // Sanitize styles + function sanitizeStyle(style) + { + if(typeof style.tip !== 'object') style.tip = { corner: style.tip }; + if(typeof style.tip.size !== 'object') style.tip.size = { width: style.tip.size, height: style.tip.size }; + if(typeof style.border !== 'object') style.border = { width: style.border }; + if(typeof style.width !== 'object') style.width = { value: style.width }; + if(typeof style.width.max == 'string') style.width.max = parseInt(style.width.max.replace(/([0-9]+)/i, "$1")); + if(typeof style.width.min == 'string') style.width.min = parseInt(style.width.min.replace(/([0-9]+)/i, "$1")); + + // Convert deprecated x and y tip values to width/height + if(typeof style.tip.size.x == 'number') + { + style.tip.size.width = style.tip.size.x; + delete style.tip.size.x; + }; + if(typeof style.tip.size.y == 'number') + { + style.tip.size.height = style.tip.size.y; + delete style.tip.size.y; + }; + + return style; + }; + + // Build styles recursively with inheritance + function buildStyle() + { + var self, i, styleArray, styleExtend, finalStyle, ieAdjust; + self = this; + + // Build style options from supplied arguments + styleArray = [true, {}]; + for(i = 0; i < arguments.length; i++) + styleArray.push(arguments[i]); + styleExtend = [ $.extend.apply($, styleArray) ]; + + // Loop through each named style inheritance + while(typeof styleExtend[0].name == 'string') + { + // Sanitize style data and append to extend array + styleExtend.unshift( sanitizeStyle($.fn.qtip.styles[ styleExtend[0].name ]) ); + }; + + // Make sure resulting tooltip className represents final style + styleExtend.unshift(true, {classes:{ tooltip: 'qtip-' + (arguments[0].name || 'defaults') }}, $.fn.qtip.styles.defaults); + + // Extend into a single style object + finalStyle = $.extend.apply($, styleExtend); + + // Adjust tip size if needed (IE 1px adjustment bug fix) + ieAdjust = ($.browser.msie) ? 1 : 0; + finalStyle.tip.size.width += ieAdjust; + finalStyle.tip.size.height += ieAdjust; + + // Force even numbers for pixel precision + if(finalStyle.tip.size.width % 2 > 0) finalStyle.tip.size.width += 1; + if(finalStyle.tip.size.height % 2 > 0) finalStyle.tip.size.height += 1; + + // Sanitize final styles tip corner value + if(finalStyle.tip.corner === true) + finalStyle.tip.corner = (self.options.position.corner.tooltip === 'center') ? false : self.options.position.corner.tooltip; + + return finalStyle; + }; + + // Tip coordinates calculator + function calculateTip(corner, width, height) + { + // Define tip coordinates in terms of height and width values + var tips = { + bottomRight: [[0,0], [width,height], [width,0]], + bottomLeft: [[0,0], [width,0], [0,height]], + topRight: [[0,height], [width,0], [width,height]], + topLeft: [[0,0], [0,height], [width,height]], + topMiddle: [[0,height], [width / 2,0], [width,height]], + bottomMiddle: [[0,0], [width,0], [width / 2,height]], + rightMiddle: [[0,0], [width,height / 2], [0,height]], + leftMiddle: [[width,0], [width,height], [0,height / 2]] + }; + tips.leftTop = tips.bottomRight; + tips.rightTop = tips.bottomLeft; + tips.leftBottom = tips.topRight; + tips.rightBottom = tips.topLeft; + + return tips[corner]; + }; + + // Border coordinates calculator + function calculateBorders(radius) + { + var borders; + + // Use canvas element if supported + if($('').get(0).getContext) + { + borders = { + topLeft: [radius,radius], topRight: [0,radius], + bottomLeft: [radius,0], bottomRight: [0,0] + }; + } + + // Canvas not supported - Use VML (IE) + else if($.browser.msie) + { + borders = { + topLeft: [-90,90,0], topRight: [-90,90,-radius], + bottomLeft: [90,270,0], bottomRight: [90, 270,-radius] + }; + }; + + return borders; + }; + + // BGIFRAME JQUERY PLUGIN ADAPTION + // Special thanks to Brandon Aaron for this plugin + // http://plugins.jquery.com/project/bgiframe + function bgiframe() + { + var self, html, dimensions; + self = this; + dimensions = self.getDimensions(); + + // Setup iframe HTML string + html = '
' + PMA_messages['strSumRows'] + ' '+ rowSum +'' + - PMA_messages['strTotal'] + ':' + totalSum + '' + totalSum + '' + totalSum + '