PageRenderTime 75ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/phpMyAdmin/js/functions.js

https://gitlab.com/Evorx/uni
JavaScript | 4109 lines | 3226 code | 209 blank | 674 comment | 555 complexity | 1e78695f2b6be61a252a53e7e7049f0f MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * general function, usually for data manipulation pages
  4. *
  5. */
  6. /**
  7. * @var $table_clone reference to the action links on the tbl_structure page
  8. */
  9. var $table_clone = false;
  10. /**
  11. * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
  12. */
  13. var sql_box_locked = false;
  14. /**
  15. * @var array holds elements which content should only selected once
  16. */
  17. var only_once_elements = [];
  18. /**
  19. * @var int ajax_message_count Number of AJAX messages shown since page load
  20. */
  21. var ajax_message_count = 0;
  22. /**
  23. * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
  24. */
  25. var codemirror_editor = false;
  26. /**
  27. * @var codemirror_editor object containing CodeMirror editor of the inline query editor
  28. */
  29. var codemirror_inline_editor = false;
  30. /**
  31. * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
  32. */
  33. var chart_activeTimeouts = {};
  34. /**
  35. * Make sure that ajax requests will not be cached
  36. * by appending a random variable to their parameters
  37. */
  38. $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  39. var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
  40. if (typeof options.data == "string") {
  41. options.data += "&_nocache=" + nocache;
  42. } else if (typeof options.data == "object") {
  43. options.data = $.extend(originalOptions.data, {'_nocache' : nocache});
  44. }
  45. });
  46. /**
  47. * Add a hidden field to the form to indicate that this will be an
  48. * Ajax request (only if this hidden field does not exist)
  49. *
  50. * @param object the form
  51. */
  52. function PMA_prepareForAjaxRequest($form)
  53. {
  54. if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
  55. $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
  56. }
  57. }
  58. /**
  59. * Generate a new password and copy it to the password input areas
  60. *
  61. * @param object the form that holds the password fields
  62. *
  63. * @return boolean always true
  64. */
  65. function suggestPassword(passwd_form)
  66. {
  67. // restrict the password to just letters and numbers to avoid problems:
  68. // "editors and viewers regard the password as multiple words and
  69. // things like double click no longer work"
  70. var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
  71. var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
  72. var passwd = passwd_form.generated_pw;
  73. passwd.value = '';
  74. for (var i = 0; i < passwordlength; i++) {
  75. passwd.value += pwchars.charAt(Math.floor(Math.random() * pwchars.length));
  76. }
  77. passwd_form.text_pma_pw.value = passwd.value;
  78. passwd_form.text_pma_pw2.value = passwd.value;
  79. return true;
  80. }
  81. /**
  82. * Version string to integer conversion.
  83. */
  84. function parseVersionString(str)
  85. {
  86. if (typeof(str) != 'string') { return false; }
  87. var add = 0;
  88. // Parse possible alpha/beta/rc/
  89. var state = str.split('-');
  90. if (state.length >= 2) {
  91. if (state[1].substr(0, 2) == 'rc') {
  92. add = - 20 - parseInt(state[1].substr(2), 10);
  93. } else if (state[1].substr(0, 4) == 'beta') {
  94. add = - 40 - parseInt(state[1].substr(4), 10);
  95. } else if (state[1].substr(0, 5) == 'alpha') {
  96. add = - 60 - parseInt(state[1].substr(5), 10);
  97. } else if (state[1].substr(0, 3) == 'dev') {
  98. /* We don't handle dev, it's git snapshot */
  99. add = 0;
  100. }
  101. }
  102. // Parse version
  103. var x = str.split('.');
  104. // Use 0 for non existing parts
  105. var maj = parseInt(x[0], 10) || 0;
  106. var min = parseInt(x[1], 10) || 0;
  107. var pat = parseInt(x[2], 10) || 0;
  108. var hotfix = parseInt(x[3], 10) || 0;
  109. return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
  110. }
  111. /**
  112. * Indicates current available version on main page.
  113. */
  114. function PMA_current_version(data)
  115. {
  116. if (data && data.version && data.date) {
  117. var current = parseVersionString(pmaversion);
  118. var latest = parseVersionString(data.version);
  119. var version_information_message = '<span>'
  120. + PMA_messages.strLatestAvailable
  121. + ' ' + escapeHtml(data.version)
  122. + '</span>';
  123. if (latest > current) {
  124. var message = $.sprintf(
  125. PMA_messages.strNewerVersion,
  126. escapeHtml(data.version),
  127. escapeHtml(data.date)
  128. );
  129. var htmlClass = 'notice';
  130. if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
  131. /* Security update */
  132. htmlClass = 'error';
  133. }
  134. $('#maincontainer').after('<div class="' + htmlClass + '">' + message + '</div>');
  135. }
  136. if (latest === current) {
  137. version_information_message = ' (' + PMA_messages.strUpToDate + ')';
  138. }
  139. $('#li_pma_version span').remove();
  140. $('#li_pma_version').append(version_information_message);
  141. }
  142. }
  143. /**
  144. * Loads Git revision data from ajax for index.php
  145. */
  146. function PMA_display_git_revision()
  147. {
  148. $('#is_git_revision').remove();
  149. $('#li_pma_version_git').remove();
  150. $.get(
  151. "index.php",
  152. {
  153. "server": PMA_commonParams.get('server'),
  154. "token": PMA_commonParams.get('token'),
  155. "git_revision": true,
  156. "ajax_request": true
  157. },
  158. function (data) {
  159. if (data.success === true) {
  160. $(data.message).insertAfter('#li_pma_version');
  161. }
  162. }
  163. );
  164. }
  165. /**
  166. * for libraries/display_change_password.lib.php
  167. * libraries/user_password.php
  168. *
  169. */
  170. function displayPasswordGenerateButton()
  171. {
  172. $('#tr_element_before_generate_password').parent().append('<tr class="vmiddle"><td>' + PMA_messages.strGeneratePassword + '</td><td><input type="button" class="button" id="button_generate_password" value="' + PMA_messages.strGenerate + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
  173. $('#div_element_before_generate_password').parent().append('<div class="item"><label for="button_generate_password">' + PMA_messages.strGeneratePassword + ':</label><span class="options"><input type="button" class="button" id="button_generate_password" value="' + PMA_messages.strGenerate + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
  174. }
  175. /*
  176. * Adds a date/time picker to an element
  177. *
  178. * @param object $this_element a jQuery object pointing to the element
  179. */
  180. function PMA_addDatepicker($this_element, options)
  181. {
  182. var showTimeOption = false;
  183. if ($this_element.is('.datetimefield')) {
  184. showTimeOption = true;
  185. }
  186. var defaultOptions = {
  187. showOn: 'button',
  188. buttonImage: themeCalendarImage, // defined in js/messages.php
  189. buttonImageOnly: true,
  190. stepMinutes: 1,
  191. stepHours: 1,
  192. showSecond: true,
  193. showMillisec: true,
  194. showMicrosec: true,
  195. showTimepicker: showTimeOption,
  196. showButtonPanel: false,
  197. dateFormat: 'yy-mm-dd', // yy means year with four digits
  198. timeFormat: 'HH:mm:ss.lc',
  199. constrainInput: false,
  200. altFieldTimeOnly: false,
  201. showAnim: '',
  202. beforeShow: function (input, inst) {
  203. // Remember that we came from the datepicker; this is used
  204. // in tbl_change.js by verificationsAfterFieldChange()
  205. $this_element.data('comes_from', 'datepicker');
  206. // Fix wrong timepicker z-index, doesn't work without timeout
  207. setTimeout(function () {
  208. $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index'));
  209. }, 0);
  210. },
  211. onClose: function (dateText, dp_inst) {
  212. // The value is no more from the date picker
  213. $this_element.data('comes_from', '');
  214. }
  215. };
  216. if (showTimeOption || (typeof(options) != 'undefined' && options.showTimepicker)) {
  217. $this_element.datetimepicker($.extend(defaultOptions, options));
  218. } else {
  219. $this_element.datepicker($.extend(defaultOptions, options));
  220. }
  221. }
  222. /**
  223. * selects the content of a given object, f.e. a textarea
  224. *
  225. * @param object element element of which the content will be selected
  226. * @param var lock variable which holds the lock for this element
  227. * or true, if no lock exists
  228. * @param boolean only_once if true this is only done once
  229. * f.e. only on first focus
  230. */
  231. function selectContent(element, lock, only_once)
  232. {
  233. if (only_once && only_once_elements[element.name]) {
  234. return;
  235. }
  236. only_once_elements[element.name] = true;
  237. if (lock) {
  238. return;
  239. }
  240. element.select();
  241. }
  242. /**
  243. * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
  244. * This function is called while clicking links
  245. *
  246. * @param object the link
  247. * @param object the sql query to submit
  248. *
  249. * @return boolean whether to run the query or not
  250. */
  251. function confirmLink(theLink, theSqlQuery)
  252. {
  253. // Confirmation is not required in the configuration file
  254. // or browser is Opera (crappy js implementation)
  255. if (PMA_messages.strDoYouReally === '' || typeof(window.opera) != 'undefined') {
  256. return true;
  257. }
  258. var is_confirmed = confirm($.sprintf(PMA_messages.strDoYouReally, theSqlQuery));
  259. if (is_confirmed) {
  260. if ($(theLink).hasClass('formLinkSubmit')) {
  261. var name = 'is_js_confirmed';
  262. if ($(theLink).attr('href').indexOf('usesubform') != -1) {
  263. name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
  264. }
  265. $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
  266. } else if (typeof(theLink.href) != 'undefined') {
  267. theLink.href += '&is_js_confirmed=1';
  268. } else if (typeof(theLink.form) != 'undefined') {
  269. theLink.form.action += '?is_js_confirmed=1';
  270. }
  271. }
  272. return is_confirmed;
  273. } // end of the 'confirmLink()' function
  274. /**
  275. * Displays an error message if a "DROP DATABASE" statement is submitted
  276. * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
  277. * sumitting it if required.
  278. * This function is called by the 'checkSqlQuery()' js function.
  279. *
  280. * @param object the form
  281. * @param object the sql query textarea
  282. *
  283. * @return boolean whether to run the query or not
  284. *
  285. * @see checkSqlQuery()
  286. */
  287. function confirmQuery(theForm1, sqlQuery1)
  288. {
  289. // Confirmation is not required in the configuration file
  290. if (PMA_messages.strDoYouReally === '') {
  291. return true;
  292. }
  293. // "DROP DATABASE" statement isn't allowed
  294. if (PMA_messages.strNoDropDatabases !== '') {
  295. var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
  296. if (drop_re.test(sqlQuery1.value)) {
  297. alert(PMA_messages.strNoDropDatabases);
  298. theForm1.reset();
  299. sqlQuery1.focus();
  300. return false;
  301. } // end if
  302. } // end if
  303. // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
  304. //
  305. // TODO: find a way (if possible) to use the parser-analyser
  306. // for this kind of verification
  307. // For now, I just added a ^ to check for the statement at
  308. // beginning of expression
  309. var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
  310. var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
  311. var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
  312. var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
  313. if (do_confirm_re_0.test(sqlQuery1.value) ||
  314. do_confirm_re_1.test(sqlQuery1.value) ||
  315. do_confirm_re_2.test(sqlQuery1.value) ||
  316. do_confirm_re_3.test(sqlQuery1.value)) {
  317. var message;
  318. if (sqlQuery1.value.length > 100) {
  319. message = sqlQuery1.value.substr(0, 100) + '\n ...';
  320. } else {
  321. message = sqlQuery1.value;
  322. }
  323. var is_confirmed = confirm($.sprintf(PMA_messages.strDoYouReally, message));
  324. // statement is confirmed -> update the
  325. // "is_js_confirmed" form field so the confirm test won't be
  326. // run on the server side and allows to submit the form
  327. if (is_confirmed) {
  328. theForm1.elements['is_js_confirmed'].value = 1;
  329. return true;
  330. }
  331. // statement is rejected -> do not submit the form
  332. else {
  333. window.focus();
  334. sqlQuery1.focus();
  335. return false;
  336. } // end if (handle confirm box result)
  337. } // end if (display confirm box)
  338. return true;
  339. } // end of the 'confirmQuery()' function
  340. /**
  341. * Displays an error message if the user submitted the sql query form with no
  342. * sql query, else checks for "DROP/DELETE/ALTER" statements
  343. *
  344. * @param object the form
  345. *
  346. * @return boolean always false
  347. *
  348. * @see confirmQuery()
  349. */
  350. function checkSqlQuery(theForm)
  351. {
  352. // get the textarea element containing the query
  353. if (codemirror_editor) {
  354. codemirror_editor.save();
  355. var sqlQuery = codemirror_editor.display.input;
  356. sqlQuery.value = codemirror_editor.getValue();
  357. } else {
  358. var sqlQuery = theForm.elements['sql_query'];
  359. }
  360. var isEmpty = 1;
  361. var space_re = new RegExp('\\s+');
  362. if (typeof(theForm.elements['sql_file']) != 'undefined' &&
  363. theForm.elements['sql_file'].value.replace(space_re, '') !== '') {
  364. return true;
  365. }
  366. if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
  367. theForm.elements['sql_localfile'].value.replace(space_re, '') !== '') {
  368. return true;
  369. }
  370. if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
  371. (theForm.elements['id_bookmark'].value !== null || theForm.elements['id_bookmark'].value !== '') &&
  372. theForm.elements['id_bookmark'].selectedIndex !== 0) {
  373. return true;
  374. }
  375. // Checks for "DROP/DELETE/ALTER" statements
  376. if (sqlQuery.value.replace(space_re, '') !== '') {
  377. if (confirmQuery(theForm, sqlQuery)) {
  378. return true;
  379. } else {
  380. return false;
  381. }
  382. }
  383. theForm.reset();
  384. isEmpty = 1;
  385. if (isEmpty) {
  386. sqlQuery.select();
  387. alert(PMA_messages.strFormEmpty);
  388. sqlQuery.focus();
  389. return false;
  390. }
  391. return true;
  392. } // end of the 'checkSqlQuery()' function
  393. /**
  394. * Check if a form's element is empty.
  395. * An element containing only spaces is also considered empty
  396. *
  397. * @param object the form
  398. * @param string the name of the form field to put the focus on
  399. *
  400. * @return boolean whether the form field is empty or not
  401. */
  402. function emptyCheckTheField(theForm, theFieldName)
  403. {
  404. var theField = theForm.elements[theFieldName];
  405. var space_re = new RegExp('\\s+');
  406. return (theField.value.replace(space_re, '') === '') ? 1 : 0;
  407. } // end of the 'emptyCheckTheField()' function
  408. /**
  409. * Check whether a form field is empty or not
  410. *
  411. * @param object the form
  412. * @param string the name of the form field to put the focus on
  413. *
  414. * @return boolean whether the form field is empty or not
  415. */
  416. function emptyFormElements(theForm, theFieldName)
  417. {
  418. var theField = theForm.elements[theFieldName];
  419. var isEmpty = emptyCheckTheField(theForm, theFieldName);
  420. return isEmpty;
  421. } // end of the 'emptyFormElements()' function
  422. /**
  423. * Ensures a value submitted in a form is numeric and is in a range
  424. *
  425. * @param object the form
  426. * @param string the name of the form field to check
  427. * @param integer the minimum authorized value
  428. * @param integer the maximum authorized value
  429. *
  430. * @return boolean whether a valid number has been submitted or not
  431. */
  432. function checkFormElementInRange(theForm, theFieldName, message, min, max)
  433. {
  434. var theField = theForm.elements[theFieldName];
  435. var val = parseInt(theField.value, 10);
  436. if (typeof(min) == 'undefined') {
  437. min = 0;
  438. }
  439. if (typeof(max) == 'undefined') {
  440. max = Number.MAX_VALUE;
  441. }
  442. // It's not a number
  443. if (isNaN(val)) {
  444. theField.select();
  445. alert(PMA_messages.strEnterValidNumber);
  446. theField.focus();
  447. return false;
  448. }
  449. // It's a number but it is not between min and max
  450. else if (val < min || val > max) {
  451. theField.select();
  452. alert($.sprintf(message, val));
  453. theField.focus();
  454. return false;
  455. }
  456. // It's a valid number
  457. else {
  458. theField.value = val;
  459. }
  460. return true;
  461. } // end of the 'checkFormElementInRange()' function
  462. function checkTableEditForm(theForm, fieldsCnt)
  463. {
  464. // TODO: avoid sending a message if user just wants to add a line
  465. // on the form but has not completed at least one field name
  466. var atLeastOneField = 0;
  467. var i, elm, elm2, elm3, val, id;
  468. for (i = 0; i < fieldsCnt; i++) {
  469. id = "#field_" + i + "_2";
  470. elm = $(id);
  471. val = elm.val();
  472. if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
  473. elm2 = $("#field_" + i + "_3");
  474. val = parseInt(elm2.val(), 10);
  475. elm3 = $("#field_" + i + "_1");
  476. if (isNaN(val) && elm3.val() !== "") {
  477. elm2.select();
  478. alert(PMA_messages.strEnterValidLength);
  479. elm2.focus();
  480. return false;
  481. }
  482. }
  483. if (atLeastOneField === 0) {
  484. id = "field_" + i + "_1";
  485. if (!emptyCheckTheField(theForm, id)) {
  486. atLeastOneField = 1;
  487. }
  488. }
  489. }
  490. if (atLeastOneField === 0) {
  491. var theField = theForm.elements["field_0_1"];
  492. alert(PMA_messages.strFormEmpty);
  493. theField.focus();
  494. return false;
  495. }
  496. // at least this section is under jQuery
  497. if ($("input.textfield[name='table']").val() === "") {
  498. alert(PMA_messages.strFormEmpty);
  499. $("input.textfield[name='table']").focus();
  500. return false;
  501. }
  502. return true;
  503. } // enf of the 'checkTableEditForm()' function
  504. /**
  505. * Unbind all event handlers before tearing down a page
  506. */
  507. AJAX.registerTeardown('functions.js', function () {
  508. $('input:checkbox.checkall').die('click');
  509. });
  510. AJAX.registerOnload('functions.js', function () {
  511. /**
  512. * Row marking in horizontal mode (use "live" so that it works also for
  513. * next pages reached via AJAX); a tr may have the class noclick to remove
  514. * this behavior.
  515. */
  516. $('input:checkbox.checkall').live('click', function (e) {
  517. var $tr = $(this).closest('tr');
  518. // make the table unselectable (to prevent default highlighting when shift+click)
  519. //$tr.parents('table').noSelect();
  520. if (!e.shiftKey || last_clicked_row == -1) {
  521. // usual click
  522. // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
  523. var $checkbox = $tr.find(':checkbox');
  524. if ($checkbox.length) {
  525. // checkbox in a row, add or remove class depending on checkbox state
  526. var checked = $checkbox.prop('checked');
  527. if (!$(e.target).is(':checkbox, label')) {
  528. checked = !checked;
  529. $checkbox.prop('checked', checked).trigger('change');
  530. }
  531. if (checked) {
  532. $tr.addClass('marked');
  533. } else {
  534. $tr.removeClass('marked');
  535. }
  536. last_click_checked = checked;
  537. } else {
  538. // normal data table, just toggle class
  539. $tr.toggleClass('marked');
  540. last_click_checked = false;
  541. }
  542. // remember the last clicked row
  543. last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr) : -1;
  544. last_shift_clicked_row = -1;
  545. } else {
  546. // handle the shift click
  547. PMA_clearSelection();
  548. var start, end;
  549. // clear last shift click result
  550. if (last_shift_clicked_row >= 0) {
  551. if (last_shift_clicked_row >= last_clicked_row) {
  552. start = last_clicked_row;
  553. end = last_shift_clicked_row;
  554. } else {
  555. start = last_shift_clicked_row;
  556. end = last_clicked_row;
  557. }
  558. $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
  559. .slice(start, end + 1)
  560. .removeClass('marked')
  561. .find(':checkbox')
  562. .prop('checked', false)
  563. .trigger('change');
  564. }
  565. // handle new shift click
  566. var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr);
  567. if (curr_row >= last_clicked_row) {
  568. start = last_clicked_row;
  569. end = curr_row;
  570. } else {
  571. start = curr_row;
  572. end = last_clicked_row;
  573. }
  574. $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
  575. .slice(start, end + 1)
  576. .addClass('marked')
  577. .find(':checkbox')
  578. .prop('checked', true)
  579. .trigger('change');
  580. // remember the last shift clicked row
  581. last_shift_clicked_row = curr_row;
  582. }
  583. });
  584. addDateTimePicker();
  585. /**
  586. * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
  587. */
  588. if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
  589. $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
  590. }
  591. });
  592. /**
  593. * True if last click is to check a row.
  594. */
  595. var last_click_checked = false;
  596. /**
  597. * Zero-based index of last clicked row.
  598. * Used to handle the shift + click event in the code above.
  599. */
  600. var last_clicked_row = -1;
  601. /**
  602. * Zero-based index of last shift clicked row.
  603. */
  604. var last_shift_clicked_row = -1;
  605. /**
  606. * Row highlighting in horizontal mode (use "live"
  607. * so that it works also for pages reached via AJAX)
  608. */
  609. /*AJAX.registerOnload('functions.js', function () {
  610. $('tr.odd, tr.even').live('hover',function (event) {
  611. var $tr = $(this);
  612. $tr.toggleClass('hover',event.type=='mouseover');
  613. $tr.children().toggleClass('hover',event.type=='mouseover');
  614. });
  615. })*/
  616. /**
  617. * This array is used to remember mark status of rows in browse mode
  618. */
  619. var marked_row = [];
  620. /**
  621. * marks all rows and selects its first checkbox inside the given element
  622. * the given element is usaly a table or a div containing the table or tables
  623. *
  624. * @param container DOM element
  625. */
  626. function markAllRows(container_id)
  627. {
  628. $("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
  629. .trigger("change")
  630. .parents("tr").addClass("marked");
  631. return true;
  632. }
  633. /**
  634. * marks all rows and selects its first checkbox inside the given element
  635. * the given element is usaly a table or a div containing the table or tables
  636. *
  637. * @param container DOM element
  638. */
  639. function unMarkAllRows(container_id)
  640. {
  641. $("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
  642. .trigger("change")
  643. .parents("tr").removeClass("marked");
  644. return true;
  645. }
  646. /**
  647. * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
  648. *
  649. * @param string container_id the container id
  650. * @param boolean state new value for checkbox (true or false)
  651. * @return boolean always true
  652. */
  653. function setCheckboxes(container_id, state)
  654. {
  655. $("#" + container_id).find("input:checkbox").prop('checked', state);
  656. return true;
  657. } // end of the 'setCheckboxes()' function
  658. /**
  659. * Checks/unchecks all options of a <select> element
  660. *
  661. * @param string the form name
  662. * @param string the element name
  663. * @param boolean whether to check or to uncheck options
  664. *
  665. * @return boolean always true
  666. */
  667. function setSelectOptions(the_form, the_select, do_check)
  668. {
  669. $("form[name='" + the_form + "'] select[name='" + the_select + "']").find("option").prop('selected', do_check);
  670. return true;
  671. } // end of the 'setSelectOptions()' function
  672. /**
  673. * Sets current value for query box.
  674. */
  675. function setQuery(query)
  676. {
  677. if (codemirror_editor) {
  678. codemirror_editor.setValue(query);
  679. codemirror_editor.focus();
  680. } else {
  681. document.sqlform.sql_query.value = query;
  682. document.sqlform.sql_query.focus();
  683. }
  684. }
  685. /**
  686. * Create quick sql statements.
  687. *
  688. */
  689. function insertQuery(queryType)
  690. {
  691. if (queryType == "clear") {
  692. setQuery('');
  693. return;
  694. }
  695. var query = "";
  696. var myListBox = document.sqlform.dummy;
  697. var table = document.sqlform.table.value;
  698. if (myListBox.options.length > 0) {
  699. sql_box_locked = true;
  700. var chaineAj = "";
  701. var valDis = "";
  702. var editDis = "";
  703. var NbSelect = 0;
  704. for (var i = 0; i < myListBox.options.length; i++) {
  705. NbSelect++;
  706. if (NbSelect > 1) {
  707. chaineAj += ", ";
  708. valDis += ",";
  709. editDis += ",";
  710. }
  711. chaineAj += myListBox.options[i].value;
  712. valDis += "[value-" + NbSelect + "]";
  713. editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
  714. }
  715. if (queryType == "selectall") {
  716. query = "SELECT * FROM `" + table + "` WHERE 1";
  717. } else if (queryType == "select") {
  718. query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
  719. } else if (queryType == "insert") {
  720. query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
  721. } else if (queryType == "update") {
  722. query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
  723. } else if (queryType == "delete") {
  724. query = "DELETE FROM `" + table + "` WHERE 1";
  725. }
  726. setQuery(query);
  727. sql_box_locked = false;
  728. }
  729. }
  730. /**
  731. * Inserts multiple fields.
  732. *
  733. */
  734. function insertValueQuery()
  735. {
  736. var myQuery = document.sqlform.sql_query;
  737. var myListBox = document.sqlform.dummy;
  738. if (myListBox.options.length > 0) {
  739. sql_box_locked = true;
  740. var chaineAj = "";
  741. var NbSelect = 0;
  742. for (var i = 0; i < myListBox.options.length; i++) {
  743. if (myListBox.options[i].selected) {
  744. NbSelect++;
  745. if (NbSelect > 1) {
  746. chaineAj += ", ";
  747. }
  748. chaineAj += myListBox.options[i].value;
  749. }
  750. }
  751. /* CodeMirror support */
  752. if (codemirror_editor) {
  753. codemirror_editor.replaceSelection(chaineAj);
  754. //IE support
  755. } else if (document.selection) {
  756. myQuery.focus();
  757. var sel = document.selection.createRange();
  758. sel.text = chaineAj;
  759. document.sqlform.insert.focus();
  760. }
  761. //MOZILLA/NETSCAPE support
  762. else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
  763. var startPos = document.sqlform.sql_query.selectionStart;
  764. var endPos = document.sqlform.sql_query.selectionEnd;
  765. var chaineSql = document.sqlform.sql_query.value;
  766. myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
  767. } else {
  768. myQuery.value += chaineAj;
  769. }
  770. sql_box_locked = false;
  771. }
  772. }
  773. /**
  774. * Add a date/time picker to each element that needs it
  775. * (only when jquery-ui-timepicker-addon.js is loaded)
  776. */
  777. function addDateTimePicker() {
  778. if ($.timepicker !== undefined) {
  779. $('input.datefield, input.datetimefield').each(function () {
  780. no_decimals = $(this).parent().data('decimals');
  781. var showMillisec = false;
  782. var showMicrosec = false;
  783. var timeFormat = 'HH:mm:ss';
  784. // check for decimal places of seconds
  785. if (($(this).parent().data('decimals') > 0) && ($(this).parent().data('type').indexOf('time') != -1)){
  786. showMillisec = true;
  787. timeFormat = 'HH:mm:ss.lc';
  788. if ($(this).parent().data('decimals') > 3) {
  789. showMicrosec = true;
  790. }
  791. }
  792. PMA_addDatepicker($(this), {
  793. showMillisec: showMillisec,
  794. showMicrosec: showMicrosec,
  795. timeFormat: timeFormat,
  796. });
  797. })
  798. }
  799. }
  800. /**
  801. * Refresh/resize the WYSIWYG scratchboard
  802. */
  803. function refreshLayout()
  804. {
  805. var $elm = $('#pdflayout');
  806. var orientation = $('#orientation_opt').val();
  807. var paper = 'A4';
  808. if ($('#paper_opt').length == 1) {
  809. paper = $('#paper_opt').val();
  810. }
  811. var posa = 'y';
  812. var posb = 'x';
  813. if (orientation == 'P') {
  814. posa = 'x';
  815. posb = 'y';
  816. }
  817. $elm.css('width', pdfPaperSize(paper, posa) + 'px');
  818. $elm.css('height', pdfPaperSize(paper, posb) + 'px');
  819. }
  820. /**
  821. * Initializes positions of elements.
  822. */
  823. function TableDragInit() {
  824. $('.pdflayout_table').each(function () {
  825. var $this = $(this);
  826. var number = $this.data('number');
  827. var x = $('#c_table_' + number + '_x').val();
  828. var y = $('#c_table_' + number + '_y').val();
  829. $this.css('left', x + 'px');
  830. $this.css('top', y + 'px');
  831. /* Make elements draggable */
  832. $this.draggable({
  833. containment: "parent",
  834. drag: function (evt, ui) {
  835. var number = $this.data('number');
  836. $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10));
  837. $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10));
  838. }
  839. });
  840. });
  841. }
  842. /**
  843. * Resets drag and drop positions.
  844. */
  845. function resetDrag() {
  846. $('.pdflayout_table').each(function () {
  847. var $this = $(this);
  848. var x = $this.data('x');
  849. var y = $this.data('y');
  850. $this.css('left', x + 'px');
  851. $this.css('top', y + 'px');
  852. });
  853. }
  854. /**
  855. * User schema handlers.
  856. */
  857. $(function () {
  858. /* Move in scratchboard on manual change */
  859. $('.position-change').live('change', function () {
  860. var $this = $(this);
  861. var $elm = $('#table_' + $this.data('number'));
  862. $elm.css($this.data('axis'), $this.val() + 'px');
  863. });
  864. /* Refresh on paper size/orientation change */
  865. $('.paper-change').live('change', function () {
  866. var $elm = $('#pdflayout');
  867. if ($elm.css('visibility') == 'visible') {
  868. refreshLayout();
  869. TableDragInit();
  870. }
  871. });
  872. /* Show/hide the WYSIWYG scratchboard */
  873. $('#toggle-dragdrop').live('click', function () {
  874. var $elm = $('#pdflayout');
  875. if ($elm.css('visibility') == 'hidden') {
  876. refreshLayout();
  877. TableDragInit();
  878. $elm.css('visibility', 'visible');
  879. $elm.css('display', 'block');
  880. $('#showwysiwyg').val('1');
  881. } else {
  882. $elm.css('visibility', 'hidden');
  883. $elm.css('display', 'none');
  884. $('#showwysiwyg').val('0');
  885. }
  886. });
  887. /* Reset scratchboard */
  888. $('#reset-dragdrop').live('click', function () {
  889. resetDrag();
  890. });
  891. });
  892. /**
  893. * Returns paper sizes for a given format
  894. */
  895. function pdfPaperSize(format, axis)
  896. {
  897. switch (format.toUpperCase()) {
  898. case '4A0':
  899. if (axis == 'x') {
  900. return 4767.87;
  901. } else {
  902. return 6740.79;
  903. }
  904. break;
  905. case '2A0':
  906. if (axis == 'x') {
  907. return 3370.39;
  908. } else {
  909. return 4767.87;
  910. }
  911. break;
  912. case 'A0':
  913. if (axis == 'x') {
  914. return 2383.94;
  915. } else {
  916. return 3370.39;
  917. }
  918. break;
  919. case 'A1':
  920. if (axis == 'x') {
  921. return 1683.78;
  922. } else {
  923. return 2383.94;
  924. }
  925. break;
  926. case 'A2':
  927. if (axis == 'x') {
  928. return 1190.55;
  929. } else {
  930. return 1683.78;
  931. }
  932. break;
  933. case 'A3':
  934. if (axis == 'x') {
  935. return 841.89;
  936. } else {
  937. return 1190.55;
  938. }
  939. break;
  940. case 'A4':
  941. if (axis == 'x') {
  942. return 595.28;
  943. } else {
  944. return 841.89;
  945. }
  946. break;
  947. case 'A5':
  948. if (axis == 'x') {
  949. return 419.53;
  950. } else {
  951. return 595.28;
  952. }
  953. break;
  954. case 'A6':
  955. if (axis == 'x') {
  956. return 297.64;
  957. } else {
  958. return 419.53;
  959. }
  960. break;
  961. case 'A7':
  962. if (axis == 'x') {
  963. return 209.76;
  964. } else {
  965. return 297.64;
  966. }
  967. break;
  968. case 'A8':
  969. if (axis == 'x') {
  970. return 147.40;
  971. } else {
  972. return 209.76;
  973. }
  974. break;
  975. case 'A9':
  976. if (axis == 'x') {
  977. return 104.88;
  978. } else {
  979. return 147.40;
  980. }
  981. break;
  982. case 'A10':
  983. if (axis == 'x') {
  984. return 73.70;
  985. } else {
  986. return 104.88;
  987. }
  988. break;
  989. case 'B0':
  990. if (axis == 'x') {
  991. return 2834.65;
  992. } else {
  993. return 4008.19;
  994. }
  995. break;
  996. case 'B1':
  997. if (axis == 'x') {
  998. return 2004.09;
  999. } else {
  1000. return 2834.65;
  1001. }
  1002. break;
  1003. case 'B2':
  1004. if (axis == 'x') {
  1005. return 1417.32;
  1006. } else {
  1007. return 2004.09;
  1008. }
  1009. break;
  1010. case 'B3':
  1011. if (axis == 'x') {
  1012. return 1000.63;
  1013. } else {
  1014. return 1417.32;
  1015. }
  1016. break;
  1017. case 'B4':
  1018. if (axis == 'x') {
  1019. return 708.66;
  1020. } else {
  1021. return 1000.63;
  1022. }
  1023. break;
  1024. case 'B5':
  1025. if (axis == 'x') {
  1026. return 498.90;
  1027. } else {
  1028. return 708.66;
  1029. }
  1030. break;
  1031. case 'B6':
  1032. if (axis == 'x') {
  1033. return 354.33;
  1034. } else {
  1035. return 498.90;
  1036. }
  1037. break;
  1038. case 'B7':
  1039. if (axis == 'x') {
  1040. return 249.45;
  1041. } else {
  1042. return 354.33;
  1043. }
  1044. break;
  1045. case 'B8':
  1046. if (axis == 'x') {
  1047. return 175.75;
  1048. } else {
  1049. return 249.45;
  1050. }
  1051. break;
  1052. case 'B9':
  1053. if (axis == 'x') {
  1054. return 124.72;
  1055. } else {
  1056. return 175.75;
  1057. }
  1058. break;
  1059. case 'B10':
  1060. if (axis == 'x') {
  1061. return 87.87;
  1062. } else {
  1063. return 124.72;
  1064. }
  1065. break;
  1066. case 'C0':
  1067. if (axis == 'x') {
  1068. return 2599.37;
  1069. } else {
  1070. return 3676.54;
  1071. }
  1072. break;
  1073. case 'C1':
  1074. if (axis == 'x') {
  1075. return 1836.85;
  1076. } else {
  1077. return 2599.37;
  1078. }
  1079. break;
  1080. case 'C2':
  1081. if (axis == 'x') {
  1082. return 1298.27;
  1083. } else {
  1084. return 1836.85;
  1085. }
  1086. break;
  1087. case 'C3':
  1088. if (axis == 'x') {
  1089. return 918.43;
  1090. } else {
  1091. return 1298.27;
  1092. }
  1093. break;
  1094. case 'C4':
  1095. if (axis == 'x') {
  1096. return 649.13;
  1097. } else {
  1098. return 918.43;
  1099. }
  1100. break;
  1101. case 'C5':
  1102. if (axis == 'x') {
  1103. return 459.21;
  1104. } else {
  1105. return 649.13;
  1106. }
  1107. break;
  1108. case 'C6':
  1109. if (axis == 'x') {
  1110. return 323.15;
  1111. } else {
  1112. return 459.21;
  1113. }
  1114. break;
  1115. case 'C7':
  1116. if (axis == 'x') {
  1117. return 229.61;
  1118. } else {
  1119. return 323.15;
  1120. }
  1121. break;
  1122. case 'C8':
  1123. if (axis == 'x') {
  1124. return 161.57;
  1125. } else {
  1126. return 229.61;
  1127. }
  1128. break;
  1129. case 'C9':
  1130. if (axis == 'x') {
  1131. return 113.39;
  1132. } else {
  1133. return 161.57;
  1134. }
  1135. break;
  1136. case 'C10':
  1137. if (axis == 'x') {
  1138. return 79.37;
  1139. } else {
  1140. return 113.39;
  1141. }
  1142. break;
  1143. case 'RA0':
  1144. if (axis == 'x') {
  1145. return 2437.80;
  1146. } else {
  1147. return 3458.27;
  1148. }
  1149. break;
  1150. case 'RA1':
  1151. if (axis == 'x') {
  1152. return 1729.13;
  1153. } else {
  1154. return 2437.80;
  1155. }
  1156. break;
  1157. case 'RA2':
  1158. if (axis == 'x') {
  1159. return 1218.90;
  1160. } else {
  1161. return 1729.13;
  1162. }
  1163. break;
  1164. case 'RA3':
  1165. if (axis == 'x') {
  1166. return 864.57;
  1167. } else {
  1168. return 1218.90;
  1169. }
  1170. break;
  1171. case 'RA4':
  1172. if (axis == 'x') {
  1173. return 609.45;
  1174. } else {
  1175. return 864.57;
  1176. }
  1177. break;
  1178. case 'SRA0':
  1179. if (axis == 'x') {
  1180. return 2551.18;
  1181. } else {
  1182. return 3628.35;
  1183. }
  1184. break;
  1185. case 'SRA1':
  1186. if (axis == 'x') {
  1187. return 1814.17;
  1188. } else {
  1189. return 2551.18;
  1190. }
  1191. break;
  1192. case 'SRA2':
  1193. if (axis == 'x') {
  1194. return 1275.59;
  1195. } else {
  1196. return 1814.17;
  1197. }
  1198. break;
  1199. case 'SRA3':
  1200. if (axis == 'x') {
  1201. return 907.09;
  1202. } else {
  1203. return 1275.59;
  1204. }
  1205. break;
  1206. case 'SRA4':
  1207. if (axis == 'x') {
  1208. return 637.80;
  1209. } else {
  1210. return 907.09;
  1211. }
  1212. break;
  1213. case 'LETTER':
  1214. if (axis == 'x') {
  1215. return 612.00;
  1216. } else {
  1217. return 792.00;
  1218. }
  1219. break;
  1220. case 'LEGAL':
  1221. if (axis == 'x') {
  1222. return 612.00;
  1223. } else {
  1224. return 1008.00;
  1225. }
  1226. break;
  1227. case 'EXECUTIVE':
  1228. if (axis == 'x') {
  1229. return 521.86;
  1230. } else {
  1231. return 756.00;
  1232. }
  1233. break;
  1234. case 'FOLIO':
  1235. if (axis == 'x') {
  1236. return 612.00;
  1237. } else {
  1238. return 936.00;
  1239. }
  1240. break;
  1241. } // end switch
  1242. return 0;
  1243. }
  1244. /**
  1245. * Unbind all event handlers before tearing down a page
  1246. */
  1247. AJAX.registerTeardown('functions.js', function () {
  1248. $("a.inline_edit_sql").die('click');
  1249. $("input#sql_query_edit_save").die('click');
  1250. $("input#sql_query_edit_discard").die('click');
  1251. $('input.sqlbutton').unbind('click');
  1252. $("#export_type").unbind('change');
  1253. $('#sqlquery').unbind('keydown');
  1254. $('#sql_query_edit').unbind('keydown');
  1255. if (codemirror_inline_editor) {
  1256. // Copy the sql query to the text area to preserve it.
  1257. $('#sql_query_edit').text(codemirror_inline_editor.getValue());
  1258. $(codemirror_inline_editor.getWrapperElement()).unbind('keydown');
  1259. codemirror_inline_editor.toTextArea();
  1260. codemirror_inline_editor = false;
  1261. }
  1262. if (codemirror_editor) {
  1263. $(codemirror_editor.getWrapperElement()).unbind('keydown');
  1264. }
  1265. });
  1266. /**
  1267. * Jquery Coding for inline editing SQL_QUERY
  1268. */
  1269. AJAX.registerOnload('functions.js', function () {
  1270. // If we are coming back to the page by clicking forward button
  1271. // of the browser, bind the code mirror to inline query editor.
  1272. bindCodeMirrorToInlineEditor();
  1273. $("a.inline_edit_sql").live('click', function () {
  1274. if ($('#sql_query_edit').length) {
  1275. // An inline query editor is already open,
  1276. // we don't want another copy of it
  1277. return false;
  1278. }
  1279. var $form = $(this).prev('form');
  1280. var sql_query = $form.find("input[name='sql_query']").val();
  1281. var $inner_sql = $(this).parent().prev().find('code.sql');
  1282. var old_text = $inner_sql.html();
  1283. var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
  1284. new_content += "<input type=\"submit\" id=\"sql_query_edit_save\" class=\"button btnSave\" value=\"" + PMA_messages.strGo + "\"/>\n";
  1285. new_content += "<input type=\"button\" id=\"sql_query_edit_discard\" class=\"button btnDiscard\" value=\"" + PMA_messages.strCancel + "\"/>\n";
  1286. var $editor_area = $('div#inline_editor');
  1287. if ($editor_area.length === 0) {
  1288. $editor_area = $('<div id="inline_editor_outer"></div>');
  1289. $editor_area.insertBefore($inner_sql);
  1290. }
  1291. $editor_area.html(new_content);
  1292. $inner_sql.hide();
  1293. bindCodeMirrorToInlineEditor();
  1294. return false;
  1295. });
  1296. $("input#sql_query_edit_save").live('click', function () {
  1297. $(".success").hide();
  1298. //hide already existing success message
  1299. var sql_query;
  1300. if (codemirror_inline_editor) {
  1301. codemirror_inline_editor.save();
  1302. sql_query = codemirror_inline_editor.getValue();
  1303. } else {
  1304. sql_query = $(this).prev().val();
  1305. }
  1306. var $form = $("a.inline_edit_sql").prev('form');
  1307. var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
  1308. .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
  1309. .append($('<input/>', {type: 'hidden', name: 'show_query', value: 1}))
  1310. .append($('<input/>', {type: 'hidden', name: 'is_js_confirmed', value: 0}))
  1311. .append($('<input/>', {type: 'hidden', name: 'sql_query', value: sql_query}));
  1312. if (! checkSqlQuery($fake_form[0])) {
  1313. return false;
  1314. }
  1315. $fake_form.appendTo($('body')).submit();
  1316. });
  1317. $("input#sql_query_edit_discard").live('click', function () {
  1318. $('div#inline_editor_outer').siblings('code.sql').show();
  1319. $('div#inline_editor_outer').remove();
  1320. });
  1321. $('input.sqlbutton').click(function (evt) {
  1322. insertQuery(evt.target.id);
  1323. return false;
  1324. });
  1325. $("#export_type").change(function () {
  1326. if ($("#export_type").val() == 'svg') {
  1327. $("#show_grid_opt").prop("disabled", true);
  1328. $("#orientation_opt").prop("disabled", true);
  1329. $("#with_doc").prop("disabled", true);
  1330. $("#show_table_dim_opt").removeProp("disabled");
  1331. $("#all_tables_same_width").removeProp("disabled");
  1332. $("#paper_opt").removeProp("disabled");
  1333. $("#show_color_opt").removeProp("disabled");
  1334. //$(this).css("background-color","yellow");
  1335. } else if ($("#export_type").val() == 'dia') {
  1336. $("#show_grid_opt").prop("disabled", true);
  1337. $("#with_doc").prop("disabled", true);
  1338. $("#show_table_dim_opt").prop("disabled", true);
  1339. $("#all_tables_same_width").prop("disabled", true);
  1340. $("#paper_opt").removeProp("disabled");
  1341. $("#show_color_opt").removeProp("disabled");
  1342. $("#orientation_opt").removeProp("disabled");
  1343. } else if ($("#export_type").val() == 'eps') {
  1344. $("#show_grid_opt").prop("disabled", true);
  1345. $("#orientation_opt").removeProp("disabled");
  1346. $("#with_doc").prop("disabled", true);
  1347. $("#show_table_dim_opt").prop("disabled", true);
  1348. $("#all_tables_same_width").prop("disabled", true);
  1349. $("#paper_opt").prop("disabled", true);
  1350. $("#show_color_opt").prop("disabled", true);
  1351. } else if ($("#export_type").val() == 'pdf') {
  1352. $("#show_grid_opt").removeProp("disabled");
  1353. $("#orientation_opt").removeProp("disabled");
  1354. $("#with_doc").removeProp("disabled");
  1355. $("#show_table_dim_opt").removeProp("disabled");
  1356. $("#all_tables_same_width").removeProp("disabled");
  1357. $("#paper_opt").removeProp("disabled");
  1358. $("#show_color_opt").removeProp("disabled");
  1359. } else {
  1360. // nothing
  1361. }
  1362. });
  1363. if ($('#input_username')) {
  1364. if ($('#input_username').val() === '') {
  1365. $('#input_username').focus();
  1366. } else {
  1367. $('#input_password').focus();
  1368. }
  1369. }
  1370. });
  1371. /**
  1372. * Binds the CodeMirror to the text area used to inline edit a query.
  1373. */
  1374. function bindCodeMirrorToInlineEditor() {
  1375. var $inline_editor = $('#sql_query_edit');
  1376. if ($inline_editor.length > 0) {
  1377. if (typeof CodeMirror !== 'undefined') {
  1378. var height = $('#sql_query_edit').css('height');
  1379. codemirror_inline_editor = CodeMirror.fromTextArea($inline_editor[0], {
  1380. lineNumbers: true,
  1381. matchBrackets: true,
  1382. indentUnit: 4,
  1383. mode: "text/x-mysql",
  1384. lineWrapping: true
  1385. });
  1386. codemirror_inline_editor.getScrollerElement().style.height = height;
  1387. codemirror_inline_editor.refresh();
  1388. codemirror_inline_editor.focus();
  1389. $(codemirror_inline_editor.getWrapperElement()).bind(
  1390. 'keydown',
  1391. catchKeypressesFromSqlTextboxes
  1392. );
  1393. } else {
  1394. $inline_editor.focus().bind(
  1395. 'keydown',
  1396. catchKeypressesFromSqlTextboxes
  1397. );
  1398. }
  1399. }
  1400. }
  1401. function catchKeypressesFromSqlTextboxes(event) {
  1402. // ctrl-enter is 10 in chrome and ie, but 13 in ff
  1403. if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
  1404. if ($('#sql_query_edit').length > 0) {
  1405. $("#sql_query_edit_save").trigger('click');
  1406. } else if ($('#sqlquery').length > 0) {
  1407. $("#button_submit_query").trigger('click');
  1408. }
  1409. }
  1410. }
  1411. /**
  1412. * Adds doc link to single highlighted SQL element
  1413. */
  1414. function PMA_doc_add($elm, params)
  1415. {
  1416. var url = $.sprintf(
  1417. mysql_doc_template,
  1418. params[0]
  1419. );
  1420. if (params.length > 1) {
  1421. url += '#' + params[1];
  1422. }
  1423. var content = $elm.text();
  1424. $elm.text('');
  1425. $elm.append('<a target="mysql_doc" class="cm-sql-doc" href="' + url + '">' + content + '</a>');
  1426. }
  1427. /**
  1428. * Generates doc links for keywords inside highlighted SQL
  1429. */
  1430. function PMA_doc_keyword(idx, elm)
  1431. {
  1432. var $elm = $(elm);
  1433. /* Skip already processed ones */
  1434. if ($elm.find('a').length > 0) {
  1435. return;
  1436. }
  1437. var keyword = $elm.text().toUpperCase();
  1438. var $next = $elm.next('.cm-keyword');
  1439. if ($next) {
  1440. var next_keyword = $next.text().toUpperCase();
  1441. var full = keyword + ' ' + next_keyword;
  1442. var $next2 = $next.next('.cm-keyword');
  1443. if ($next2) {
  1444. var next2_keyword = $next2.text().toUpperCase();
  1445. var full2 = full + ' ' + next2_keyword;
  1446. if (full2 in mysql_doc_keyword) {
  1447. PMA_doc_add($elm, mysql_doc_keyword[full2]);
  1448. PMA_doc_add($next, mysql_doc_keyword[full2]);
  1449. PMA_doc_add($next2, mysql_doc_keyword[full2]);
  1450. return;
  1451. }
  1452. }
  1453. if (full in mysql_doc_keyword) {
  1454. PMA_doc_add($elm, mysql_doc_keyword[full]);
  1455. PMA_doc_add($next, mysql_doc_keyword[full]);
  1456. return;
  1457. }
  1458. }
  1459. if (keyword in mysql_doc_keyword) {
  1460. PMA_doc_add($elm, mysql_doc_keyword[keyword]);
  1461. }
  1462. }
  1463. /**
  1464. * Generates doc links for builtins inside highlighted SQL
  1465. */
  1466. function PMA_doc_builtin(idx, elm)
  1467. {
  1468. var $elm = $(elm);
  1469. var builtin = $elm.text().toUpperCase();
  1470. if (builtin in mysql_doc_builtin) {
  1471. PMA_doc_add($elm, mysql_doc_builtin[builtin]);
  1472. }
  1473. }
  1474. /**
  1475. * Higlights SQL using CodeMirror.
  1476. */
  1477. function PMA_highlightSQL(base)
  1478. {
  1479. var $elm = base.find('code.sql');
  1480. $elm.each(function () {
  1481. var $sql = $(this);
  1482. var $pre = $sql.find('pre');
  1483. /* We only care about visible elements to avoid double processing */
  1484. if ($pre.is(":visible")) {
  1485. var $highlight = $('<div class="sql-highlight cm-s-default"></div>');
  1486. $sql.append($highlight);
  1487. if (typeof CodeMirror != 'undefined') {
  1488. CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]);
  1489. $pre.hide();
  1490. $highlight.find('.cm-keyword').each(PMA_doc_keyword);
  1491. $highlight.find('.cm-builtin').each(PMA_doc_builtin);
  1492. }
  1493. }
  1494. });
  1495. }
  1496. /**
  1497. * Show a message on the top of the page for an Ajax request
  1498. *
  1499. * Sample usage:
  1500. *
  1501. * 1) var $msg = PMA_ajaxShowMessage();
  1502. * This will show a message that reads "Loading...". Such a message will not
  1503. * disappear automatically and cannot be dismissed by the user. To remove this
  1504. * message either the PMA_ajaxRemoveMessage($msg) function must be called or
  1505. * another message must be show with PMA_ajaxShowMessage() function.
  1506. *
  1507. * 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  1508. * This is a special case. The behaviour is same as above,
  1509. * just with a different message
  1510. *
  1511. * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
  1512. * This will show a message that will disappear automatically and it can also
  1513. * be dismissed by the user.
  1514. *
  1515. * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
  1516. * This will show a message that will not disappear automatically, but it
  1517. * can be dismissed by the user after he has finished reading it.
  1518. *
  1519. * @param string message string containing the message to be shown.
  1520. * optional, defaults to 'Loading...'
  1521. * @param mixed timeout number of milliseconds for the message to be visible
  1522. * optional, defaults to 5000. If set to 'false', the
  1523. * notification will never disappear
  1524. * @return jQuery object jQuery Element that holds the message div
  1525. * this object can be passed to PMA_ajaxRemoveMessage()
  1526. * to remove the notification
  1527. */
  1528. function PMA_ajaxShowMessage(message, timeout)
  1529. {
  1530. /**
  1531. * @var self_closing Whether the notification will automatically disappear
  1532. */
  1533. var self_closing = true;
  1534. /**
  1535. * @var dismissable Whether the user will be able to remove
  1536. * the notification by clicking on it
  1537. */
  1538. var dismissable = true;
  1539. // Handle the case when a empty data.message is passed.
  1540. // We don't want the empty message
  1541. if (message === '') {
  1542. return true;
  1543. } else if (! message) {
  1544. // If the message is undefined, show the default
  1545. message = PMA_messages.strLoading;
  1546. dismissable = false;
  1547. self_closing = false;
  1548. } else if (message == PMA_messages.strProcessingRequest) {
  1549. // This is another case where the message should not disappear
  1550. dismissable = false;
  1551. self_closing = false;
  1552. }
  1553. // Figure out whether (or after how long) to remove the notification
  1554. if (timeout === undefined) {
  1555. timeout = 5000;
  1556. } else if (timeout === false) {
  1557. self_closing = false;
  1558. }
  1559. // Create a parent element for the AJAX messages, if necessary
  1560. if ($('#loading_parent').length === 0) {
  1561. $('<div id="loading_parent"></div>')
  1562. .prependTo("body");
  1563. }
  1564. // Update message count to create distinct message elements every time
  1565. ajax_message_count++;
  1566. // Remove all old messages, if any
  1567. $("span.ajax_notification[id^=ajax_message_num]").remove();
  1568. /**
  1569. * @var $retval a jQuery object containing the reference
  1570. * to the created AJAX message
  1571. */
  1572. var $retval = $(
  1573. '<span class="ajax_notification" id="ajax_message_num_' +
  1574. ajax_message_count +
  1575. '"></span>'
  1576. )
  1577. .hide()
  1578. .appendTo("#loading_parent")
  1579. .html(message)
  1580. .show();
  1581. // If the notification is self-closing we should create a callback to remove it
  1582. if (self_closing) {
  1583. $retval
  1584. .delay(timeout)
  1585. .fadeOut('medium', function () {
  1586. if ($(this).is(':data(tooltip)')) {
  1587. $(this).tooltip('destroy');
  1588. }
  1589. // Remove the notification
  1590. $(this).remove();
  1591. });
  1592. }
  1593. // If the notification is dismissable we need to add the relevant class to it
  1594. // and add a tooltip so that the users know that it can be removed
  1595. if (dismissable) {
  1596. $retval.addClass('dismissable').css('cursor', 'pointer');
  1597. /**
  1598. * Add a tooltip to the notification to let the user know that (s)he
  1599. * can dismiss the ajax notification by clicking on it.
  1600. */
  1601. PMA_tooltip(
  1602. $retval,
  1603. 'span',
  1604. PMA_messages.strDismiss
  1605. );
  1606. }
  1607. PMA_highlightSQL($retval);
  1608. return $retval;
  1609. }
  1610. /**
  1611. * Removes the message shown for an Ajax operation when it's completed
  1612. *
  1613. * @param jQuery object jQuery Element that holds the notification
  1614. *
  1615. * @return nothing
  1616. */
  1617. function PMA_ajaxRemoveMessage($this_msgbox)
  1618. {
  1619. if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
  1620. $this_msgbox
  1621. .stop(true, true)
  1622. .fadeOut('medium');
  1623. if ($this_msgbox.is(':data(tooltip)')) {
  1624. $this_msgbox.tooltip('destroy');
  1625. } else {
  1626. $this_msgbox.remove();
  1627. }
  1628. }
  1629. }
  1630. // This event only need to be fired once after the initial page load
  1631. $(function () {
  1632. /**
  1633. * Allows the user to dismiss a notification
  1634. * created with PMA_ajaxShowMessage()
  1635. */
  1636. $('span.ajax_notification.dismissable').live('click', function () {
  1637. PMA_ajaxRemoveMessage($(this));
  1638. });
  1639. /**
  1640. * The below two functions hide the "Dismiss notification" tooltip when a user
  1641. * is hovering a link or button that is inside an ajax message
  1642. */
  1643. $('span.ajax_notification a, span.ajax_notification button, span.ajax_notification input')
  1644. .live('mouseover', function () {
  1645. if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
  1646. $(this).parents('span.ajax_notification').tooltip('disable');
  1647. }
  1648. })
  1649. .live('mouseout', function () {
  1650. if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
  1651. $(this).parents('span.ajax_notification').tooltip('enable');
  1652. }
  1653. });
  1654. });
  1655. /**
  1656. * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
  1657. */
  1658. function PMA_showNoticeForEnum(selectElement)
  1659. {
  1660. var enum_notice_id = selectElement.attr("id").split("_")[1];
  1661. enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2], 10) + 1);
  1662. var selectedType = selectElement.val();
  1663. if (selectedType == "ENUM" || selectedType == "SET") {
  1664. $("p#enum_notice_" + enum_notice_id).show();
  1665. } else {
  1666. $("p#enum_notice_" + enum_notice_id).hide();
  1667. }
  1668. }
  1669. /*
  1670. * Creates a Profiling Chart with jqplot. Used in sql.js
  1671. * and in server_status_monitor.js
  1672. */
  1673. function PMA_createProfilingChartJqplot(target, data)
  1674. {
  1675. return $.jqplot(target, [data],
  1676. {
  1677. seriesDefaults: {
  1678. renderer: $.jqplot.PieRenderer,
  1679. rendererOptions: {
  1680. showDataLabels: true
  1681. }
  1682. },
  1683. highlighter: {
  1684. show: true,
  1685. tooltipLocation: 'se',
  1686. sizeAdjust: 0,
  1687. tooltipAxes: 'pieref',
  1688. useAxesFormatters: false,
  1689. formatString: '%s, %.9Ps'
  1690. },
  1691. legend: {
  1692. show: true,
  1693. location: 'e'
  1694. },
  1695. // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
  1696. seriesColors: [
  1697. '#fce94f',
  1698. '#fcaf3e',
  1699. '#e9b96e',
  1700. '#8ae234',
  1701. '#729fcf',
  1702. '#ad7fa8',
  1703. '#ef2929',
  1704. '#eeeeec',
  1705. '#888a85',
  1706. '#c4a000',
  1707. '#ce5c00',
  1708. '#8f5902',
  1709. '#4e9a06',
  1710. '#204a87',
  1711. '#5c3566',
  1712. '#a40000',
  1713. '#babdb6',
  1714. '#2e3436'
  1715. ]
  1716. }
  1717. );
  1718. }
  1719. /**
  1720. * Formats a profiling duration nicely (in us and ms time).
  1721. * Used in server_status_monitor.js
  1722. *
  1723. * @param integer Number to be formatted, should be in the range of microsecond to second
  1724. * @param integer Accuracy, how many numbers right to the comma should be
  1725. * @return string The formatted number
  1726. */
  1727. function PMA_prettyProfilingNum(num, acc)
  1728. {
  1729. if (!acc) {
  1730. acc = 2;
  1731. }
  1732. acc = Math.pow(10, acc);
  1733. if (num * 1000 < 0.1) {
  1734. num = Math.round(acc * (num * 1000 * 1000)) / acc + 'Âľ';
  1735. } else if (num < 0.1) {
  1736. num = Math.round(acc * (num * 1000)) / acc + 'm';
  1737. } else {
  1738. num = Math.round(acc * num) / acc;
  1739. }
  1740. return num + 's';
  1741. }
  1742. /**
  1743. * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
  1744. *
  1745. * @param string Query to be formatted
  1746. * @return string The formatted query
  1747. */
  1748. function PMA_SQLPrettyPrint(string)
  1749. {
  1750. if (typeof CodeMirror == 'undefined') {
  1751. return string;
  1752. }
  1753. var mode = CodeMirror.getMode({}, "text/x-mysql");
  1754. var stream = new CodeMirror.StringStream(string);
  1755. var state = mode.startState();
  1756. var token, tokens = [];
  1757. var output = '';
  1758. var tabs = function (cnt) {
  1759. var ret = '';
  1760. for (var i = 0; i < 4 * cnt; i++) {
  1761. ret += " ";
  1762. }
  1763. return ret;
  1764. };
  1765. // "root-level" statements
  1766. var statements = {
  1767. 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
  1768. 'update': ['update', 'set', 'where'],
  1769. 'insert into': ['insert into', 'values']
  1770. };
  1771. // don't put spaces before these tokens
  1772. var spaceExceptionsBefore = {';': true, ',': true, '.': true, '(': true};
  1773. // don't put spaces after these tokens
  1774. var spaceExceptionsAfter = {'.': true};
  1775. // Populate tokens array
  1776. var str = '';
  1777. while (! stream.eol()) {
  1778. stream.start = stream.pos;
  1779. token = mode.token(stream, state);
  1780. if (token !== null) {
  1781. tokens.push([token, stream.current().toLowerCase()]);
  1782. }
  1783. }
  1784. var currentStatement = tokens[0][1];
  1785. if (! statements[currentStatement]) {
  1786. return string;
  1787. }
  1788. // Holds all currently opened code blocks (statement, function or generic)
  1789. var blockStack = [];
  1790. // Holds the type of block from last iteration (the current is in blockStack[0])
  1791. var previousBlock;
  1792. // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
  1793. var newBlock, endBlock;
  1794. // How much to indent in the current line
  1795. var indentLevel = 0;
  1796. // Holds the "root-level" statements
  1797. var statementPart, lastStatementPart = statements[currentStatement][0];
  1798. blockStack.unshift('statement');
  1799. // Iterate through every token and format accordingly
  1800. for (var i = 0; i < tokens.length; i++) {
  1801. previousBlock = blockStack[0];
  1802. // New block => push to stack
  1803. if (tokens[i][1] == '(') {
  1804. if (i < tokens.length - 1 && tokens[i + 1][0] == 'statement-verb') {
  1805. blockStack.unshift(newBlock = 'statement');
  1806. } else if (i > 0 && tokens[i - 1][0] == 'builtin') {
  1807. blockStack.unshift(newBlock = 'function');
  1808. } else {
  1809. blockStack.unshift(newBlock = 'generic');
  1810. }
  1811. } else {
  1812. newBlock = null;
  1813. }
  1814. // Block end => pop from stack
  1815. if (tokens[i][1] == ')') {
  1816. endBlock = blockStack[0];
  1817. blockStack.shift();
  1818. } else {
  1819. endBlock = null;
  1820. }
  1821. // A subquery is starting
  1822. if (i > 0 && newBlock == 'statement') {
  1823. indentLevel++;
  1824. output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
  1825. currentStatement = tokens[i + 1][1];
  1826. i++;
  1827. continue;
  1828. }
  1829. // A subquery is ending
  1830. if (endBlock == 'statement' && indentLevel > 0) {
  1831. output += "\n" + tabs(indentLevel);
  1832. indentLevel--;
  1833. }
  1834. // One less indentation for statement parts (from, where, order by, etc.) and a newline
  1835. statementPart = statements[currentStatement].indexOf(tokens[i][1]);
  1836. if (statementPart != -1) {
  1837. if (i > 0) {
  1838. output += "\n";
  1839. }
  1840. output += tabs(indentLevel) + tokens[i][1].toUpperCase();
  1841. output += "\n" + tabs(indentLevel + 1);
  1842. lastStatementPart = tokens[i][1];
  1843. }
  1844. // Normal indentatin and spaces for everything else
  1845. else {
  1846. if (! spaceExceptionsBefore[tokens[i][1]] &&
  1847. ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
  1848. output.charAt(output.length - 1) != ' ') {
  1849. output += " ";
  1850. }
  1851. if (tokens[i][0] == 'keyword') {
  1852. output += tokens[i][1].toUpperCase();
  1853. } else {
  1854. output += tokens[i][1];
  1855. }
  1856. }
  1857. // split columns in select and 'update set' clauses, but only inside statements blocks
  1858. if ((lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set') &&
  1859. tokens[i][1] == ',' && blockStack[0] == 'statement') {
  1860. output += "\n" + tabs(indentLevel + 1);
  1861. }
  1862. // split conditions in where clauses, but only inside statements blocks
  1863. if (lastStatementPart == 'where' &&
  1864. (tokens[i][1] == 'and' || tokens[i][1] == 'or' || tokens[i][1] == 'xor')) {
  1865. if (blockStack[0] == 'statement') {
  1866. output += "\n" + tabs(indentLevel + 1);
  1867. }
  1868. // Todo: Also split and or blocks in newlines & identation++
  1869. //if (blockStack[0] == 'generic')
  1870. // output += ...
  1871. }
  1872. }
  1873. return output;
  1874. }
  1875. /**
  1876. * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
  1877. * return a jQuery object yet and hence cannot be chained
  1878. *
  1879. * @param string question
  1880. * @param string url URL to be passed to the callbackFn to make
  1881. * an Ajax call to
  1882. * @param function callbackFn callback to execute after user clicks on OK
  1883. */
  1884. jQuery.fn.PMA_confirm = function (question, url, callbackFn) {
  1885. var confirmState = PMA_commonParams.get('confirm');
  1886. // when the Confirm directive is set to false in config.inc.php
  1887. // and not changed in user prefs, confirmState is ""
  1888. // when it's unticked in user prefs, confirmState is 1
  1889. if (confirmState === "" || confirmState === "1") {
  1890. // user does not want to confirm
  1891. if ($.isFunction(callbackFn)) {
  1892. callbackFn.call(this, url);
  1893. return true;
  1894. }
  1895. }
  1896. if (PMA_messages.strDoYouReally === '') {
  1897. return true;
  1898. }
  1899. /**
  1900. * @var button_options Object that stores the options passed to jQueryUI
  1901. * dialog
  1902. */
  1903. var button_options = {};
  1904. button_options[PMA_messages.strOK] = function () {
  1905. $(this).dialog("close");
  1906. if ($.isFunction(callbackFn)) {
  1907. callbackFn.call(this, url);
  1908. }
  1909. };
  1910. button_options[PMA_messages.strCancel] = function () {
  1911. $(this).dialog("close");
  1912. };
  1913. $('<div/>', {'id': 'confirm_dialog'})
  1914. .prepend(question)
  1915. .dialog({
  1916. buttons: button_options,
  1917. close: function () {
  1918. $(this).remove();
  1919. },
  1920. modal: true
  1921. });
  1922. };
  1923. /**
  1924. * jQuery function to sort a table's body after a new row has been appended to it.
  1925. * Also fixes the even/odd classes of the table rows at the end.
  1926. *
  1927. * @param string text_selector string to select the sortKey's text
  1928. *
  1929. * @return jQuery Object for chaining purposes
  1930. */
  1931. jQuery.fn.PMA_sort_table = function (text_selector) {
  1932. return this.each(function () {
  1933. /**
  1934. * @var table_body Object referring to the table's <tbody> element
  1935. */
  1936. var table_body = $(this);
  1937. /**
  1938. * @var rows Object referring to the collection of rows in {@link table_body}
  1939. */
  1940. var rows = $(this).find('tr').get();
  1941. //get the text of the field that we will sort by
  1942. $.each(rows, function (index, row) {
  1943. row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
  1944. });
  1945. //get the sorted order
  1946. rows.sort(function (a, b) {
  1947. if (a.sortKey < b.sortKey) {
  1948. return -1;
  1949. }
  1950. if (a.sortKey > b.sortKey) {
  1951. return 1;
  1952. }
  1953. return 0;
  1954. });
  1955. //pull out each row from the table and then append it according to it's order
  1956. $.each(rows, function (index, row) {
  1957. $(table_body).append(row);
  1958. row.sortKey = null;
  1959. });
  1960. //Re-check the classes of each row
  1961. $(this).find('tr:odd')
  1962. .removeClass('even').addClass('odd')
  1963. .end()
  1964. .find('tr:even')
  1965. .removeClass('odd').addClass('even');
  1966. });
  1967. };
  1968. /**
  1969. * Unbind all event handlers before tearing down a page
  1970. */
  1971. AJAX.registerTeardown('functions.js', function () {
  1972. $("#create_table_form_minimal.ajax").die('submit');
  1973. $("form.create_table_form.ajax").die('submit');
  1974. $("form.create_table_form.ajax input[name=submit_num_fields]").die('click');
  1975. $("form.create_table_form.ajax input").die('keyup');
  1976. });
  1977. /**
  1978. * jQuery coding for 'Create Table'. Used on db_operations.php,
  1979. * db_structure.php and db_tracking.php (i.e., wherever
  1980. * libraries/display_create_table.lib.php is used)
  1981. *
  1982. * Attach Ajax Event handlers for Create Table
  1983. */
  1984. AJAX.registerOnload('functions.js', function () {
  1985. /**
  1986. * Attach event handler for submission of create table form (save)
  1987. */
  1988. $("form.create_table_form.ajax").live('submit', function (event) {
  1989. event.preventDefault();
  1990. /**
  1991. * @var the_form object referring to the create table form
  1992. */
  1993. var $form = $(this);
  1994. /*
  1995. * First validate the form; if there is a problem, avoid submitting it
  1996. *
  1997. * checkTableEditForm() needs a pure element and not a jQuery object,
  1998. * this is why we pass $form[0] as a parameter (the jQuery object
  1999. * is actually an array of DOM elements)
  2000. */
  2001. if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
  2002. PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2003. PMA_prepareForAjaxRequest($form);
  2004. //User wants to submit the form
  2005. $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
  2006. if (data.success === true) {
  2007. $('#properties_message')
  2008. .removeClass('error')
  2009. .html('');
  2010. PMA_ajaxShowMessage(data.message);
  2011. // Only if the create table dialog (distinct panel) exists
  2012. if ($("#create_table_dialog").length > 0) {
  2013. $("#create_table_dialog").dialog("close").remove();
  2014. }
  2015. $('#tableslistcontainer').before(data.formatted_sql);
  2016. /**
  2017. * @var tables_table Object referring to the <tbody> element that holds the list of tables
  2018. */
  2019. var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
  2020. // this is the first table created in this db
  2021. if (tables_table.length === 0) {
  2022. PMA_commonActions.refreshMain(
  2023. PMA_commonParams.get('opendb_url')
  2024. );
  2025. } else {
  2026. /**
  2027. * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
  2028. */
  2029. var curr_last_row = $(tables_table).find('tr:last');
  2030. /**
  2031. * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
  2032. */
  2033. var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
  2034. /**
  2035. * @var curr_last_row_index Index of {@link curr_last_row}
  2036. */
  2037. var curr_last_row_index = parseFloat(curr_last_row_index_string);
  2038. /**
  2039. * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
  2040. */
  2041. var new_last_row_index = curr_last_row_index + 1;
  2042. /**
  2043. * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
  2044. */
  2045. var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
  2046. data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
  2047. //append to table
  2048. $(data.new_table_string)
  2049. .appendTo(tables_table);
  2050. //Sort the table
  2051. $(tables_table).PMA_sort_table('th');
  2052. // Adjust summary row
  2053. PMA_adjustTotals();
  2054. }
  2055. //Refresh navigation as a new table has been added
  2056. PMA_reloadNavigation();
  2057. } else {
  2058. PMA_ajaxShowMessage(
  2059. '<div class="error">' + data.error + '</div>',
  2060. false
  2061. );
  2062. }
  2063. }); // end $.post()
  2064. } // end if (checkTableEditForm() )
  2065. }); // end create table form (save)
  2066. /**
  2067. * Attach event handler for create table form (add fields)
  2068. */
  2069. $("form.create_table_form.ajax input[name=submit_num_fields]").live('click', function (event) {
  2070. event.preventDefault();
  2071. /**
  2072. * @var the_form object referring to the create table form
  2073. */
  2074. var $form = $(this).closest('form');
  2075. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2076. PMA_prepareForAjaxRequest($form);
  2077. //User wants to add more fields to the table
  2078. $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=1", function (data) {
  2079. if (data.success) {
  2080. $("#page_content").html(data.message);
  2081. PMA_highlightSQL($('#page_content'));
  2082. PMA_verifyColumnsProperties();
  2083. PMA_ajaxRemoveMessage($msgbox);
  2084. } else {
  2085. PMA_ajaxShowMessage(data.error);
  2086. }
  2087. }); //end $.post()
  2088. }); // end create table form (add fields)
  2089. $("form.create_table_form.ajax input").live('keydown', function (event) {
  2090. if (event.keyCode == 13) {
  2091. event.preventDefault();
  2092. event.stopImmediatePropagation();
  2093. $(this)
  2094. .closest('form')
  2095. .append('<input type="hidden" name="do_save_data" value="1" />')
  2096. .submit();
  2097. }
  2098. });
  2099. });
  2100. /**
  2101. * Unbind all event handlers before tearing down a page
  2102. */
  2103. AJAX.registerTeardown('functions.js', function () {
  2104. $("#copyTable.ajax").die('submit');
  2105. $("#moveTableForm").die('submit');
  2106. $("#tableOptionsForm").die('submit');
  2107. $("#tbl_maintenance li a.maintain_action.ajax").die('click');
  2108. });
  2109. /**
  2110. * jQuery coding for 'Table operations'. Used on tbl_operations.php
  2111. * Attach Ajax Event handlers for Table operations
  2112. */
  2113. AJAX.registerOnload('functions.js', function () {
  2114. /**
  2115. *Ajax action for submitting the "Copy table"
  2116. **/
  2117. $("#copyTable.ajax").live('submit', function (event) {
  2118. event.preventDefault();
  2119. var $form = $(this);
  2120. PMA_prepareForAjaxRequest($form);
  2121. $.post($form.attr('action'), $form.serialize() + "&submit_copy=Go", function (data) {
  2122. if (data.success === true) {
  2123. if ($form.find("input[name='switch_to_new']").prop('checked')) {
  2124. PMA_commonParams.set(
  2125. 'db',
  2126. data.db
  2127. );
  2128. PMA_commonParams.set(
  2129. 'table',
  2130. $form.find("input[name='new_name']").val()
  2131. );
  2132. PMA_commonActions.refreshMain(false, function () {
  2133. PMA_ajaxShowMessage(data.message);
  2134. });
  2135. } else {
  2136. PMA_ajaxShowMessage(data.message);
  2137. }
  2138. // Refresh navigation when the table is copied
  2139. PMA_reloadNavigation();
  2140. } else {
  2141. PMA_ajaxShowMessage(data.error, false);
  2142. }
  2143. }); // end $.post()
  2144. });//end of copyTable ajax submit
  2145. /**
  2146. *Ajax action for submitting the "Move table"
  2147. */
  2148. $("#moveTableForm").live('submit', function (event) {
  2149. event.preventDefault();
  2150. var $form = $(this);
  2151. var db = $form.find('select[name=target_db]').val();
  2152. var tbl = $form.find('input[name=new_name]').val();
  2153. PMA_prepareForAjaxRequest($form);
  2154. $.post($form.attr('action'), $form.serialize() + "&submit_move=1", function (data) {
  2155. if (data.success === true) {
  2156. PMA_commonParams.set('db', db);
  2157. PMA_commonParams.set('table', tbl);
  2158. PMA_commonActions.refreshMain(false, function () {
  2159. PMA_ajaxShowMessage(data.message);
  2160. });
  2161. // Refresh navigation when the table is copied
  2162. PMA_reloadNavigation();
  2163. } else {
  2164. PMA_ajaxShowMessage(data.error, false);
  2165. }
  2166. }); // end $.post()
  2167. });
  2168. /**
  2169. * Ajax action for submitting the "Table options"
  2170. */
  2171. $("#tableOptionsForm").live('submit', function (event) {
  2172. event.preventDefault();
  2173. event.stopPropagation();
  2174. var $form = $(this);
  2175. var $tblNameField = $form.find('input[name=new_name]');
  2176. if ($tblNameField.val() !== $tblNameField[0].defaultValue) {
  2177. // reload page and navigation if the table has been renamed
  2178. PMA_prepareForAjaxRequest($form);
  2179. var tbl = $tblNameField.val();
  2180. $.post($form.attr('action'), $form.serialize(), function (data) {
  2181. if (data.success === true) {
  2182. PMA_commonParams.set('table', tbl);
  2183. PMA_commonActions.refreshMain(false, function () {
  2184. $('#page_content').html(data.message);
  2185. PMA_highlightSQL($('#page_content'));
  2186. });
  2187. } else {
  2188. PMA_ajaxShowMessage(data.error, false);
  2189. }
  2190. }); // end $.post()
  2191. } else {
  2192. $form.removeClass('ajax').submit().addClass('ajax');
  2193. }
  2194. });
  2195. /**
  2196. *Ajax events for actions in the "Table maintenance"
  2197. **/
  2198. $("#tbl_maintenance li a.maintain_action.ajax").live('click', function (event) {
  2199. event.preventDefault();
  2200. if ($("#sqlqueryresults").length !== 0) {
  2201. $("#sqlqueryresults").remove();
  2202. }
  2203. if ($("#result_query").length !== 0) {
  2204. $("#result_query").remove();
  2205. }
  2206. //variables which stores the common attributes
  2207. $.post($(this).attr('href'), { ajax_request: 1 }, function (data) {
  2208. function scrollToTop() {
  2209. $('html, body').animate({ scrollTop: 0 });
  2210. }
  2211. if (data.success === true && data.sql_query !== undefined) {
  2212. PMA_ajaxShowMessage(data.message);
  2213. $("<div id='sqlqueryresults' class='ajax'></div>").prependTo("#page_content");
  2214. $("#sqlqueryresults").html(data.sql_query);
  2215. PMA_highlightSQL($('#page_content'));
  2216. scrollToTop();
  2217. } else if (data.success === true) {
  2218. var $temp_div = $("<div id='temp_div'></div>");
  2219. $temp_div.html(data.message);
  2220. var $success = $temp_div.find("#result_query .success");
  2221. PMA_ajaxShowMessage($success);
  2222. $("<div id='sqlqueryresults' class='ajax'></div>").prependTo("#page_content");
  2223. $("#sqlqueryresults").html(data.message);
  2224. PMA_highlightSQL($('#page_content'));
  2225. PMA_init_slider();
  2226. $("#sqlqueryresults").children("fieldset,br").remove();
  2227. scrollToTop();
  2228. } else {
  2229. var $temp_div = $("<div id='temp_div'></div>");
  2230. $temp_div.html(data.error);
  2231. var $error = $temp_div.find("code").addClass("error");
  2232. PMA_ajaxShowMessage($error, false);
  2233. }
  2234. }); // end $.post()
  2235. });//end of table maintanance ajax click
  2236. }); //end $(document).ready for 'Table operations'
  2237. /**
  2238. * Unbind all event handlers before tearing down a page
  2239. */
  2240. AJAX.registerTeardown('functions.js', function () {
  2241. $("#drop_db_anchor.ajax").die('click');
  2242. });
  2243. /**
  2244. * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
  2245. * as it was also required on db_create.php
  2246. */
  2247. AJAX.registerOnload('functions.js', function () {
  2248. $("#drop_db_anchor.ajax").live('click', function (event) {
  2249. event.preventDefault();
  2250. /**
  2251. * @var question String containing the question to be asked for confirmation
  2252. */
  2253. var question = PMA_messages.strDropDatabaseStrongWarning + ' ';
  2254. question += $.sprintf(
  2255. PMA_messages.strDoYouReally,
  2256. 'DROP DATABASE ' + escapeHtml(PMA_commonParams.get('db'))
  2257. );
  2258. $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
  2259. PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2260. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
  2261. if (data.success) {
  2262. //Database deleted successfully, refresh both the frames
  2263. PMA_reloadNavigation();
  2264. PMA_commonParams.set('db', '');
  2265. PMA_commonActions.refreshMain(
  2266. 'server_databases.php',
  2267. function () {
  2268. PMA_ajaxShowMessage(data.message);
  2269. }
  2270. );
  2271. } else {
  2272. PMA_ajaxShowMessage(data.error, false);
  2273. }
  2274. });
  2275. });
  2276. });
  2277. }); // end of $() for Drop Database
  2278. /**
  2279. * Validates the password field in a form
  2280. *
  2281. * @see PMA_messages.strPasswordEmpty
  2282. * @see PMA_messages.strPasswordNotSame
  2283. * @param object $the_form The form to be validated
  2284. * @return bool
  2285. */
  2286. function PMA_checkPassword($the_form)
  2287. {
  2288. // Did the user select 'no password'?
  2289. if ($the_form.find('#nopass_1').is(':checked')) {
  2290. return true;
  2291. } else {
  2292. var $pred = $the_form.find('#select_pred_password');
  2293. if ($pred.length && ($pred.val() == 'none' || $pred.val() == 'keep')) {
  2294. return true;
  2295. }
  2296. }
  2297. var $password = $the_form.find('input[name=pma_pw]');
  2298. var $password_repeat = $the_form.find('input[name=pma_pw2]');
  2299. var alert_msg = false;
  2300. if ($password.val() === '') {
  2301. alert_msg = PMA_messages.strPasswordEmpty;
  2302. } else if ($password.val() != $password_repeat.val()) {
  2303. alert_msg = PMA_messages.strPasswordNotSame;
  2304. }
  2305. if (alert_msg) {
  2306. alert(alert_msg);
  2307. $password.val('');
  2308. $password_repeat.val('');
  2309. $password.focus();
  2310. return false;
  2311. }
  2312. return true;
  2313. }
  2314. /**
  2315. * Unbind all event handlers before tearing down a page
  2316. */
  2317. AJAX.registerTeardown('functions.js', function () {
  2318. $('#change_password_anchor.ajax').die('click');
  2319. });
  2320. /**
  2321. * Attach Ajax event handlers for 'Change Password' on index.php
  2322. */
  2323. AJAX.registerOnload('functions.js', function () {
  2324. /**
  2325. * Attach Ajax event handler on the change password anchor
  2326. */
  2327. $('#change_password_anchor.ajax').live('click', function (event) {
  2328. event.preventDefault();
  2329. var $msgbox = PMA_ajaxShowMessage();
  2330. /**
  2331. * @var button_options Object containing options to be passed to jQueryUI's dialog
  2332. */
  2333. var button_options = {};
  2334. button_options[PMA_messages.strGo] = function () {
  2335. event.preventDefault();
  2336. /**
  2337. * @var $the_form Object referring to the change password form
  2338. */
  2339. var $the_form = $("#change_password_form");
  2340. if (! PMA_checkPassword($the_form)) {
  2341. return false;
  2342. }
  2343. /**
  2344. * @var this_value String containing the value of the submit button.
  2345. * Need to append this for the change password form on Server Privileges
  2346. * page to work
  2347. */
  2348. var this_value = $(this).val();
  2349. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2350. $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
  2351. $.post($the_form.attr('action'), $the_form.serialize() + '&change_pw=' + this_value, function (data) {
  2352. if (data.success === true) {
  2353. $("#page_content").prepend(data.message);
  2354. PMA_highlightSQL($('#page_content'));
  2355. $("#change_password_dialog").hide().remove();
  2356. $("#edit_user_dialog").dialog("close").remove();
  2357. PMA_ajaxRemoveMessage($msgbox);
  2358. }
  2359. else {
  2360. PMA_ajaxShowMessage(data.error, false);
  2361. }
  2362. }); // end $.post()
  2363. };
  2364. button_options[PMA_messages.strCancel] = function () {
  2365. $(this).dialog('close');
  2366. };
  2367. $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
  2368. if (data.success) {
  2369. $('<div id="change_password_dialog"></div>')
  2370. .dialog({
  2371. title: PMA_messages.strChangePassword,
  2372. width: 600,
  2373. close: function (ev, ui) {
  2374. $(this).remove();
  2375. },
  2376. buttons : button_options,
  2377. modal: true
  2378. })
  2379. .append(data.message);
  2380. // for this dialog, we remove the fieldset wrapping due to double headings
  2381. $("fieldset#fieldset_change_password")
  2382. .find("legend").remove().end()
  2383. .find("table.noclick").unwrap().addClass("some-margin")
  2384. .find("input#text_pma_pw").focus();
  2385. displayPasswordGenerateButton();
  2386. $('#fieldset_change_password_footer').hide();
  2387. PMA_ajaxRemoveMessage($msgbox);
  2388. $('#change_password_form').bind('submit', function (e) {
  2389. e.preventDefault();
  2390. $(this)
  2391. .closest('.ui-dialog')
  2392. .find('.ui-dialog-buttonpane .ui-button')
  2393. .first()
  2394. .click();
  2395. });
  2396. } else {
  2397. PMA_ajaxShowMessage(data.error, false);
  2398. }
  2399. }); // end $.get()
  2400. }); // end handler for change password anchor
  2401. }); // end $() for Change Password
  2402. /**
  2403. * Unbind all event handlers before tearing down a page
  2404. */
  2405. AJAX.registerTeardown('functions.js', function () {
  2406. $("select.column_type").die('change');
  2407. $("select.default_type").die('change');
  2408. $('input.allow_null').die('change');
  2409. });
  2410. /**
  2411. * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
  2412. * the page loads and when the selected data type changes
  2413. */
  2414. AJAX.registerOnload('functions.js', function () {
  2415. // is called here for normal page loads and also when opening
  2416. // the Create table dialog
  2417. PMA_verifyColumnsProperties();
  2418. //
  2419. // needs live() to work also in the Create Table dialog
  2420. $("select.column_type").live('change', function () {
  2421. PMA_showNoticeForEnum($(this));
  2422. });
  2423. $("select.default_type").live('change', function () {
  2424. PMA_hideShowDefaultValue($(this));
  2425. });
  2426. $('input.allow_null').live('change', function () {
  2427. PMA_validateDefaultValue($(this));
  2428. });
  2429. });
  2430. function PMA_verifyColumnsProperties()
  2431. {
  2432. $("select.column_type").each(function () {
  2433. PMA_showNoticeForEnum($(this));
  2434. });
  2435. $("select.default_type").each(function () {
  2436. PMA_hideShowDefaultValue($(this));
  2437. });
  2438. }
  2439. /**
  2440. * Hides/shows the default value input field, depending on the default type
  2441. * Ticks the NULL checkbox if NULL is chosen as default value.
  2442. */
  2443. function PMA_hideShowDefaultValue($default_type)
  2444. {
  2445. if ($default_type.val() == 'USER_DEFINED') {
  2446. $default_type.siblings('.default_value').show().focus();
  2447. } else {
  2448. $default_type.siblings('.default_value').hide();
  2449. if ($default_type.val() == 'NULL') {
  2450. var $null_checkbox = $default_type.closest('tr').find('.allow_null');
  2451. $null_checkbox.prop('checked', true);
  2452. }
  2453. }
  2454. }
  2455. /**
  2456. * If the column does not allow NULL values, makes sure that default is not NULL
  2457. */
  2458. function PMA_validateDefaultValue($null_checkbox)
  2459. {
  2460. if (! $null_checkbox.prop('checked')) {
  2461. var $default = $null_checkbox.closest('tr').find('.default_type');
  2462. if ($default.val() == 'NULL') {
  2463. $default.val('NONE');
  2464. }
  2465. }
  2466. }
  2467. /**
  2468. * Unbind all event handlers before tearing down a page
  2469. */
  2470. AJAX.registerTeardown('functions.js', function () {
  2471. $("a.open_enum_editor").die('click');
  2472. $("input.add_value").die('click');
  2473. $("#enum_editor td.drop").die('click');
  2474. });
  2475. /**
  2476. * @var $enum_editor_dialog An object that points to the jQuery
  2477. * dialog of the ENUM/SET editor
  2478. */
  2479. var $enum_editor_dialog = null;
  2480. /**
  2481. * Opens the ENUM/SET editor and controls its functions
  2482. */
  2483. AJAX.registerOnload('functions.js', function () {
  2484. $("a.open_enum_editor").live('click', function () {
  2485. // Get the name of the column that is being edited
  2486. var colname = $(this).closest('tr').find('input:first').val();
  2487. var title;
  2488. var i;
  2489. // And use it to make up a title for the page
  2490. if (colname.length < 1) {
  2491. title = PMA_messages.enum_newColumnVals;
  2492. } else {
  2493. title = PMA_messages.enum_columnVals.replace(
  2494. /%s/,
  2495. '"' + decodeURIComponent(colname) + '"'
  2496. );
  2497. }
  2498. // Get the values as a string
  2499. var inputstring = $(this)
  2500. .closest('td')
  2501. .find("input")
  2502. .val();
  2503. // Escape html entities
  2504. inputstring = $('<div/>')
  2505. .text(inputstring)
  2506. .html();
  2507. // Parse the values, escaping quotes and
  2508. // slashes on the fly, into an array
  2509. var values = [];
  2510. var in_string = false;
  2511. var curr, next, buffer = '';
  2512. for (i = 0; i < inputstring.length; i++) {
  2513. curr = inputstring.charAt(i);
  2514. next = i == inputstring.length ? '' : inputstring.charAt(i + 1);
  2515. if (! in_string && curr == "'") {
  2516. in_string = true;
  2517. } else if (in_string && curr == "\\" && next == "\\") {
  2518. buffer += "&#92;";
  2519. i++;
  2520. } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
  2521. buffer += "&#39;";
  2522. i++;
  2523. } else if (in_string && curr == "'") {
  2524. in_string = false;
  2525. values.push(buffer);
  2526. buffer = '';
  2527. } else if (in_string) {
  2528. buffer += curr;
  2529. }
  2530. }
  2531. if (buffer.length > 0) {
  2532. // The leftovers in the buffer are the last value (if any)
  2533. values.push(buffer);
  2534. }
  2535. var fields = '';
  2536. // If there are no values, maybe the user is about to make a
  2537. // new list so we add a few for him/her to get started with.
  2538. if (values.length === 0) {
  2539. values.push('', '', '', '');
  2540. }
  2541. // Add the parsed values to the editor
  2542. var drop_icon = PMA_getImage('b_drop.png');
  2543. for (i = 0; i < values.length; i++) {
  2544. fields += "<tr><td>" +
  2545. "<input type='text' value='" + values[i] + "'/>" +
  2546. "</td><td class='drop'>" +
  2547. drop_icon +
  2548. "</td></tr>";
  2549. }
  2550. /**
  2551. * @var dialog HTML code for the ENUM/SET dialog
  2552. */
  2553. var dialog = "<div id='enum_editor'>" +
  2554. "<fieldset>" +
  2555. "<legend>" + title + "</legend>" +
  2556. "<p>" + PMA_getImage('s_notice.png') +
  2557. PMA_messages.enum_hint + "</p>" +
  2558. "<table class='values'>" + fields + "</table>" +
  2559. "</fieldset><fieldset class='tblFooters'>" +
  2560. "<table class='add'><tr><td>" +
  2561. "<div class='slider'></div>" +
  2562. "</td><td>" +
  2563. "<form><div><input type='submit' class='add_value' value='" +
  2564. $.sprintf(PMA_messages.enum_addValue, 1) +
  2565. "'/></div></form>" +
  2566. "</td></tr></table>" +
  2567. "<input type='hidden' value='" + // So we know which column's data is being edited
  2568. $(this).closest('td').find("input").attr("id") +
  2569. "' />" +
  2570. "</fieldset>" +
  2571. "</div>";
  2572. /**
  2573. * @var Defines functions to be called when the buttons in
  2574. * the buttonOptions jQuery dialog bar are pressed
  2575. */
  2576. var buttonOptions = {};
  2577. buttonOptions[PMA_messages.strGo] = function () {
  2578. // When the submit button is clicked,
  2579. // put the data back into the original form
  2580. var value_array = [];
  2581. $(this).find(".values input").each(function (index, elm) {
  2582. var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
  2583. value_array.push("'" + val + "'");
  2584. });
  2585. // get the Length/Values text field where this value belongs
  2586. var values_id = $(this).find("input[type='hidden']").val();
  2587. $("input#" + values_id).val(value_array.join(","));
  2588. $(this).dialog("close");
  2589. };
  2590. buttonOptions[PMA_messages.strClose] = function () {
  2591. $(this).dialog("close");
  2592. };
  2593. // Show the dialog
  2594. var width = parseInt(
  2595. (parseInt($('html').css('font-size'), 10) / 13) * 340,
  2596. 10
  2597. );
  2598. if (! width) {
  2599. width = 340;
  2600. }
  2601. $enum_editor_dialog = $(dialog).dialog({
  2602. minWidth: width,
  2603. modal: true,
  2604. title: PMA_messages.enum_editor,
  2605. buttons: buttonOptions,
  2606. open: function () {
  2607. // Focus the "Go" button after opening the dialog
  2608. $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
  2609. },
  2610. close: function () {
  2611. $(this).remove();
  2612. }
  2613. });
  2614. // slider for choosing how many fields to add
  2615. $enum_editor_dialog.find(".slider").slider({
  2616. animate: true,
  2617. range: "min",
  2618. value: 1,
  2619. min: 1,
  2620. max: 9,
  2621. slide: function (event, ui) {
  2622. $(this).closest('table').find('input[type=submit]').val(
  2623. $.sprintf(PMA_messages.enum_addValue, ui.value)
  2624. );
  2625. }
  2626. });
  2627. // Focus the slider, otherwise it looks nearly transparent
  2628. $('a.ui-slider-handle').addClass('ui-state-focus');
  2629. return false;
  2630. });
  2631. // When "add a new value" is clicked, append an empty text field
  2632. $("input.add_value").live('click', function (e) {
  2633. e.preventDefault();
  2634. var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
  2635. while (num_new_rows--) {
  2636. $enum_editor_dialog.find('.values')
  2637. .append(
  2638. "<tr style='display: none;'><td>" +
  2639. "<input type='text' />" +
  2640. "</td><td class='drop'>" +
  2641. PMA_getImage('b_drop.png') +
  2642. "</td></tr>"
  2643. )
  2644. .find('tr:last')
  2645. .show('fast');
  2646. }
  2647. });
  2648. // Removes the specified row from the enum editor
  2649. $("#enum_editor td.drop").live('click', function () {
  2650. $(this).closest('tr').hide('fast', function () {
  2651. $(this).remove();
  2652. });
  2653. });
  2654. });
  2655. /**
  2656. * Ensures indexes names are valid according to their type and, for a primary
  2657. * key, lock index name to 'PRIMARY'
  2658. * @param string form_id Variable which parses the form name as
  2659. * the input
  2660. * @return boolean false if there is no index form, true else
  2661. */
  2662. function checkIndexName(form_id)
  2663. {
  2664. if ($("#" + form_id).length === 0) {
  2665. return false;
  2666. }
  2667. // Gets the elements pointers
  2668. var $the_idx_name = $("#input_index_name");
  2669. var $the_idx_type = $("#select_index_type");
  2670. // Index is a primary key
  2671. if ($the_idx_type.find("option:selected").val() == 'PRIMARY') {
  2672. $the_idx_name.val('PRIMARY');
  2673. $the_idx_name.prop("disabled", true);
  2674. }
  2675. // Other cases
  2676. else {
  2677. if ($the_idx_name.val() == 'PRIMARY') {
  2678. $the_idx_name.val("");
  2679. }
  2680. $the_idx_name.prop("disabled", false);
  2681. }
  2682. return true;
  2683. } // end of the 'checkIndexName()' function
  2684. AJAX.registerTeardown('functions.js', function () {
  2685. $('#index_frm input[type=submit]').die('click');
  2686. });
  2687. AJAX.registerOnload('functions.js', function () {
  2688. /**
  2689. * Handler for adding more columns to an index in the editor
  2690. */
  2691. $('#index_frm input[type=submit]').live('click', function (event) {
  2692. event.preventDefault();
  2693. var rows_to_add = $(this)
  2694. .closest('fieldset')
  2695. .find('.slider')
  2696. .slider('value');
  2697. while (rows_to_add--) {
  2698. var $newrow = $('#index_columns')
  2699. .find('tbody > tr:first')
  2700. .clone()
  2701. .appendTo(
  2702. $('#index_columns').find('tbody')
  2703. );
  2704. $newrow.find(':input').each(function () {
  2705. $(this).val('');
  2706. });
  2707. // focus index size input on column picked
  2708. $newrow.find('select').change(function () {
  2709. if ($(this).find("option:selected").val() === '') {
  2710. return true;
  2711. }
  2712. $(this).closest("tr").find("input").focus();
  2713. });
  2714. }
  2715. });
  2716. });
  2717. function indexEditorDialog(url, title, callback_success, callback_failure)
  2718. {
  2719. /*Remove the hidden dialogs if there are*/
  2720. if ($('#edit_index_dialog').length !== 0) {
  2721. $('#edit_index_dialog').remove();
  2722. }
  2723. var $div = $('<div id="edit_index_dialog"></div>');
  2724. /**
  2725. * @var button_options Object that stores the options
  2726. * passed to jQueryUI dialog
  2727. */
  2728. var button_options = {};
  2729. button_options[PMA_messages.strGo] = function () {
  2730. /**
  2731. * @var the_form object referring to the export form
  2732. */
  2733. var $form = $("#index_frm");
  2734. var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  2735. PMA_prepareForAjaxRequest($form);
  2736. //User wants to submit the form
  2737. $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function (data) {
  2738. if ($("#sqlqueryresults").length !== 0) {
  2739. $("#sqlqueryresults").remove();
  2740. }
  2741. if (data.success === true) {
  2742. PMA_ajaxShowMessage(data.message);
  2743. if ($('#result_query').length) {
  2744. $('#result_query').remove();
  2745. }
  2746. if (data.sql_query) {
  2747. $('<div id="result_query"></div>')
  2748. .html(data.sql_query)
  2749. .prependTo('#page_content');
  2750. PMA_highlightSQL($('#page_content'));
  2751. }
  2752. $("#result_query .notice").remove();
  2753. $("#result_query").prepend(data.message);
  2754. /*Reload the field form*/
  2755. $("#table_index").remove();
  2756. var $temp_div = $("<div id='temp_div'><div>").append(data.index_table);
  2757. $temp_div.find("#table_index").insertAfter("#index_header");
  2758. if ($("#edit_index_dialog").length > 0) {
  2759. $("#edit_index_dialog").dialog("close");
  2760. }
  2761. $('div.no_indexes_defined').hide();
  2762. if (callback_success) {
  2763. callback_success();
  2764. }
  2765. PMA_reloadNavigation();
  2766. } else {
  2767. var $temp_div = $("<div id='temp_div'><div>").append(data.error);
  2768. var $error;
  2769. if ($temp_div.find(".error code").length !== 0) {
  2770. $error = $temp_div.find(".error code").addClass("error");
  2771. } else {
  2772. $error = $temp_div;
  2773. }
  2774. if (callback_failure) {
  2775. callback_failure();
  2776. }
  2777. PMA_ajaxShowMessage($error, false);
  2778. }
  2779. }); // end $.post()
  2780. };
  2781. button_options[PMA_messages.strCancel] = function () {
  2782. $(this).dialog('close');
  2783. };
  2784. var $msgbox = PMA_ajaxShowMessage();
  2785. $.get("tbl_indexes.php", url, function (data) {
  2786. if (data.success === false) {
  2787. //in the case of an error, show the error message returned.
  2788. PMA_ajaxShowMessage(data.error, false);
  2789. } else {
  2790. PMA_ajaxRemoveMessage($msgbox);
  2791. // Show dialog if the request was successful
  2792. $div
  2793. .append(data.message)
  2794. .dialog({
  2795. title: title,
  2796. width: 450,
  2797. open: PMA_verifyColumnsProperties,
  2798. modal: true,
  2799. buttons: button_options,
  2800. close: function () {
  2801. $(this).remove();
  2802. }
  2803. });
  2804. checkIndexType();
  2805. checkIndexName("index_frm");
  2806. PMA_showHints($div);
  2807. // Add a slider for selecting how many columns to add to the index
  2808. $div.find('.slider').slider({
  2809. animate: true,
  2810. value: 1,
  2811. min: 1,
  2812. max: 16,
  2813. slide: function (event, ui) {
  2814. $(this).closest('fieldset').find('input[type=submit]').val(
  2815. $.sprintf(PMA_messages.strAddToIndex, ui.value)
  2816. );
  2817. }
  2818. });
  2819. // focus index size input on column picked
  2820. $div.find('table#index_columns select').change(function () {
  2821. if ($(this).find("option:selected").val() === '') {
  2822. return true;
  2823. }
  2824. $(this).closest("tr").find("input").focus();
  2825. });
  2826. // Focus the slider, otherwise it looks nearly transparent
  2827. $('a.ui-slider-handle').addClass('ui-state-focus');
  2828. // set focus on index name input, if empty
  2829. var input = $div.find('input#input_index_name');
  2830. input.val() || input.focus();
  2831. }
  2832. }); // end $.get()
  2833. }
  2834. /**
  2835. * Function to display tooltips that were
  2836. * generated on the PHP side by PMA_Util::showHint()
  2837. *
  2838. * @param object $div a div jquery object which specifies the
  2839. * domain for searching for tooltips. If we
  2840. * omit this parameter the function searches
  2841. * in the whole body
  2842. **/
  2843. function PMA_showHints($div)
  2844. {
  2845. if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
  2846. $div = $("body");
  2847. }
  2848. $div.find('.pma_hint').each(function () {
  2849. PMA_tooltip(
  2850. $(this).children('img'),
  2851. 'img',
  2852. $(this).children('span').html()
  2853. );
  2854. });
  2855. }
  2856. AJAX.registerOnload('functions.js', function () {
  2857. PMA_showHints();
  2858. });
  2859. function PMA_mainMenuResizerCallback() {
  2860. // 5 px margin for jumping menu in Chrome
  2861. return $(document.body).width() - 5;
  2862. }
  2863. // This must be fired only once after the inital page load
  2864. $(function () {
  2865. // Initialise the menu resize plugin
  2866. $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
  2867. // register resize event
  2868. $(window).resize(function () {
  2869. $('#topmenu').menuResizer('resize');
  2870. });
  2871. });
  2872. /**
  2873. * Get the row number from the classlist (for example, row_1)
  2874. */
  2875. function PMA_getRowNumber(classlist)
  2876. {
  2877. return parseInt(classlist.split(/\s+row_/)[1], 10);
  2878. }
  2879. /**
  2880. * Changes status of slider
  2881. */
  2882. function PMA_set_status_label($element)
  2883. {
  2884. var text;
  2885. if ($element.css('display') == 'none') {
  2886. text = '+ ';
  2887. } else {
  2888. text = '- ';
  2889. }
  2890. $element.closest('.slide-wrapper').prev().find('span').text(text);
  2891. }
  2892. /**
  2893. * var toggleButton This is a function that creates a toggle
  2894. * sliding button given a jQuery reference
  2895. * to the correct DOM element
  2896. */
  2897. var toggleButton = function ($obj) {
  2898. // In rtl mode the toggle switch is flipped horizontally
  2899. // so we need to take that into account
  2900. var right;
  2901. if ($('span.text_direction', $obj).text() == 'ltr') {
  2902. right = 'right';
  2903. } else {
  2904. right = 'left';
  2905. }
  2906. /**
  2907. * var h Height of the button, used to scale the
  2908. * background image and position the layers
  2909. */
  2910. var h = $obj.height();
  2911. $('img', $obj).height(h);
  2912. $('table', $obj).css('bottom', h - 1);
  2913. /**
  2914. * var on Width of the "ON" part of the toggle switch
  2915. * var off Width of the "OFF" part of the toggle switch
  2916. */
  2917. var on = $('td.toggleOn', $obj).width();
  2918. var off = $('td.toggleOff', $obj).width();
  2919. // Make the "ON" and "OFF" parts of the switch the same size
  2920. // + 2 pixels to avoid overflowed
  2921. $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
  2922. $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
  2923. /**
  2924. * var w Width of the central part of the switch
  2925. */
  2926. var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
  2927. // Resize the central part of the switch on the top
  2928. // layer to match the background
  2929. $('table td:nth-child(2) > div', $obj).width(w);
  2930. /**
  2931. * var imgw Width of the background image
  2932. * var tblw Width of the foreground layer
  2933. * var offset By how many pixels to move the background
  2934. * image, so that it matches the top layer
  2935. */
  2936. var imgw = $('img', $obj).width();
  2937. var tblw = $('table', $obj).width();
  2938. var offset = parseInt(((imgw - tblw) / 2), 10);
  2939. // Move the background to match the layout of the top layer
  2940. $obj.find('img').css(right, offset);
  2941. /**
  2942. * var offw Outer width of the "ON" part of the toggle switch
  2943. * var btnw Outer width of the central part of the switch
  2944. */
  2945. var offw = $('td.toggleOff', $obj).outerWidth();
  2946. var btnw = $('table td:nth-child(2)', $obj).outerWidth();
  2947. // Resize the main div so that exactly one side of
  2948. // the switch plus the central part fit into it.
  2949. $obj.width(offw + btnw + 2);
  2950. /**
  2951. * var move How many pixels to move the
  2952. * switch by when toggling
  2953. */
  2954. var move = $('td.toggleOff', $obj).outerWidth();
  2955. // If the switch is initialized to the
  2956. // OFF state we need to move it now.
  2957. if ($('div.container', $obj).hasClass('off')) {
  2958. if (right == 'right') {
  2959. $('div.container', $obj).animate({'left': '-=' + move + 'px'}, 0);
  2960. } else {
  2961. $('div.container', $obj).animate({'left': '+=' + move + 'px'}, 0);
  2962. }
  2963. }
  2964. // Attach an 'onclick' event to the switch
  2965. $('div.container', $obj).click(function () {
  2966. if ($(this).hasClass('isActive')) {
  2967. return false;
  2968. } else {
  2969. $(this).addClass('isActive');
  2970. }
  2971. var $msg = PMA_ajaxShowMessage();
  2972. var $container = $(this);
  2973. var callback = $('span.callback', this).text();
  2974. var operator, url, removeClass, addClass;
  2975. // Perform the actual toggle
  2976. if ($(this).hasClass('on')) {
  2977. if (right == 'right') {
  2978. operator = '-=';
  2979. } else {
  2980. operator = '+=';
  2981. }
  2982. url = $(this).find('td.toggleOff > span').text();
  2983. removeClass = 'on';
  2984. addClass = 'off';
  2985. } else {
  2986. if (right == 'right') {
  2987. operator = '+=';
  2988. } else {
  2989. operator = '-=';
  2990. }
  2991. url = $(this).find('td.toggleOn > span').text();
  2992. removeClass = 'off';
  2993. addClass = 'on';
  2994. }
  2995. $.post(url, {'ajax_request': true}, function (data) {
  2996. if (data.success === true) {
  2997. PMA_ajaxRemoveMessage($msg);
  2998. $container
  2999. .removeClass(removeClass)
  3000. .addClass(addClass)
  3001. .animate({'left': operator + move + 'px'}, function () {
  3002. $container.removeClass('isActive');
  3003. });
  3004. eval(callback);
  3005. } else {
  3006. PMA_ajaxShowMessage(data.error, false);
  3007. $container.removeClass('isActive');
  3008. }
  3009. });
  3010. });
  3011. };
  3012. /**
  3013. * Unbind all event handlers before tearing down a page
  3014. */
  3015. AJAX.registerTeardown('functions.js', function () {
  3016. $('div.container').unbind('click');
  3017. });
  3018. /**
  3019. * Initialise all toggle buttons
  3020. */
  3021. AJAX.registerOnload('functions.js', function () {
  3022. $('div.toggleAjax').each(function () {
  3023. var $button = $(this).show();
  3024. $button.find('img').each(function () {
  3025. if (this.complete) {
  3026. toggleButton($button);
  3027. } else {
  3028. $(this).load(function () {
  3029. toggleButton($button);
  3030. });
  3031. }
  3032. });
  3033. });
  3034. });
  3035. /**
  3036. * Unbind all event handlers before tearing down a page
  3037. */
  3038. AJAX.registerTeardown('functions.js', function () {
  3039. $('.vpointer').die('hover');
  3040. $('.vmarker').die('click');
  3041. $('#pageselector').die('change');
  3042. $('a.formLinkSubmit').die('click');
  3043. $('#update_recent_tables').unbind('ready');
  3044. });
  3045. /**
  3046. * Vertical pointer
  3047. */
  3048. AJAX.registerOnload('functions.js', function () {
  3049. $('.vpointer').live('hover',
  3050. //handlerInOut
  3051. function (e) {
  3052. var $this_td = $(this);
  3053. var row_num = PMA_getRowNumber($this_td.attr('class'));
  3054. // for all td of the same vertical row, toggle hover
  3055. $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
  3056. }
  3057. );
  3058. /**
  3059. * Vertical marker
  3060. */
  3061. $('.vmarker').live('click', function (e) {
  3062. // do not trigger when clicked on anchor
  3063. if ($(e.target).is('a, img, a *')) {
  3064. return;
  3065. }
  3066. var $this_td = $(this);
  3067. var row_num = PMA_getRowNumber($this_td.attr('class'));
  3068. // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
  3069. var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
  3070. if ($checkbox.length) {
  3071. // checkbox in a row, add or remove class depending on checkbox state
  3072. var checked = $checkbox.prop('checked');
  3073. if (!$(e.target).is(':checkbox, label')) {
  3074. checked = !checked;
  3075. $checkbox.prop('checked', checked);
  3076. }
  3077. // for all td of the same vertical row, toggle the marked class
  3078. if (checked) {
  3079. $('.vmarker').filter('.row_' + row_num).addClass('marked');
  3080. } else {
  3081. $('.vmarker').filter('.row_' + row_num).removeClass('marked');
  3082. }
  3083. } else {
  3084. // normaln data table, just toggle class
  3085. $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
  3086. }
  3087. });
  3088. /**
  3089. * Autosubmit page selector
  3090. */
  3091. $('select.pageselector').live('change', function (event) {
  3092. event.stopPropagation();
  3093. // Check where to load the new content
  3094. if ($(this).closest("#pma_navigation").length === 0) {
  3095. // For the main page we don't need to do anything,
  3096. $(this).closest("form").submit();
  3097. } else {
  3098. // but for the navigation we need to manually replace the content
  3099. PMA_navigationTreePagination($(this));
  3100. }
  3101. });
  3102. /**
  3103. * Load version information asynchronously.
  3104. */
  3105. if ($('li.jsversioncheck').length > 0) {
  3106. $.getJSON('version_check.php', {}, PMA_current_version);
  3107. }
  3108. if ($('#is_git_revision').length > 0) {
  3109. setTimeout(PMA_display_git_revision, 10);
  3110. }
  3111. /**
  3112. * Slider effect.
  3113. */
  3114. PMA_init_slider();
  3115. /**
  3116. * Enables the text generated by PMA_Util::linkOrButton() to be clickable
  3117. */
  3118. $('a.formLinkSubmit').live('click', function (e) {
  3119. if ($(this).attr('href').indexOf('=') != -1) {
  3120. var data = $(this).attr('href').substr($(this).attr('href').indexOf('#') + 1).split('=', 2);
  3121. $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
  3122. }
  3123. $(this).parents('form').submit();
  3124. return false;
  3125. });
  3126. if ($('#update_recent_tables').length) {
  3127. $.get(
  3128. $('#update_recent_tables').attr('href'),
  3129. function (data) {
  3130. if (data.success === true) {
  3131. $('#recentTable').html(data.options);
  3132. }
  3133. }
  3134. );
  3135. }
  3136. }); // end of $()
  3137. /**
  3138. * Initializes slider effect.
  3139. */
  3140. function PMA_init_slider()
  3141. {
  3142. $('div.pma_auto_slider').each(function () {
  3143. var $this = $(this);
  3144. if ($this.data('slider_init_done')) {
  3145. return;
  3146. }
  3147. var $wrapper = $('<div>', {'class': 'slide-wrapper'});
  3148. $wrapper.toggle($this.is(':visible'));
  3149. $('<a>', {href: '#' + this.id, "class": 'ajax'})
  3150. .text(this.title)
  3151. .prepend($('<span>'))
  3152. .insertBefore($this)
  3153. .click(function () {
  3154. var $wrapper = $this.closest('.slide-wrapper');
  3155. var visible = $this.is(':visible');
  3156. if (!visible) {
  3157. $wrapper.show();
  3158. }
  3159. $this[visible ? 'hide' : 'show']('blind', function () {
  3160. $wrapper.toggle(!visible);
  3161. PMA_set_status_label($this);
  3162. });
  3163. return false;
  3164. });
  3165. $this.wrap($wrapper);
  3166. PMA_set_status_label($this);
  3167. $this.data('slider_init_done', 1);
  3168. });
  3169. }
  3170. /**
  3171. * Initializes slider effect.
  3172. */
  3173. AJAX.registerOnload('functions.js', function () {
  3174. PMA_init_slider();
  3175. });
  3176. /**
  3177. * Restores sliders to the state they were in before initialisation.
  3178. */
  3179. AJAX.registerTeardown('functions.js', function () {
  3180. $('div.pma_auto_slider').each(function () {
  3181. var $this = $(this);
  3182. $this.removeData();
  3183. $this.parent().replaceWith($this);
  3184. $this.parent().children('a').remove();
  3185. });
  3186. });
  3187. /**
  3188. * Creates a message inside an object with a sliding effect
  3189. *
  3190. * @param msg A string containing the text to display
  3191. * @param $obj a jQuery object containing the reference
  3192. * to the element where to put the message
  3193. * This is optional, if no element is
  3194. * provided, one will be created below the
  3195. * navigation links at the top of the page
  3196. *
  3197. * @return bool True on success, false on failure
  3198. */
  3199. function PMA_slidingMessage(msg, $obj)
  3200. {
  3201. if (msg === undefined || msg.length === 0) {
  3202. // Don't show an empty message
  3203. return false;
  3204. }
  3205. if ($obj === undefined || ! $obj instanceof jQuery || $obj.length === 0) {
  3206. // If the second argument was not supplied,
  3207. // we might have to create a new DOM node.
  3208. if ($('#PMA_slidingMessage').length === 0) {
  3209. $('#page_content').prepend(
  3210. '<span id="PMA_slidingMessage" ' +
  3211. 'style="display: inline-block;"></span>'
  3212. );
  3213. }
  3214. $obj = $('#PMA_slidingMessage');
  3215. }
  3216. if ($obj.has('div').length > 0) {
  3217. // If there already is a message inside the
  3218. // target object, we must get rid of it
  3219. $obj
  3220. .find('div')
  3221. .first()
  3222. .fadeOut(function () {
  3223. $obj
  3224. .children()
  3225. .remove();
  3226. $obj
  3227. .append('<div>' + msg + '</div>');
  3228. // highlight any sql before taking height;
  3229. PMA_highlightSQL($obj);
  3230. $obj.find('div')
  3231. .first()
  3232. .hide();
  3233. $obj
  3234. .animate({
  3235. height: $obj.find('div').first().height()
  3236. })
  3237. .find('div')
  3238. .first()
  3239. .fadeIn();
  3240. });
  3241. } else {
  3242. // Object does not already have a message
  3243. // inside it, so we simply slide it down
  3244. $obj.width('100%')
  3245. .html('<div>' + msg + '</div>');
  3246. // highlight any sql before taking height;
  3247. PMA_highlightSQL($obj);
  3248. var h = $obj
  3249. .find('div')
  3250. .first()
  3251. .hide()
  3252. .height();
  3253. $obj
  3254. .find('div')
  3255. .first()
  3256. .css('height', 0)
  3257. .show()
  3258. .animate({
  3259. height: h
  3260. }, function () {
  3261. // Set the height of the parent
  3262. // to the height of the child
  3263. $obj
  3264. .height(
  3265. $obj
  3266. .find('div')
  3267. .first()
  3268. .height()
  3269. );
  3270. });
  3271. }
  3272. return true;
  3273. } // end PMA_slidingMessage()
  3274. /**
  3275. * Unbind all event handlers before tearing down a page
  3276. */
  3277. AJAX.registerTeardown('functions.js', function () {
  3278. $("#drop_tbl_anchor.ajax").die('click');
  3279. $("#drop_view_anchor.ajax").die('click');
  3280. $("#truncate_tbl_anchor.ajax").die('click');
  3281. });
  3282. /**
  3283. * Attach Ajax event handlers for Drop Table.
  3284. */
  3285. AJAX.registerOnload('functions.js', function () {
  3286. $("#drop_tbl_anchor.ajax").live('click', function (event) {
  3287. event.preventDefault();
  3288. /**
  3289. * @var question String containing the question to be asked for confirmation
  3290. */
  3291. var question = PMA_messages.strDropTableStrongWarning + ' ';
  3292. question += $.sprintf(
  3293. PMA_messages.strDoYouReally,
  3294. 'DROP TABLE ' + PMA_commonParams.get('table')
  3295. );
  3296. $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
  3297. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  3298. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
  3299. if (data.success === true) {
  3300. PMA_ajaxRemoveMessage($msgbox);
  3301. // Table deleted successfully, refresh both the frames
  3302. PMA_reloadNavigation();
  3303. PMA_commonParams.set('table', '');
  3304. PMA_commonActions.refreshMain(
  3305. PMA_commonParams.get('opendb_url'),
  3306. function () {
  3307. PMA_ajaxShowMessage(data.message);
  3308. }
  3309. );
  3310. } else {
  3311. PMA_ajaxShowMessage(data.error, false);
  3312. }
  3313. }); // end $.get()
  3314. }); // end $.PMA_confirm()
  3315. }); //end of Drop Table Ajax action
  3316. $("#drop_view_anchor.ajax").live('click', function (event) {
  3317. event.preventDefault();
  3318. /**
  3319. * @var question String containing the question to be asked for confirmation
  3320. */
  3321. var question = PMA_messages.strDropTableStrongWarning + ' ';
  3322. question += $.sprintf(
  3323. PMA_messages.strDoYouReally,
  3324. 'DROP VIEW ' + PMA_commonParams.get('table')
  3325. );
  3326. $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
  3327. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  3328. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
  3329. if (data.success === true) {
  3330. PMA_ajaxRemoveMessage($msgbox);
  3331. // Table deleted successfully, refresh both the frames
  3332. PMA_reloadNavigation();
  3333. PMA_commonParams.set('table', '');
  3334. PMA_commonActions.refreshMain(
  3335. PMA_commonParams.get('opendb_url'),
  3336. function () {
  3337. PMA_ajaxShowMessage(data.message);
  3338. }
  3339. );
  3340. } else {
  3341. PMA_ajaxShowMessage(data.error, false);
  3342. }
  3343. }); // end $.get()
  3344. }); // end $.PMA_confirm()
  3345. }); //end of Drop View Ajax action
  3346. $("#truncate_tbl_anchor.ajax").live('click', function (event) {
  3347. event.preventDefault();
  3348. /**
  3349. * @var question String containing the question to be asked for confirmation
  3350. */
  3351. var question = PMA_messages.strTruncateTableStrongWarning + ' ';
  3352. question += $.sprintf(
  3353. PMA_messages.strDoYouReally,
  3354. 'TRUNCATE ' + PMA_commonParams.get('table')
  3355. );
  3356. $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
  3357. PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  3358. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
  3359. if ($("#sqlqueryresults").length !== 0) {
  3360. $("#sqlqueryresults").remove();
  3361. }
  3362. if ($("#result_query").length !== 0) {
  3363. $("#result_query").remove();
  3364. }
  3365. if (data.success === true) {
  3366. PMA_ajaxShowMessage(data.message);
  3367. $("<div id='sqlqueryresults'></div>").prependTo("#page_content");
  3368. $("#sqlqueryresults").html(data.sql_query);
  3369. PMA_highlightSQL($('#page_content'));
  3370. } else {
  3371. PMA_ajaxShowMessage(data.error, false);
  3372. }
  3373. }); // end $.get()
  3374. }); // end $.PMA_confirm()
  3375. }); //end of Truncate Table Ajax action
  3376. }); // end of $() for Truncate Table
  3377. /**
  3378. * Attach CodeMirror2 editor to SQL edit area.
  3379. */
  3380. AJAX.registerOnload('functions.js', function () {
  3381. var $elm = $('#sqlquery');
  3382. if ($elm.length > 0) {
  3383. if (typeof CodeMirror != 'undefined') {
  3384. // for codemirror
  3385. codemirror_editor = CodeMirror.fromTextArea($elm[0], {
  3386. lineNumbers: true,
  3387. matchBrackets: true,
  3388. indentUnit: 4,
  3389. mode: "text/x-mysql",
  3390. lineWrapping: true
  3391. });
  3392. codemirror_editor.focus();
  3393. $(codemirror_editor.getWrapperElement()).bind(
  3394. 'keydown',
  3395. catchKeypressesFromSqlTextboxes
  3396. );
  3397. } else {
  3398. // without codemirror
  3399. $elm.focus().bind('keydown', catchKeypressesFromSqlTextboxes);
  3400. }
  3401. }
  3402. PMA_highlightSQL($('body'));
  3403. });
  3404. AJAX.registerTeardown('functions.js', function () {
  3405. if (codemirror_editor) {
  3406. $('#sqlquery').text(codemirror_editor.getValue());
  3407. codemirror_editor.toTextArea();
  3408. codemirror_editor = false;
  3409. }
  3410. });
  3411. /**
  3412. * jQuery plugin to cancel selection in HTML code.
  3413. */
  3414. (function ($) {
  3415. $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
  3416. var prevent = (p === null) ? true : p;
  3417. if (prevent) {
  3418. return this.each(function () {
  3419. if ($.browser.msie || $.browser.safari) {
  3420. $(this).bind('selectstart', function () {
  3421. return false;
  3422. });
  3423. } else if ($.browser.mozilla) {
  3424. $(this).css('MozUserSelect', 'none');
  3425. $('body').trigger('focus');
  3426. } else if ($.browser.opera) {
  3427. $(this).bind('mousedown', function () {
  3428. return false;
  3429. });
  3430. } else {
  3431. $(this).attr('unselectable', 'on');
  3432. }
  3433. });
  3434. } else {
  3435. return this.each(function () {
  3436. if ($.browser.msie || $.browser.safari) {
  3437. $(this).unbind('selectstart');
  3438. } else if ($.browser.mozilla) {
  3439. $(this).css('MozUserSelect', 'inherit');
  3440. } else if ($.browser.opera) {
  3441. $(this).unbind('mousedown');
  3442. } else {
  3443. $(this).removeAttr('unselectable');
  3444. }
  3445. });
  3446. }
  3447. }; //end noSelect
  3448. })(jQuery);
  3449. /**
  3450. * jQuery plugin to correctly filter input fields by value, needed
  3451. * because some nasty values may break selector syntax
  3452. */
  3453. (function ($) {
  3454. $.fn.filterByValue = function (value) {
  3455. return this.filter(function () {
  3456. return $(this).val() === value;
  3457. });
  3458. };
  3459. })(jQuery);
  3460. /**
  3461. * Create a jQuery UI tooltip
  3462. *
  3463. * @param $elements jQuery object representing the elements
  3464. * @param item the item
  3465. * (see http://api.jqueryui.com/tooltip/#option-items)
  3466. * @param myContent content of the tooltip
  3467. * @param additionalOptions to override the default options
  3468. *
  3469. */
  3470. function PMA_tooltip($elements, item, myContent, additionalOptions)
  3471. {
  3472. if ($('#no_hint').length > 0) {
  3473. return;
  3474. }
  3475. var defaultOptions = {
  3476. content: myContent,
  3477. items: item,
  3478. tooltipClass: "tooltip",
  3479. track: true,
  3480. show: false,
  3481. hide: false
  3482. };
  3483. $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
  3484. }
  3485. /**
  3486. * Return value of a cell in a table.
  3487. */
  3488. function PMA_getCellValue(td) {
  3489. var $td = $(td);
  3490. if ($td.is('.null')) {
  3491. return '';
  3492. } else if (! $td.is('.to_be_saved') && $td.data('original_data')) {
  3493. return $td.data('original_data');
  3494. } else {
  3495. return $td.text();
  3496. }
  3497. }
  3498. /**
  3499. * Unbind all event handlers before tearing down a page
  3500. */
  3501. AJAX.registerTeardown('functions.js', function () {
  3502. $('a.themeselect').die('click');
  3503. $('.autosubmit').die('change');
  3504. $('a.take_theme').unbind('click');
  3505. });
  3506. AJAX.registerOnload('functions.js', function () {
  3507. /**
  3508. * Theme selector.
  3509. */
  3510. $('a.themeselect').live('click', function (e) {
  3511. window.open(
  3512. e.target,
  3513. 'themes',
  3514. 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
  3515. );
  3516. return false;
  3517. });
  3518. /**
  3519. * Automatic form submission on change.
  3520. */
  3521. $('.autosubmit').live('change', function (e) {
  3522. $(this).closest('form').submit();
  3523. });
  3524. /**
  3525. * Theme changer.
  3526. */
  3527. $('a.take_theme').click(function (e) {
  3528. var what = this.name;
  3529. if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
  3530. window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
  3531. window.opener.document.forms['setTheme'].submit();
  3532. window.close();
  3533. return false;
  3534. }
  3535. return true;
  3536. });
  3537. });
  3538. /**
  3539. * Clear text selection
  3540. */
  3541. function PMA_clearSelection() {
  3542. if (document.selection && document.selection.empty) {
  3543. document.selection.empty();
  3544. } else if (window.getSelection) {
  3545. var sel = window.getSelection();
  3546. if (sel.empty) {
  3547. sel.empty();
  3548. }
  3549. if (sel.removeAllRanges) {
  3550. sel.removeAllRanges();
  3551. }
  3552. }
  3553. }
  3554. /**
  3555. * HTML escaping
  3556. */
  3557. function escapeHtml(unsafe) {
  3558. return unsafe
  3559. .replace(/&/g, "&amp;")
  3560. .replace(/</g, "&lt;")
  3561. .replace(/>/g, "&gt;")
  3562. .replace(/"/g, "&quot;")
  3563. .replace(/'/g, "&#039;");
  3564. }
  3565. /**
  3566. * Print button
  3567. */
  3568. function printPage()
  3569. {
  3570. // Do print the page
  3571. if (typeof(window.print) != 'undefined') {
  3572. window.print();
  3573. }
  3574. }
  3575. /**
  3576. * Unbind all event handlers before tearing down a page
  3577. */
  3578. AJAX.registerTeardown('functions.js', function () {
  3579. $('input#print').unbind('click');
  3580. $('a.create_view.ajax').die('click');
  3581. $('#createViewDialog').find('input, select').die('keydown');
  3582. });
  3583. AJAX.registerOnload('functions.js', function () {
  3584. $('input#print').click(printPage);
  3585. /**
  3586. * Ajaxification for the "Create View" action
  3587. */
  3588. $('a.create_view.ajax').live('click', function (e) {
  3589. e.preventDefault();
  3590. PMA_createViewDialog($(this));
  3591. });
  3592. /**
  3593. * Attach Ajax event handlers for input fields in the editor
  3594. * and used to submit the Ajax request when the ENTER key is pressed.
  3595. */
  3596. $('#createViewDialog').find('input, select').live('keydown', function (e) {
  3597. if (e.which === 13) { // 13 is the ENTER key
  3598. e.preventDefault();
  3599. // with preventing default, selection by <select> tag
  3600. // was also prevented in IE
  3601. $(this).blur();
  3602. $(this).closest('.ui-dialog').find('.ui-button:first').click();
  3603. }
  3604. }); // end $.live()
  3605. var $elm = $('textarea[name="view[as]"]');
  3606. if ($elm.length > 0) {
  3607. if (typeof CodeMirror != 'undefined') {
  3608. syntaxHighlighter = CodeMirror.fromTextArea(
  3609. $elm[0],
  3610. {
  3611. lineNumbers: true,
  3612. matchBrackets: true,
  3613. indentUnit: 4,
  3614. mode: "text/x-mysql",
  3615. lineWrapping: true
  3616. }
  3617. );
  3618. }
  3619. }
  3620. });
  3621. function PMA_createViewDialog($this)
  3622. {
  3623. var $msg = PMA_ajaxShowMessage();
  3624. var syntaxHighlighter = null;
  3625. $.get($this.attr('href') + '&ajax_request=1&ajax_dialog=1', function (data) {
  3626. if (data.success === true) {
  3627. PMA_ajaxRemoveMessage($msg);
  3628. var buttonOptions = {};
  3629. buttonOptions[PMA_messages.strGo] = function () {
  3630. if (typeof CodeMirror !== 'undefined') {
  3631. syntaxHighlighter.save();
  3632. }
  3633. $msg = PMA_ajaxShowMessage();
  3634. $.get('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
  3635. PMA_ajaxRemoveMessage($msg);
  3636. if (data.success === true) {
  3637. $('#createViewDialog').dialog("close");
  3638. $('#result_query').html(data.message);
  3639. PMA_reloadNavigation();
  3640. } else {
  3641. PMA_ajaxShowMessage(data.error, false);
  3642. }
  3643. });
  3644. };
  3645. buttonOptions[PMA_messages.strClose] = function () {
  3646. $(this).dialog("close");
  3647. };
  3648. var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
  3649. width: 600,
  3650. minWidth: 400,
  3651. modal: true,
  3652. buttons: buttonOptions,
  3653. title: PMA_messages.strCreateView,
  3654. close: function () {
  3655. $(this).remove();
  3656. }
  3657. });
  3658. // Attach syntax highlited editor
  3659. if (typeof CodeMirror !== 'undefined') {
  3660. var $elm = $dialog.find('textarea');
  3661. var opts = {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql", lineWrapping: true};
  3662. syntaxHighlighter = CodeMirror.fromTextArea($elm[0], opts);
  3663. }
  3664. $('input:visible[type=text]', $dialog).first().focus();
  3665. } else {
  3666. PMA_ajaxShowMessage(data.error);
  3667. }
  3668. });
  3669. }
  3670. /**
  3671. * Makes the breadcrumbs and the menu bar float at the top of the viewport
  3672. */
  3673. $(function () {
  3674. if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length === 0) {
  3675. var left = $('html').attr('dir') == 'ltr' ? 'left' : 'right';
  3676. $("#floating_menubar")
  3677. .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
  3678. .css(left, 0)
  3679. .css({
  3680. 'position': 'fixed',
  3681. 'top': 0,
  3682. 'width': '100%',
  3683. 'z-index': 500
  3684. })
  3685. .append($('#serverinfo'))
  3686. .append($('#topmenucontainer'));
  3687. // Allow the DOM to render, then adjust the padding on the body
  3688. setTimeout(function () {
  3689. $('body').css(
  3690. 'padding-top',
  3691. $('#floating_menubar').outerHeight(true)
  3692. );
  3693. $('#topmenu').menuResizer('resize');
  3694. }, 4);
  3695. }
  3696. });
  3697. /**
  3698. * Scrolls the page to the top if clicking the serverinfo bar
  3699. */
  3700. $(function () {
  3701. $(document).delegate("#serverinfo, #goto_pagetop", "click", function (event) {
  3702. event.preventDefault();
  3703. $('html, body').animate({scrollTop: 0}, 'fast');
  3704. });
  3705. });
  3706. var checkboxes_sel = "input.checkall:checkbox:enabled";
  3707. /**
  3708. * Watches checkboxes in a form to set the checkall box accordingly
  3709. */
  3710. var checkboxes_changed = function () {
  3711. var $form = $(this.form);
  3712. // total number of checkboxes in current form
  3713. var total_boxes = $form.find(checkboxes_sel).length;
  3714. // number of checkboxes checked in current form
  3715. var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
  3716. var $checkall = $form.find("input.checkall_box");
  3717. if (total_boxes == checked_boxes) {
  3718. $checkall.prop({checked: true, indeterminate: false});
  3719. }
  3720. else if (checked_boxes > 0) {
  3721. $checkall.prop({checked: true, indeterminate: true});
  3722. }
  3723. else {
  3724. $checkall.prop({checked: false, indeterminate: false});
  3725. }
  3726. };
  3727. $(checkboxes_sel).live("change", checkboxes_changed);
  3728. $("input.checkall_box").live("change", function () {
  3729. var is_checked = $(this).is(":checked");
  3730. $(this.form).find(checkboxes_sel).prop("checked", is_checked)
  3731. .parents("tr").toggleClass("marked", is_checked);
  3732. });
  3733. /**
  3734. * Toggles row colors of a set of 'tr' elements starting from a given element
  3735. *
  3736. * @param $start Starting element
  3737. */
  3738. function toggleRowColors($start)
  3739. {
  3740. for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
  3741. if ($curr_row.hasClass('odd')) {
  3742. $curr_row.removeClass('odd').addClass('even');
  3743. } else if ($curr_row.hasClass('even')) {
  3744. $curr_row.removeClass('even').addClass('odd');
  3745. }
  3746. }
  3747. }
  3748. /**
  3749. * Formats a byte number to human-readable form
  3750. *
  3751. * @param bytes the bytes to format
  3752. * @param optional subdecimals the number of digits after the point
  3753. * @param optional pointchar the char to use as decimal point
  3754. */
  3755. function formatBytes(bytes, subdecimals, pointchar) {
  3756. if (!subdecimals) {
  3757. subdecimals = 0;
  3758. }
  3759. if (!pointchar) {
  3760. pointchar = '.';
  3761. }
  3762. var units = ['B', 'KiB', 'MiB', 'GiB'];
  3763. for (var i = 0; bytes > 1024 && i < units.length; i++) {
  3764. bytes /= 1024;
  3765. }
  3766. var factor = Math.pow(10, subdecimals);
  3767. bytes = Math.round(bytes * factor) / factor;
  3768. bytes = bytes.toString().split('.').join(pointchar);
  3769. return bytes + ' ' + units[i];
  3770. }
  3771. AJAX.registerOnload('functions.js', function () {
  3772. /**
  3773. * Opens pma more themes link in themes browser, in new window instead of popup
  3774. * This way, we don't break HTML validity
  3775. */
  3776. $("a._blank").prop("target", "_blank");
  3777. /**
  3778. * Reveal the login form to users with JS enabled
  3779. * and focus the appropriate input field
  3780. */
  3781. var $loginform = $('#loginform');
  3782. if ($loginform.length) {
  3783. $loginform.find('.js-show').show();
  3784. if ($('#input_username').val()) {
  3785. $('#input_password').focus();
  3786. } else {
  3787. $('#input_username').focus();
  3788. }
  3789. }
  3790. });
  3791. /**
  3792. * When user gets an ajax session expiry message, we show a login link
  3793. */
  3794. $('a.login-link').live('click', function (e) {
  3795. e.preventDefault();
  3796. window.location.reload(true);
  3797. });
  3798. /**
  3799. * Dynamically adjust the width of the boxes
  3800. * on the table and db operations pages
  3801. */
  3802. (function () {
  3803. function DynamicBoxes() {
  3804. var $boxContainer = $('#boxContainer');
  3805. if ($boxContainer.length) {
  3806. var minWidth = $boxContainer.data('box-width');
  3807. var viewport = $(window).width() - $('#pma_navigation').width();
  3808. var slots = Math.floor(viewport / minWidth);
  3809. $boxContainer.children()
  3810. .each(function () {
  3811. if (viewport < minWidth) {
  3812. $(this).width(minWidth);
  3813. } else {
  3814. $(this).css('width', ((1 / slots) * 100) + "%");
  3815. }
  3816. })
  3817. .removeClass('clearfloat')
  3818. .filter(':nth-child(' + slots + 'n+1)')
  3819. .addClass('clearfloat');
  3820. }
  3821. }
  3822. AJAX.registerOnload('functions.js', function () {
  3823. DynamicBoxes();
  3824. });
  3825. $(function () {
  3826. $(window).resize(DynamicBoxes);
  3827. });
  3828. })();
  3829. /**
  3830. * Formats timestamp for display
  3831. */
  3832. function PMA_formatDateTime(date, seconds) {
  3833. var result = $.datepicker.formatDate('yy-mm-dd', date);
  3834. var timefmt = 'HH:mm';
  3835. if (seconds) {
  3836. timefmt = 'HH:mm:ss';
  3837. }
  3838. return result + ' ' + $.datepicker.formatTime(
  3839. timefmt, {
  3840. hour: date.getHours(),
  3841. minute: date.getMinutes(),
  3842. second: date.getSeconds()
  3843. }
  3844. );
  3845. }