console.js 57 KB

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