console.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * Used in or for console
  4. *
  5. * @package phpMyAdmin-Console
  6. */
  7. /**
  8. * Console object
  9. */
  10. var PMA_console = {
  11. /**
  12. * @var object, jQuery object, selector is '#pma_console>.content'
  13. * @access private
  14. */
  15. $consoleContent: null,
  16. /**
  17. * @var object, jQuery object, selector is '#pma_console .content',
  18. * used for resizer
  19. * @access private
  20. */
  21. $consoleAllContents: null,
  22. /**
  23. * @var object, jQuery object, selector is '#pma_console .toolbar'
  24. * @access private
  25. */
  26. $consoleToolbar: null,
  27. /**
  28. * @var object, jQuery object, selector is '#pma_console .template'
  29. * @access private
  30. */
  31. $consoleTemplates: null,
  32. /**
  33. * @var object, jQuery object, form for submit
  34. * @access private
  35. */
  36. $requestForm: null,
  37. /**
  38. * @var object, contain console config
  39. * @access private
  40. */
  41. config: null,
  42. /**
  43. * @var bool, if console element exist, it'll be true
  44. * @access public
  45. */
  46. isEnabled: false,
  47. /**
  48. * @var bool, make sure console events bind only once
  49. * @access private
  50. */
  51. isInitialized: false,
  52. /**
  53. * Used for console initialize, reinit is ok, just some variable assignment
  54. *
  55. * @return void
  56. */
  57. initialize: function () {
  58. if ($('#pma_console').length === 0) {
  59. return;
  60. }
  61. PMA_console.config = configGet('Console', false);
  62. PMA_console.isEnabled = true;
  63. // Vars init
  64. PMA_console.$consoleToolbar = $('#pma_console').find('>.toolbar');
  65. PMA_console.$consoleContent = $('#pma_console').find('>.content');
  66. PMA_console.$consoleAllContents = $('#pma_console').find('.content');
  67. PMA_console.$consoleTemplates = $('#pma_console').find('>.templates');
  68. // Generate a from for post
  69. PMA_console.$requestForm = $('<form method="post" action="import.php">' +
  70. '<input name="is_js_confirmed" value="0">' +
  71. '<textarea name="sql_query"></textarea>' +
  72. '<input name="console_message_id" value="0">' +
  73. '<input name="server" value="">' +
  74. '<input name="db" value="">' +
  75. '<input name="table" value="">' +
  76. '<input name="token" value="">' +
  77. '</form>'
  78. );
  79. PMA_console.$requestForm.children('[name=token]').val(PMA_commonParams.get('token'));
  80. PMA_console.$requestForm.on('submit', AJAX.requestHandler);
  81. // Event binds shouldn't run again
  82. if (PMA_console.isInitialized === false) {
  83. // Load config first
  84. if (PMA_console.config.AlwaysExpand === true) {
  85. $('#pma_console_options input[name=always_expand]').prop('checked', true);
  86. }
  87. if (PMA_console.config.StartHistory === true) {
  88. $('#pma_console_options').find('input[name=start_history]').prop('checked', true);
  89. }
  90. if (PMA_console.config.CurrentQuery === true) {
  91. $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
  92. }
  93. if (PMA_console.config.EnterExecutes === true) {
  94. $('#pma_console_options').find('input[name=enter_executes]').prop('checked', true);
  95. }
  96. if (PMA_console.config.DarkTheme === true) {
  97. $('#pma_console_options').find('input[name=dark_theme]').prop('checked', true);
  98. $('#pma_console').find('>.content').addClass('console_dark_theme');
  99. }
  100. PMA_consoleResizer.initialize();
  101. PMA_consoleInput.initialize();
  102. PMA_consoleMessages.initialize();
  103. PMA_consoleBookmarks.initialize();
  104. PMA_consoleDebug.initialize();
  105. PMA_console.$consoleToolbar.children('.console_switch').click(PMA_console.toggle);
  106. $('#pma_console').find('.toolbar').children().mousedown(function (event) {
  107. event.preventDefault();
  108. event.stopImmediatePropagation();
  109. });
  110. $('#pma_console').find('.button.clear').click(function () {
  111. PMA_consoleMessages.clear();
  112. });
  113. $('#pma_console').find('.button.history').click(function () {
  114. PMA_consoleMessages.showHistory();
  115. });
  116. $('#pma_console').find('.button.options').click(function () {
  117. PMA_console.showCard('#pma_console_options');
  118. });
  119. $('#pma_console').find('.button.debug').click(function () {
  120. PMA_console.showCard('#debug_console');
  121. });
  122. PMA_console.$consoleContent.click(function (event) {
  123. if (event.target === this) {
  124. PMA_consoleInput.focus();
  125. }
  126. });
  127. $('#pma_console').find('.mid_layer').click(function () {
  128. PMA_console.hideCard($(this).parent().children('.card'));
  129. });
  130. $('#debug_console').find('.switch_button').click(function () {
  131. PMA_console.hideCard($(this).closest('.card'));
  132. });
  133. $('#pma_bookmarks').find('.switch_button').click(function () {
  134. PMA_console.hideCard($(this).closest('.card'));
  135. });
  136. $('#pma_console_options').find('.switch_button').click(function () {
  137. PMA_console.hideCard($(this).closest('.card'));
  138. });
  139. $('#pma_console_options').find('input[type=checkbox]').change(function () {
  140. PMA_console.updateConfig();
  141. });
  142. $('#pma_console_options').find('.button.default').click(function () {
  143. $('#pma_console_options input[name=always_expand]').prop('checked', false);
  144. $('#pma_console_options').find('input[name=start_history]').prop('checked', false);
  145. $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
  146. $('#pma_console_options').find('input[name=enter_executes]').prop('checked', false);
  147. $('#pma_console_options').find('input[name=dark_theme]').prop('checked', false);
  148. PMA_console.updateConfig();
  149. });
  150. $('#pma_console_options').find('input[name=enter_executes]').change(function () {
  151. PMA_consoleMessages.showInstructions(PMA_console.config.EnterExecutes);
  152. });
  153. $(document).ajaxComplete(function (event, xhr, ajaxOptions) {
  154. if (ajaxOptions.dataType && ajaxOptions.dataType.indexOf('json') !== -1) {
  155. return;
  156. }
  157. if (xhr.status !== 200) {
  158. return;
  159. }
  160. try {
  161. var data = JSON.parse(xhr.responseText);
  162. PMA_console.ajaxCallback(data);
  163. } catch (e) {
  164. console.trace();
  165. console.log('Failed to parse JSON: ' + e.message);
  166. }
  167. });
  168. PMA_console.isInitialized = true;
  169. }
  170. // Change console mode from cookie
  171. switch (PMA_console.config.Mode) {
  172. case 'collapse':
  173. PMA_console.collapse();
  174. break;
  175. /* jshint -W086 */// no break needed in default section
  176. default:
  177. PMA_console.setConfig('Mode', 'info');
  178. case 'info':
  179. /* jshint +W086 */
  180. PMA_console.info();
  181. break;
  182. case 'show':
  183. PMA_console.show(true);
  184. PMA_console.scrollBottom();
  185. break;
  186. }
  187. },
  188. /**
  189. * Execute query and show results in console
  190. *
  191. * @return void
  192. */
  193. execute: function (queryString, options) {
  194. if (typeof(queryString) !== 'string' || ! /[a-z]|[A-Z]/.test(queryString)) {
  195. return;
  196. }
  197. PMA_console.$requestForm.children('textarea').val(queryString);
  198. PMA_console.$requestForm.children('[name=server]').attr('value', PMA_commonParams.get('server'));
  199. if (options && options.db) {
  200. PMA_console.$requestForm.children('[name=db]').val(options.db);
  201. if (options.table) {
  202. PMA_console.$requestForm.children('[name=table]').val(options.table);
  203. } else {
  204. PMA_console.$requestForm.children('[name=table]').val('');
  205. }
  206. } else {
  207. PMA_console.$requestForm.children('[name=db]').val(
  208. (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : ''));
  209. }
  210. PMA_console.$requestForm.find('[name=profiling]').remove();
  211. if (options && options.profiling === true) {
  212. PMA_console.$requestForm.append('<input name="profiling" value="on">');
  213. }
  214. if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0].value)) {
  215. return;
  216. }
  217. PMA_console.$requestForm.children('[name=console_message_id]')
  218. .val(PMA_consoleMessages.appendQuery({ sql_query: queryString }).message_id);
  219. PMA_console.$requestForm.trigger('submit');
  220. PMA_consoleInput.clear();
  221. PMA_reloadNavigation();
  222. },
  223. ajaxCallback: function (data) {
  224. if (data && data.console_message_id) {
  225. PMA_consoleMessages.updateQuery(data.console_message_id, data.success,
  226. (data._reloadQuerywindow ? data._reloadQuerywindow : false));
  227. } else if (data && data._reloadQuerywindow) {
  228. if (data._reloadQuerywindow.sql_query.length > 0) {
  229. PMA_consoleMessages.appendQuery(data._reloadQuerywindow, 'successed')
  230. .$message.addClass(PMA_console.config.CurrentQuery ? '' : 'hide');
  231. }
  232. }
  233. },
  234. /**
  235. * Change console to collapse mode
  236. *
  237. * @return void
  238. */
  239. collapse: function () {
  240. PMA_console.setConfig('Mode', 'collapse');
  241. var pmaConsoleHeight = Math.max(92, PMA_console.config.Height);
  242. PMA_console.$consoleToolbar.addClass('collapsed');
  243. PMA_console.$consoleAllContents.height(pmaConsoleHeight);
  244. PMA_console.$consoleContent.stop();
  245. PMA_console.$consoleContent.animate({ 'margin-bottom': -1 * PMA_console.$consoleContent.outerHeight() + 'px' },
  246. 'fast', 'easeOutQuart', function () {
  247. PMA_console.$consoleContent.css({ display:'none' });
  248. $(window).trigger('resize');
  249. });
  250. PMA_console.hideCard();
  251. },
  252. /**
  253. * Show console
  254. *
  255. * @param bool inputFocus If true, focus the input line after show()
  256. * @return void
  257. */
  258. show: function (inputFocus) {
  259. PMA_console.setConfig('Mode', 'show');
  260. var pmaConsoleHeight = Math.max(92, PMA_console.config.Height);
  261. pmaConsoleHeight = Math.min(PMA_console.config.Height, (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 25);
  262. PMA_console.$consoleContent.css({ display:'block' });
  263. if (PMA_console.$consoleToolbar.hasClass('collapsed')) {
  264. PMA_console.$consoleToolbar.removeClass('collapsed');
  265. }
  266. PMA_console.$consoleAllContents.height(pmaConsoleHeight);
  267. PMA_console.$consoleContent.stop();
  268. PMA_console.$consoleContent.animate({ 'margin-bottom': 0 },
  269. 'fast', 'easeOutQuart', function () {
  270. $(window).trigger('resize');
  271. if (inputFocus) {
  272. PMA_consoleInput.focus();
  273. }
  274. });
  275. },
  276. /**
  277. * Change console to SQL information mode
  278. * this mode shows current SQL query
  279. * This mode is the default mode
  280. *
  281. * @return void
  282. */
  283. info: function () {
  284. // Under construction
  285. PMA_console.collapse();
  286. },
  287. /**
  288. * Toggle console mode between collapse/show
  289. * Used for toggle buttons and shortcuts
  290. *
  291. * @return void
  292. */
  293. toggle: function () {
  294. switch (PMA_console.config.Mode) {
  295. case 'collapse':
  296. case 'info':
  297. PMA_console.show(true);
  298. break;
  299. case 'show':
  300. PMA_console.collapse();
  301. break;
  302. default:
  303. PMA_consoleInitialize();
  304. }
  305. },
  306. /**
  307. * Scroll console to bottom
  308. *
  309. * @return void
  310. */
  311. scrollBottom: function () {
  312. PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop('scrollHeight'));
  313. },
  314. /**
  315. * Show card
  316. *
  317. * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector
  318. * this param also can be JQuery object, if you need.
  319. *
  320. * @return void
  321. */
  322. showCard: function (cardSelector) {
  323. var $card = null;
  324. if (typeof(cardSelector) !== 'string') {
  325. if (cardSelector.length > 0) {
  326. $card = cardSelector;
  327. } else {
  328. return;
  329. }
  330. } else {
  331. $card = $('#pma_console ' + cardSelector);
  332. }
  333. if ($card.length === 0) {
  334. return;
  335. }
  336. $card.parent().children('.mid_layer').show().fadeTo(0, 0.15);
  337. $card.addClass('show');
  338. PMA_consoleInput.blur();
  339. if ($card.parents('.card').length > 0) {
  340. PMA_console.showCard($card.parents('.card'));
  341. }
  342. },
  343. /**
  344. * Scroll console to bottom
  345. *
  346. * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards
  347. * @return void
  348. */
  349. hideCard: function ($targetCard) {
  350. if (! $targetCard) {
  351. $('#pma_console').find('.mid_layer').fadeOut(140);
  352. $('#pma_console').find('.card').removeClass('show');
  353. } else if ($targetCard.length > 0) {
  354. $targetCard.parent().find('.mid_layer').fadeOut(140);
  355. $targetCard.find('.card').removeClass('show');
  356. $targetCard.removeClass('show');
  357. }
  358. },
  359. /**
  360. * Used for update console config
  361. *
  362. * @return void
  363. */
  364. updateConfig: function () {
  365. PMA_console.setConfig('AlwaysExpand', $('#pma_console_options input[name=always_expand]').prop('checked'));
  366. PMA_console.setConfig('StartHistory', $('#pma_console_options').find('input[name=start_history]').prop('checked'));
  367. PMA_console.setConfig('CurrentQuery', $('#pma_console_options').find('input[name=current_query]').prop('checked'));
  368. PMA_console.setConfig('EnterExecutes', $('#pma_console_options').find('input[name=enter_executes]').prop('checked'));
  369. PMA_console.setConfig('DarkTheme', $('#pma_console_options').find('input[name=dark_theme]').prop('checked'));
  370. /* Setting the dark theme of the console*/
  371. if (PMA_console.config.DarkTheme) {
  372. $('#pma_console').find('>.content').addClass('console_dark_theme');
  373. } else {
  374. $('#pma_console').find('>.content').removeClass('console_dark_theme');
  375. }
  376. },
  377. setConfig: function (key, value) {
  378. PMA_console.config[key] = value;
  379. configSet('Console/' + key, value);
  380. },
  381. isSelect: function (queryString) {
  382. var reg_exp = /^SELECT\s+/i;
  383. return reg_exp.test(queryString);
  384. }
  385. };
  386. /**
  387. * Resizer object
  388. * Careful: this object UI logics highly related with functions under PMA_console
  389. * Resizing min-height is 32, if small than it, console will collapse
  390. */
  391. var PMA_consoleResizer = {
  392. _posY: 0,
  393. _height: 0,
  394. _resultHeight: 0,
  395. /**
  396. * Mousedown event handler for bind to resizer
  397. *
  398. * @return void
  399. */
  400. _mousedown: function (event) {
  401. if (PMA_console.config.Mode !== 'show') {
  402. return;
  403. }
  404. PMA_consoleResizer._posY = event.pageY;
  405. PMA_consoleResizer._height = PMA_console.$consoleContent.height();
  406. $(document).mousemove(PMA_consoleResizer._mousemove);
  407. $(document).mouseup(PMA_consoleResizer._mouseup);
  408. // Disable text selection while resizing
  409. $(document).on('selectstart', function () {
  410. return false;
  411. });
  412. },
  413. /**
  414. * Mousemove event handler for bind to resizer
  415. *
  416. * @return void
  417. */
  418. _mousemove: function (event) {
  419. if (event.pageY < 35) {
  420. event.pageY = 35;
  421. }
  422. PMA_consoleResizer._resultHeight = PMA_consoleResizer._height + (PMA_consoleResizer._posY - event.pageY);
  423. // Content min-height is 32, if adjusting height small than it we'll move it out of the page
  424. if (PMA_consoleResizer._resultHeight <= 32) {
  425. PMA_console.$consoleAllContents.height(32);
  426. PMA_console.$consoleContent.css('margin-bottom', PMA_consoleResizer._resultHeight - 32);
  427. } else {
  428. // Logic below makes viewable area always at bottom when adjusting height and content already at bottom
  429. if (PMA_console.$consoleContent.scrollTop() + PMA_console.$consoleContent.innerHeight() + 16
  430. >= PMA_console.$consoleContent.prop('scrollHeight')) {
  431. PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
  432. PMA_console.scrollBottom();
  433. } else {
  434. PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
  435. }
  436. }
  437. },
  438. /**
  439. * Mouseup event handler for bind to resizer
  440. *
  441. * @return void
  442. */
  443. _mouseup: function () {
  444. PMA_console.setConfig('Height', PMA_consoleResizer._resultHeight);
  445. PMA_console.show();
  446. $(document).off('mousemove');
  447. $(document).off('mouseup');
  448. $(document).off('selectstart');
  449. },
  450. /**
  451. * Used for console resizer initialize
  452. *
  453. * @return void
  454. */
  455. initialize: function () {
  456. $('#pma_console').find('.toolbar').off('mousedown');
  457. $('#pma_console').find('.toolbar').mousedown(PMA_consoleResizer._mousedown);
  458. }
  459. };
  460. /**
  461. * Console input object
  462. */
  463. var PMA_consoleInput = {
  464. /**
  465. * @var array, contains Codemirror objects or input jQuery objects
  466. * @access private
  467. */
  468. _inputs: null,
  469. /**
  470. * @var bool, if codemirror enabled
  471. * @access private
  472. */
  473. _codemirror: false,
  474. /**
  475. * @var int, count for history navigation, 0 for current input
  476. * @access private
  477. */
  478. _historyCount: 0,
  479. /**
  480. * @var string, current input when navigating through history
  481. * @access private
  482. */
  483. _historyPreserveCurrent: null,
  484. /**
  485. * Used for console input initialize
  486. *
  487. * @return void
  488. */
  489. initialize: function () {
  490. // _cm object can't be reinitialize
  491. if (PMA_consoleInput._inputs !== null) {
  492. return;
  493. }
  494. if (typeof CodeMirror !== 'undefined') {
  495. PMA_consoleInput._codemirror = true;
  496. }
  497. PMA_consoleInput._inputs = [];
  498. if (PMA_consoleInput._codemirror) {
  499. PMA_consoleInput._inputs.console = CodeMirror($('#pma_console').find('.console_query_input')[0], {
  500. theme: 'pma',
  501. mode: 'text/x-sql',
  502. lineWrapping: true,
  503. extraKeys: { 'Ctrl-Space': 'autocomplete' },
  504. hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true },
  505. gutters: ['CodeMirror-lint-markers'],
  506. lint: {
  507. 'getAnnotations': CodeMirror.sqlLint,
  508. 'async': true,
  509. }
  510. });
  511. PMA_consoleInput._inputs.console.on('inputRead', codemirrorAutocompleteOnInputRead);
  512. PMA_consoleInput._inputs.console.on('keydown', function (instance, event) {
  513. PMA_consoleInput._historyNavigate(event);
  514. });
  515. if ($('#pma_bookmarks').length !== 0) {
  516. PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console').find('.bookmark_add_input')[0], {
  517. theme: 'pma',
  518. mode: 'text/x-sql',
  519. lineWrapping: true,
  520. extraKeys: { 'Ctrl-Space': 'autocomplete' },
  521. hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true },
  522. gutters: ['CodeMirror-lint-markers'],
  523. lint: {
  524. 'getAnnotations': CodeMirror.sqlLint,
  525. 'async': true,
  526. }
  527. });
  528. PMA_consoleInput._inputs.bookmark.on('inputRead', codemirrorAutocompleteOnInputRead);
  529. }
  530. } else {
  531. PMA_consoleInput._inputs.console =
  532. $('<textarea>').appendTo('#pma_console .console_query_input')
  533. .on('keydown', PMA_consoleInput._historyNavigate);
  534. if ($('#pma_bookmarks').length !== 0) {
  535. PMA_consoleInput._inputs.bookmark =
  536. $('<textarea>').appendTo('#pma_console .bookmark_add_input');
  537. }
  538. }
  539. $('#pma_console').find('.console_query_input').keydown(PMA_consoleInput._keydown);
  540. },
  541. _historyNavigate: function (event) {
  542. if (event.keyCode === 38 || event.keyCode === 40) {
  543. var upPermitted = false;
  544. var downPermitted = false;
  545. var editor = PMA_consoleInput._inputs.console;
  546. var cursorLine;
  547. var totalLine;
  548. if (PMA_consoleInput._codemirror) {
  549. cursorLine = editor.getCursor().line;
  550. totalLine = editor.lineCount();
  551. } else {
  552. // Get cursor position from textarea
  553. var text = PMA_consoleInput.getText();
  554. cursorLine = text.substr(0, editor.prop('selectionStart')).split('\n').length - 1;
  555. totalLine = text.split(/\r*\n/).length;
  556. }
  557. if (cursorLine === 0) {
  558. upPermitted = true;
  559. }
  560. if (cursorLine === totalLine - 1) {
  561. downPermitted = true;
  562. }
  563. var nextCount;
  564. var queryString = false;
  565. if (upPermitted && event.keyCode === 38) {
  566. // Navigate up in history
  567. if (PMA_consoleInput._historyCount === 0) {
  568. PMA_consoleInput._historyPreserveCurrent = PMA_consoleInput.getText();
  569. }
  570. nextCount = PMA_consoleInput._historyCount + 1;
  571. queryString = PMA_consoleMessages.getHistory(nextCount);
  572. } else if (downPermitted && event.keyCode === 40) {
  573. // Navigate down in history
  574. if (PMA_consoleInput._historyCount === 0) {
  575. return;
  576. }
  577. nextCount = PMA_consoleInput._historyCount - 1;
  578. if (nextCount === 0) {
  579. queryString = PMA_consoleInput._historyPreserveCurrent;
  580. } else {
  581. queryString = PMA_consoleMessages.getHistory(nextCount);
  582. }
  583. }
  584. if (queryString !== false) {
  585. PMA_consoleInput._historyCount = nextCount;
  586. PMA_consoleInput.setText(queryString, 'console');
  587. if (PMA_consoleInput._codemirror) {
  588. editor.setCursor(editor.lineCount(), 0);
  589. }
  590. event.preventDefault();
  591. }
  592. }
  593. },
  594. /**
  595. * Mousedown event handler for bind to input
  596. * Shortcut is Ctrl+Enter key or just ENTER, depending on console's
  597. * configuration.
  598. *
  599. * @return void
  600. */
  601. _keydown: function (event) {
  602. if (PMA_console.config.EnterExecutes) {
  603. // Enter, but not in combination with Shift (which writes a new line).
  604. if (!event.shiftKey && event.keyCode === 13) {
  605. PMA_consoleInput.execute();
  606. }
  607. } else {
  608. // Ctrl+Enter
  609. if (event.ctrlKey && event.keyCode === 13) {
  610. PMA_consoleInput.execute();
  611. }
  612. }
  613. },
  614. /**
  615. * Used for send text to PMA_console.execute()
  616. *
  617. * @return void
  618. */
  619. execute: function () {
  620. if (PMA_consoleInput._codemirror) {
  621. PMA_console.execute(PMA_consoleInput._inputs.console.getValue());
  622. } else {
  623. PMA_console.execute(PMA_consoleInput._inputs.console.val());
  624. }
  625. },
  626. /**
  627. * Used for clear the input
  628. *
  629. * @param string target, default target is console input
  630. * @return void
  631. */
  632. clear: function (target) {
  633. PMA_consoleInput.setText('', target);
  634. },
  635. /**
  636. * Used for set focus to input
  637. *
  638. * @return void
  639. */
  640. focus: function () {
  641. PMA_consoleInput._inputs.console.focus();
  642. },
  643. /**
  644. * Used for blur input
  645. *
  646. * @return void
  647. */
  648. blur: function () {
  649. if (PMA_consoleInput._codemirror) {
  650. PMA_consoleInput._inputs.console.getInputField().blur();
  651. } else {
  652. PMA_consoleInput._inputs.console.blur();
  653. }
  654. },
  655. /**
  656. * Used for set text in input
  657. *
  658. * @param string text
  659. * @param string target
  660. * @return void
  661. */
  662. setText: function (text, target) {
  663. if (PMA_consoleInput._codemirror) {
  664. switch (target) {
  665. case 'bookmark':
  666. PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text));
  667. break;
  668. default:
  669. case 'console':
  670. PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text));
  671. }
  672. } else {
  673. switch (target) {
  674. case 'bookmark':
  675. PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text));
  676. break;
  677. default:
  678. case 'console':
  679. PMA_console.execute(PMA_consoleInput._inputs.console.val(text));
  680. }
  681. }
  682. },
  683. getText: function (target) {
  684. if (PMA_consoleInput._codemirror) {
  685. switch (target) {
  686. case 'bookmark':
  687. return PMA_consoleInput._inputs.bookmark.getValue();
  688. default:
  689. case 'console':
  690. return PMA_consoleInput._inputs.console.getValue();
  691. }
  692. } else {
  693. switch (target) {
  694. case 'bookmark':
  695. return PMA_consoleInput._inputs.bookmark.val();
  696. default:
  697. case 'console':
  698. return PMA_consoleInput._inputs.console.val();
  699. }
  700. }
  701. }
  702. };
  703. /**
  704. * Console messages, and message items management object
  705. */
  706. var PMA_consoleMessages = {
  707. /**
  708. * Used for clear the messages
  709. *
  710. * @return void
  711. */
  712. clear: function () {
  713. $('#pma_console').find('.content .console_message_container .message:not(.welcome)').addClass('hide');
  714. $('#pma_console').find('.content .console_message_container .message.failed').remove();
  715. $('#pma_console').find('.content .console_message_container .message.expanded').find('.action.collapse').click();
  716. },
  717. /**
  718. * Used for show history messages
  719. *
  720. * @return void
  721. */
  722. showHistory: function () {
  723. $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide');
  724. },
  725. /**
  726. * Used for getting a perticular history query
  727. *
  728. * @param int nthLast get nth query message from latest, i.e 1st is last
  729. * @return string message
  730. */
  731. getHistory: function (nthLast) {
  732. var $queries = $('#pma_console').find('.content .console_message_container .query');
  733. var length = $queries.length;
  734. var $query = $queries.eq(length - nthLast);
  735. if (!$query || (length - nthLast) < 0) {
  736. return false;
  737. } else {
  738. return $query.text();
  739. }
  740. },
  741. /**
  742. * Used to show the correct message depending on which key
  743. * combination executes the query (Ctrl+Enter or Enter).
  744. *
  745. * @param bool enterExecutes Only Enter has to be pressed to execute query.
  746. * @return void
  747. */
  748. showInstructions: function (enterExecutes) {
  749. enterExecutes = +enterExecutes || 0; // conversion to int
  750. var $welcomeMsg = $('#pma_console').find('.content .console_message_container .message.welcome span');
  751. $welcomeMsg.children('[id^=instructions]').hide();
  752. $welcomeMsg.children('#instructions-' + enterExecutes).show();
  753. },
  754. /**
  755. * Used for log new message
  756. *
  757. * @param string msgString Message to show
  758. * @param string msgType Message type
  759. * @return object, {message_id, $message}
  760. */
  761. append: function (msgString, msgType) {
  762. if (typeof(msgString) !== 'string') {
  763. return false;
  764. }
  765. // Generate an ID for each message, we can find them later
  766. var msgId = Math.round(Math.random() * (899999999999) + 100000000000);
  767. var now = new Date();
  768. var $newMessage =
  769. $('<div class="message ' +
  770. (PMA_console.config.AlwaysExpand ? 'expanded' : 'collapsed') +
  771. '" msgid="' + msgId + '"><div class="action_content"></div></div>');
  772. switch (msgType) {
  773. case 'query':
  774. $newMessage.append('<div class="query highlighted"></div>');
  775. if (PMA_consoleInput._codemirror) {
  776. CodeMirror.runMode(msgString,
  777. 'text/x-sql', $newMessage.children('.query')[0]);
  778. } else {
  779. $newMessage.children('.query').text(msgString);
  780. }
  781. $newMessage.children('.action_content')
  782. .append(PMA_console.$consoleTemplates.children('.query_actions').html());
  783. break;
  784. default:
  785. case 'normal':
  786. $newMessage.append('<div>' + msgString + '</div>');
  787. }
  788. PMA_consoleMessages._msgEventBinds($newMessage);
  789. $newMessage.find('span.text.query_time span')
  790. .text(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds())
  791. .parent().attr('title', now);
  792. return { message_id: msgId,
  793. $message: $newMessage.appendTo('#pma_console .content .console_message_container') };
  794. },
  795. /**
  796. * Used for log new query
  797. *
  798. * @param string queryData Struct should be
  799. * {sql_query: "Query string", db: "Target DB", table: "Target Table"}
  800. * @param string state Message state
  801. * @return object, {message_id: string message id, $message: JQuery object}
  802. */
  803. appendQuery: function (queryData, state) {
  804. var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query');
  805. if (! targetMessage) {
  806. return false;
  807. }
  808. if (queryData.db && queryData.table) {
  809. targetMessage.$message.attr('targetdb', queryData.db);
  810. targetMessage.$message.attr('targettable', queryData.table);
  811. targetMessage.$message.find('.text.targetdb span').text(queryData.db);
  812. }
  813. if (PMA_console.isSelect(queryData.sql_query)) {
  814. targetMessage.$message.addClass('select');
  815. }
  816. switch (state) {
  817. case 'failed':
  818. targetMessage.$message.addClass('failed');
  819. break;
  820. case 'successed':
  821. targetMessage.$message.addClass('successed');
  822. break;
  823. default:
  824. case 'pending':
  825. targetMessage.$message.addClass('pending');
  826. }
  827. return targetMessage;
  828. },
  829. _msgEventBinds: function ($targetMessage) {
  830. // Leave unbinded elements, remove binded.
  831. $targetMessage = $targetMessage.filter(':not(.binded)');
  832. if ($targetMessage.length === 0) {
  833. return;
  834. }
  835. $targetMessage.addClass('binded');
  836. $targetMessage.find('.action.expand').click(function () {
  837. $(this).closest('.message').removeClass('collapsed');
  838. $(this).closest('.message').addClass('expanded');
  839. });
  840. $targetMessage.find('.action.collapse').click(function () {
  841. $(this).closest('.message').addClass('collapsed');
  842. $(this).closest('.message').removeClass('expanded');
  843. });
  844. $targetMessage.find('.action.edit').click(function () {
  845. PMA_consoleInput.setText($(this).parent().siblings('.query').text());
  846. PMA_consoleInput.focus();
  847. });
  848. $targetMessage.find('.action.requery').click(function () {
  849. var query = $(this).parent().siblings('.query').text();
  850. var $message = $(this).closest('.message');
  851. if (confirm(PMA_messages.strConsoleRequeryConfirm + '\n' +
  852. (query.length < 100 ? query : query.slice(0, 100) + '...'))
  853. ) {
  854. PMA_console.execute(query, { db: $message.attr('targetdb'), table: $message.attr('targettable') });
  855. }
  856. });
  857. $targetMessage.find('.action.bookmark').click(function () {
  858. var query = $(this).parent().siblings('.query').text();
  859. var $message = $(this).closest('.message');
  860. PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'));
  861. PMA_console.showCard('#pma_bookmarks .card.add');
  862. });
  863. $targetMessage.find('.action.edit_bookmark').click(function () {
  864. var query = $(this).parent().siblings('.query').text();
  865. var $message = $(this).closest('.message');
  866. var isShared = $message.find('span.bookmark_label').hasClass('shared');
  867. var label = $message.find('span.bookmark_label').text();
  868. PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'), label, isShared);
  869. PMA_console.showCard('#pma_bookmarks .card.add');
  870. });
  871. $targetMessage.find('.action.delete_bookmark').click(function () {
  872. var $message = $(this).closest('.message');
  873. if (confirm(PMA_messages.strConsoleDeleteBookmarkConfirm + '\n' + $message.find('.bookmark_label').text())) {
  874. $.post('import.php',
  875. {
  876. server: PMA_commonParams.get('server'),
  877. action_bookmark: 2,
  878. ajax_request: true,
  879. id_bookmark: $message.attr('bookmarkid') },
  880. function () {
  881. PMA_consoleBookmarks.refresh();
  882. });
  883. }
  884. });
  885. $targetMessage.find('.action.profiling').click(function () {
  886. var $message = $(this).closest('.message');
  887. PMA_console.execute($(this).parent().siblings('.query').text(),
  888. { db: $message.attr('targetdb'),
  889. table: $message.attr('targettable'),
  890. profiling: true });
  891. });
  892. $targetMessage.find('.action.explain').click(function () {
  893. var $message = $(this).closest('.message');
  894. PMA_console.execute('EXPLAIN ' + $(this).parent().siblings('.query').text(),
  895. { db: $message.attr('targetdb'),
  896. table: $message.attr('targettable') });
  897. });
  898. $targetMessage.find('.action.dbg_show_trace').click(function () {
  899. var $message = $(this).closest('.message');
  900. if (!$message.find('.trace').length) {
  901. PMA_consoleDebug.getQueryDetails(
  902. $message.data('queryInfo'),
  903. $message.data('totalTime'),
  904. $message
  905. );
  906. PMA_consoleMessages._msgEventBinds($message.find('.message:not(.binded)'));
  907. }
  908. $message.addClass('show_trace');
  909. $message.removeClass('hide_trace');
  910. });
  911. $targetMessage.find('.action.dbg_hide_trace').click(function () {
  912. var $message = $(this).closest('.message');
  913. $message.addClass('hide_trace');
  914. $message.removeClass('show_trace');
  915. });
  916. $targetMessage.find('.action.dbg_show_args').click(function () {
  917. var $message = $(this).closest('.message');
  918. $message.addClass('show_args expanded');
  919. $message.removeClass('hide_args collapsed');
  920. });
  921. $targetMessage.find('.action.dbg_hide_args').click(function () {
  922. var $message = $(this).closest('.message');
  923. $message.addClass('hide_args collapsed');
  924. $message.removeClass('show_args expanded');
  925. });
  926. if (PMA_consoleInput._codemirror) {
  927. $targetMessage.find('.query:not(.highlighted)').each(function (index, elem) {
  928. CodeMirror.runMode($(elem).text(),
  929. 'text/x-sql', elem);
  930. $(this).addClass('highlighted');
  931. });
  932. }
  933. },
  934. msgAppend: function (msgId, msgString, msgType) {
  935. var $targetMessage = $('#pma_console').find('.content .console_message_container .message[msgid=' + msgId + ']');
  936. if ($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') {
  937. return false;
  938. }
  939. $targetMessage.append('<div>' + msgString + '</div>');
  940. },
  941. updateQuery: function (msgId, isSuccessed, queryData) {
  942. var $targetMessage = $('#pma_console').find('.console_message_container .message[msgid=' + parseInt(msgId) + ']');
  943. if ($targetMessage.length === 0 || isNaN(parseInt(msgId))) {
  944. return false;
  945. }
  946. $targetMessage.removeClass('pending failed successed');
  947. if (isSuccessed) {
  948. $targetMessage.addClass('successed');
  949. if (queryData) {
  950. $targetMessage.children('.query').text('');
  951. $targetMessage.removeClass('select');
  952. if (PMA_console.isSelect(queryData.sql_query)) {
  953. $targetMessage.addClass('select');
  954. }
  955. if (PMA_consoleInput._codemirror) {
  956. CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]);
  957. } else {
  958. $targetMessage.children('.query').text(queryData.sql_query);
  959. }
  960. $targetMessage.attr('targetdb', queryData.db);
  961. $targetMessage.attr('targettable', queryData.table);
  962. $targetMessage.find('.text.targetdb span').text(queryData.db);
  963. }
  964. } else {
  965. $targetMessage.addClass('failed');
  966. }
  967. },
  968. /**
  969. * Used for console messages initialize
  970. *
  971. * @return void
  972. */
  973. initialize: function () {
  974. PMA_consoleMessages._msgEventBinds($('#pma_console').find('.message:not(.binded)'));
  975. if (PMA_console.config.StartHistory) {
  976. PMA_consoleMessages.showHistory();
  977. }
  978. PMA_consoleMessages.showInstructions(PMA_console.config.EnterExecutes);
  979. }
  980. };
  981. /**
  982. * Console bookmarks card, and bookmarks items management object
  983. */
  984. var PMA_consoleBookmarks = {
  985. _bookmarks: [],
  986. addBookmark: function (queryString, targetDb, label, isShared, id) {
  987. $('#pma_bookmarks').find('.add [name=shared]').prop('checked', false);
  988. $('#pma_bookmarks').find('.add [name=label]').val('');
  989. $('#pma_bookmarks').find('.add [name=targetdb]').val('');
  990. $('#pma_bookmarks').find('.add [name=id_bookmark]').val('');
  991. PMA_consoleInput.setText('', 'bookmark');
  992. switch (arguments.length) {
  993. case 4:
  994. $('#pma_bookmarks').find('.add [name=shared]').prop('checked', isShared);
  995. case 3:
  996. $('#pma_bookmarks').find('.add [name=label]').val(label);
  997. case 2:
  998. $('#pma_bookmarks').find('.add [name=targetdb]').val(targetDb);
  999. case 1:
  1000. PMA_consoleInput.setText(queryString, 'bookmark');
  1001. default:
  1002. break;
  1003. }
  1004. },
  1005. refresh: function () {
  1006. $.get('import.php',
  1007. { ajax_request: true,
  1008. server: PMA_commonParams.get('server'),
  1009. console_bookmark_refresh: 'refresh' },
  1010. function (data) {
  1011. if (data.console_message_bookmark) {
  1012. $('#pma_bookmarks').find('.content.bookmark').html(data.console_message_bookmark);
  1013. PMA_consoleMessages._msgEventBinds($('#pma_bookmarks').find('.message:not(.binded)'));
  1014. }
  1015. });
  1016. },
  1017. /**
  1018. * Used for console bookmarks initialize
  1019. * message events are already binded by PMA_consoleMsg._msgEventBinds
  1020. *
  1021. * @return void
  1022. */
  1023. initialize: function () {
  1024. if ($('#pma_bookmarks').length === 0) {
  1025. return;
  1026. }
  1027. $('#pma_console').find('.button.bookmarks').click(function () {
  1028. PMA_console.showCard('#pma_bookmarks');
  1029. });
  1030. $('#pma_bookmarks').find('.button.add').click(function () {
  1031. PMA_console.showCard('#pma_bookmarks .card.add');
  1032. });
  1033. $('#pma_bookmarks').find('.card.add [name=submit]').click(function () {
  1034. if ($('#pma_bookmarks').find('.card.add [name=label]').val().length === 0
  1035. || PMA_consoleInput.getText('bookmark').length === 0) {
  1036. alert(PMA_messages.strFormEmpty);
  1037. return;
  1038. }
  1039. $(this).prop('disabled', true);
  1040. $.post('import.php',
  1041. {
  1042. ajax_request: true,
  1043. console_bookmark_add: 'true',
  1044. label: $('#pma_bookmarks').find('.card.add [name=label]').val(),
  1045. server: PMA_commonParams.get('server'),
  1046. db: $('#pma_bookmarks').find('.card.add [name=targetdb]').val(),
  1047. bookmark_query: PMA_consoleInput.getText('bookmark'),
  1048. shared: $('#pma_bookmarks').find('.card.add [name=shared]').prop('checked') },
  1049. function () {
  1050. PMA_consoleBookmarks.refresh();
  1051. $('#pma_bookmarks').find('.card.add [name=submit]').prop('disabled', false);
  1052. PMA_console.hideCard($('#pma_bookmarks').find('.card.add'));
  1053. });
  1054. });
  1055. $('#pma_console').find('.button.refresh').click(function () {
  1056. PMA_consoleBookmarks.refresh();
  1057. });
  1058. }
  1059. };
  1060. var PMA_consoleDebug;
  1061. PMA_consoleDebug = {
  1062. _config: {
  1063. groupQueries: false,
  1064. orderBy: 'exec', // Possible 'exec' => Execution order, 'time' => Time taken, 'count'
  1065. order: 'asc' // Possible 'asc', 'desc'
  1066. },
  1067. _lastDebugInfo: {
  1068. debugInfo: null,
  1069. url: null
  1070. },
  1071. initialize: function () {
  1072. // Try to get debug info after every AJAX request
  1073. $(document).ajaxSuccess(function (event, xhr, settings, data) {
  1074. if (data._debug) {
  1075. PMA_consoleDebug.showLog(data._debug, settings.url);
  1076. }
  1077. });
  1078. if (PMA_console.config.GroupQueries) {
  1079. $('#debug_console').addClass('grouped');
  1080. } else {
  1081. $('#debug_console').addClass('ungrouped');
  1082. if (PMA_console.config.OrderBy === 'count') {
  1083. $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
  1084. }
  1085. }
  1086. var orderBy = PMA_console.config.OrderBy;
  1087. var order = PMA_console.config.Order;
  1088. $('#debug_console').find('.button.order_by.sort_' + orderBy).addClass('active');
  1089. $('#debug_console').find('.button.order.order_' + order).addClass('active');
  1090. // Initialize actions in toolbar
  1091. $('#debug_console').find('.button.group_queries').click(function () {
  1092. $('#debug_console').addClass('grouped');
  1093. $('#debug_console').removeClass('ungrouped');
  1094. PMA_console.setConfig('GroupQueries', true);
  1095. PMA_consoleDebug.refresh();
  1096. if (PMA_console.config.OrderBy === 'count') {
  1097. $('#debug_console').find('.button.order_by.sort_exec').removeClass('active');
  1098. }
  1099. });
  1100. $('#debug_console').find('.button.ungroup_queries').click(function () {
  1101. $('#debug_console').addClass('ungrouped');
  1102. $('#debug_console').removeClass('grouped');
  1103. PMA_console.setConfig('GroupQueries', false);
  1104. PMA_consoleDebug.refresh();
  1105. if (PMA_console.config.OrderBy === 'count') {
  1106. $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
  1107. }
  1108. });
  1109. $('#debug_console').find('.button.order_by').click(function () {
  1110. var $this = $(this);
  1111. $('#debug_console').find('.button.order_by').removeClass('active');
  1112. $this.addClass('active');
  1113. if ($this.hasClass('sort_time')) {
  1114. PMA_console.setConfig('OrderBy', 'time');
  1115. } else if ($this.hasClass('sort_exec')) {
  1116. PMA_console.setConfig('OrderBy', 'exec');
  1117. } else if ($this.hasClass('sort_count')) {
  1118. PMA_console.setConfig('OrderBy', 'count');
  1119. }
  1120. PMA_consoleDebug.refresh();
  1121. });
  1122. $('#debug_console').find('.button.order').click(function () {
  1123. var $this = $(this);
  1124. $('#debug_console').find('.button.order').removeClass('active');
  1125. $this.addClass('active');
  1126. if ($this.hasClass('order_asc')) {
  1127. PMA_console.setConfig('Order', 'asc');
  1128. } else if ($this.hasClass('order_desc')) {
  1129. PMA_console.setConfig('Order', 'desc');
  1130. }
  1131. PMA_consoleDebug.refresh();
  1132. });
  1133. // Show SQL debug info for first page load
  1134. if (typeof debugSQLInfo !== 'undefined' && debugSQLInfo !== 'null') {
  1135. $('#pma_console').find('.button.debug').removeClass('hide');
  1136. } else {
  1137. return;
  1138. }
  1139. PMA_consoleDebug.showLog(debugSQLInfo);
  1140. },
  1141. _formatFunctionCall: function (dbgStep) {
  1142. var functionName = '';
  1143. if ('class' in dbgStep) {
  1144. functionName += dbgStep.class;
  1145. functionName += dbgStep.type;
  1146. }
  1147. functionName += dbgStep.function;
  1148. if (dbgStep.args && dbgStep.args.length) {
  1149. functionName += '(...)';
  1150. } else {
  1151. functionName += '()';
  1152. }
  1153. return functionName;
  1154. },
  1155. _formatFunctionArgs: function (dbgStep) {
  1156. var $args = $('<div>');
  1157. if (dbgStep.args.length) {
  1158. $args.append('<div class="message welcome">')
  1159. .append(
  1160. $('<div class="message welcome">')
  1161. .text(
  1162. PMA_sprintf(
  1163. PMA_messages.strConsoleDebugArgsSummary,
  1164. dbgStep.args.length
  1165. )
  1166. )
  1167. );
  1168. for (var i = 0; i < dbgStep.args.length; i++) {
  1169. $args.append(
  1170. $('<div class="message">')
  1171. .html(
  1172. '<pre>' +
  1173. escapeHtml(JSON.stringify(dbgStep.args[i], null, ' ')) +
  1174. '</pre>'
  1175. )
  1176. );
  1177. }
  1178. }
  1179. return $args;
  1180. },
  1181. _formatFileName: function (dbgStep) {
  1182. var fileName = '';
  1183. if ('file' in dbgStep) {
  1184. fileName += dbgStep.file;
  1185. fileName += '#' + dbgStep.line;
  1186. }
  1187. return fileName;
  1188. },
  1189. _formatBackTrace: function (dbgTrace) {
  1190. var $traceElem = $('<div class="trace">');
  1191. $traceElem.append(
  1192. $('<div class="message welcome">')
  1193. );
  1194. var step;
  1195. var $stepElem;
  1196. for (var stepId in dbgTrace) {
  1197. if (dbgTrace.hasOwnProperty(stepId)) {
  1198. step = dbgTrace[stepId];
  1199. if (!Array.isArray(step) && typeof step !== 'object') {
  1200. $stepElem =
  1201. $('<div class="message traceStep collapsed hide_args">')
  1202. .append(
  1203. $('<span>').text(step)
  1204. );
  1205. } else {
  1206. if (typeof step.args === 'string' && step.args) {
  1207. step.args = [step.args];
  1208. }
  1209. $stepElem =
  1210. $('<div class="message traceStep collapsed hide_args">')
  1211. .append(
  1212. $('<span class="function">').text(this._formatFunctionCall(step))
  1213. )
  1214. .append(
  1215. $('<span class="file">').text(this._formatFileName(step))
  1216. );
  1217. if (step.args && step.args.length) {
  1218. $stepElem
  1219. .append(
  1220. $('<span class="args">').html(this._formatFunctionArgs(step))
  1221. )
  1222. .prepend(
  1223. $('<div class="action_content">')
  1224. .append(
  1225. '<span class="action dbg_show_args">' +
  1226. PMA_messages.strConsoleDebugShowArgs +
  1227. '</span> '
  1228. )
  1229. .append(
  1230. '<span class="action dbg_hide_args">' +
  1231. PMA_messages.strConsoleDebugHideArgs +
  1232. '</span> '
  1233. )
  1234. );
  1235. }
  1236. }
  1237. $traceElem.append($stepElem);
  1238. }
  1239. }
  1240. return $traceElem;
  1241. },
  1242. _formatQueryOrGroup: function (queryInfo, totalTime) {
  1243. var grouped;
  1244. var queryText;
  1245. var queryTime;
  1246. var count;
  1247. var i;
  1248. if (Array.isArray(queryInfo)) {
  1249. // It is grouped
  1250. grouped = true;
  1251. queryText = queryInfo[0].query;
  1252. queryTime = 0;
  1253. for (i in queryInfo) {
  1254. queryTime += queryInfo[i].time;
  1255. }
  1256. count = queryInfo.length;
  1257. } else {
  1258. queryText = queryInfo.query;
  1259. queryTime = queryInfo.time;
  1260. }
  1261. var $query = $('<div class="message collapsed hide_trace">')
  1262. .append(
  1263. $('#debug_console').find('.templates .debug_query').clone()
  1264. )
  1265. .append(
  1266. $('<div class="query">')
  1267. .text(queryText)
  1268. )
  1269. .data('queryInfo', queryInfo)
  1270. .data('totalTime', totalTime);
  1271. if (grouped) {
  1272. $query.find('.text.count').removeClass('hide');
  1273. $query.find('.text.count span').text(count);
  1274. }
  1275. $query.find('.text.time span').text(queryTime + 's (' + ((queryTime * 100) / totalTime).toFixed(3) + '%)');
  1276. return $query;
  1277. },
  1278. _appendQueryExtraInfo: function (query, $elem) {
  1279. if ('error' in query) {
  1280. $elem.append(
  1281. $('<div>').html(query.error)
  1282. );
  1283. }
  1284. $elem.append(this._formatBackTrace(query.trace));
  1285. },
  1286. getQueryDetails: function (queryInfo, totalTime, $query) {
  1287. if (Array.isArray(queryInfo)) {
  1288. var $singleQuery;
  1289. for (var i in queryInfo) {
  1290. $singleQuery = $('<div class="message welcome trace">')
  1291. .text((parseInt(i) + 1) + '.')
  1292. .append(
  1293. $('<span class="time">').text(
  1294. PMA_messages.strConsoleDebugTimeTaken +
  1295. ' ' + queryInfo[i].time + 's' +
  1296. ' (' + ((queryInfo[i].time * 100) / totalTime).toFixed(3) + '%)'
  1297. )
  1298. );
  1299. this._appendQueryExtraInfo(queryInfo[i], $singleQuery);
  1300. $query
  1301. .append('<div class="message welcome trace">')
  1302. .append($singleQuery);
  1303. }
  1304. } else {
  1305. this._appendQueryExtraInfo(queryInfo, $query);
  1306. }
  1307. },
  1308. showLog: function (debugInfo, url) {
  1309. this._lastDebugInfo.debugInfo = debugInfo;
  1310. this._lastDebugInfo.url = url;
  1311. $('#debug_console').find('.debugLog').empty();
  1312. $('#debug_console').find('.debug>.welcome').empty();
  1313. var debugJson = false;
  1314. var i;
  1315. if (typeof debugInfo === 'object' && 'queries' in debugInfo) {
  1316. // Copy it to debugJson, so that it doesn't get changed
  1317. if (!('queries' in debugInfo)) {
  1318. debugJson = false;
  1319. } else {
  1320. debugJson = { queries: [] };
  1321. for (i in debugInfo.queries) {
  1322. debugJson.queries[i] = debugInfo.queries[i];
  1323. }
  1324. }
  1325. } else if (typeof debugInfo === 'string') {
  1326. try {
  1327. debugJson = JSON.parse(debugInfo);
  1328. } catch (e) {
  1329. debugJson = false;
  1330. }
  1331. if (debugJson && !('queries' in debugJson)) {
  1332. debugJson = false;
  1333. }
  1334. }
  1335. if (debugJson === false) {
  1336. $('#debug_console').find('.debug>.welcome').text(
  1337. PMA_messages.strConsoleDebugError
  1338. );
  1339. return;
  1340. }
  1341. var allQueries = debugJson.queries;
  1342. var uniqueQueries = {};
  1343. var totalExec = allQueries.length;
  1344. // Calculate total time and make unique query array
  1345. var totalTime = 0;
  1346. for (i = 0; i < totalExec; ++i) {
  1347. totalTime += allQueries[i].time;
  1348. if (!(allQueries[i].hash in uniqueQueries)) {
  1349. uniqueQueries[allQueries[i].hash] = [];
  1350. }
  1351. uniqueQueries[allQueries[i].hash].push(allQueries[i]);
  1352. }
  1353. // Count total unique queries, convert uniqueQueries to Array
  1354. var totalUnique = 0;
  1355. var uniqueArray = [];
  1356. for (var hash in uniqueQueries) {
  1357. if (uniqueQueries.hasOwnProperty(hash)) {
  1358. ++totalUnique;
  1359. uniqueArray.push(uniqueQueries[hash]);
  1360. }
  1361. }
  1362. uniqueQueries = uniqueArray;
  1363. // Show summary
  1364. $('#debug_console').find('.debug>.welcome').append(
  1365. $('<span class="debug_summary">').text(
  1366. PMA_sprintf(
  1367. PMA_messages.strConsoleDebugSummary,
  1368. totalUnique,
  1369. totalExec,
  1370. totalTime
  1371. )
  1372. )
  1373. );
  1374. if (url) {
  1375. $('#debug_console').find('.debug>.welcome').append(
  1376. $('<span class="script_name">').text(url.split('?')[0])
  1377. );
  1378. }
  1379. // For sorting queries
  1380. function sortByTime (a, b) {
  1381. var order = ((PMA_console.config.Order === 'asc') ? 1 : -1);
  1382. if (Array.isArray(a) && Array.isArray(b)) {
  1383. // It is grouped
  1384. var timeA = 0;
  1385. var timeB = 0;
  1386. var i;
  1387. for (i in a) {
  1388. timeA += a[i].time;
  1389. }
  1390. for (i in b) {
  1391. timeB += b[i].time;
  1392. }
  1393. return (timeA - timeB) * order;
  1394. } else {
  1395. return (a.time - b.time) * order;
  1396. }
  1397. }
  1398. function sortByCount (a, b) {
  1399. var order = ((PMA_console.config.Oorder === 'asc') ? 1 : -1);
  1400. return (a.length - b.length) * order;
  1401. }
  1402. var orderBy = PMA_console.config.OrderBy;
  1403. var order = PMA_console.config.Order;
  1404. if (PMA_console.config.GroupQueries) {
  1405. // Sort queries
  1406. if (orderBy === 'time') {
  1407. uniqueQueries.sort(sortByTime);
  1408. } else if (orderBy === 'count') {
  1409. uniqueQueries.sort(sortByCount);
  1410. } else if (orderBy === 'exec' && order === 'desc') {
  1411. uniqueQueries.reverse();
  1412. }
  1413. for (i in uniqueQueries) {
  1414. if (orderBy === 'time') {
  1415. uniqueQueries[i].sort(sortByTime);
  1416. } else if (orderBy === 'exec' && order === 'desc') {
  1417. uniqueQueries[i].reverse();
  1418. }
  1419. $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(uniqueQueries[i], totalTime));
  1420. }
  1421. } else {
  1422. if (orderBy === 'time') {
  1423. allQueries.sort(sortByTime);
  1424. } else if (order === 'desc') {
  1425. allQueries.reverse();
  1426. }
  1427. for (i = 0; i < totalExec; ++i) {
  1428. $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(allQueries[i], totalTime));
  1429. }
  1430. }
  1431. PMA_consoleMessages._msgEventBinds($('#debug_console').find('.message:not(.binded)'));
  1432. },
  1433. refresh: function () {
  1434. var last = this._lastDebugInfo;
  1435. PMA_consoleDebug.showLog(last.debugInfo, last.url);
  1436. }
  1437. };
  1438. /** s
  1439. * Executed on page load
  1440. */
  1441. $(function () {
  1442. PMA_console.initialize();
  1443. });