console.js 48 KB

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