1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Functions used in configuration forms and on user preferences pages
7 * checks whether browser supports web storage
9 * @param type the type of storage i.e. localStorage or sessionStorage
13 function isStorageSupported (type, warn) {
15 window[type].setItem('PMATest', 'test');
16 // Check whether key-value pair was set successfully
17 if (window[type].getItem('PMATest') === 'test') {
18 // Supported, remove test variable from storage
19 window[type].removeItem('PMATest');
25 PMA_ajaxShowMessage(PMA_messages.strNoLocalStorage, false);
32 * Unbind all event handlers before tearing down a page
34 AJAX.registerTeardown('config.js', function () {
35 $('.optbox input[id], .optbox select[id], .optbox textarea[id]').off('change').off('keyup');
36 $('.optbox input[type=button][name=submit_reset]').off('click');
37 $('div.tabs_contents').off();
38 $('#import_local_storage, #export_local_storage').off('click');
39 $('form.prefs-form').off('change').off('submit');
40 $(document).off('click', 'div.click-hide-message');
41 $('#prefs_autoload').find('a').off('click');
44 AJAX.registerOnload('config.js', function () {
45 var $topmenu_upt = $('#topmenu2.user_prefs_tabs');
46 $topmenu_upt.find('li.active a').attr('rel', 'samepage');
47 $topmenu_upt.find('li:not(.active) a').attr('rel', 'newpage');
50 // default values for fields
51 var defaultValues = {};
56 * @param {Element} field
58 function getFieldType (field) {
59 var $field = $(field);
60 var tagName = $field.prop('tagName');
61 if (tagName === 'INPUT') {
62 return $field.attr('type');
63 } else if (tagName === 'SELECT') {
65 } else if (tagName === 'TEXTAREA') {
72 * Enables or disables the "restore default value" button
74 * @param {Element} field
75 * @param {boolean} display
77 function setRestoreDefaultBtn (field, display) {
78 var $el = $(field).closest('td').find('.restore-default img');
79 $el[display ? 'show' : 'hide']();
83 * Marks field depending on its value (system default or custom)
85 * @param {Element} field
87 function markField (field) {
88 var $field = $(field);
89 var type = getFieldType($field);
90 var isDefault = checkFieldDefault($field, type);
92 // checkboxes uses parent <span> for marking
93 var $fieldMarker = (type === 'checkbox') ? $field.parent() : $field;
94 setRestoreDefaultBtn($field, !isDefault);
95 $fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
101 * value must be of type:
102 * o undefined (omitted) - restore default value (form default, not PMA default)
103 * o String - if field_type is 'text'
104 * o boolean - if field_type is 'checkbox'
105 * o Array of values - if field_type is 'select'
107 * @param {Element} field
108 * @param {String} field_type see {@link #getFieldType}
109 * @param {String|Boolean} value
111 function setFieldValue (field, field_type, value) {
112 var $field = $(field);
113 switch (field_type) {
119 $field.prop('checked', value);
122 var options = $field.prop('options');
124 var imax = options.length;
125 var i, imax = options.length;
126 for (i = 0; i < imax; i++) {
127 options[i].selected = (value.indexOf(options[i].value) != -1);
137 * Will return one of:
138 * o String - if type is 'text'
139 * o boolean - if type is 'checkbox'
140 * o Array of values - if type is 'select'
142 * @param {Element} field
143 * @param {String} field_type returned by {@link #getFieldType}
144 * @type Boolean|String|String[]
146 function getFieldValue (field, field_type) {
147 var $field = $(field);
148 switch (field_type) {
151 return $field.prop('value');
153 return $field.prop('checked');
155 var options = $field.prop('options');
157 var imax = options.length;
159 for (i = 0; i < imax; i++) {
160 if (options[i].selected) {
161 items.push(options[i].value);
170 * Returns values for all fields in fieldsets
172 function getAllValues () {
173 var $elements = $('fieldset input, fieldset select, fieldset textarea');
177 for (var i = 0; i < $elements.length; i++) {
178 type = getFieldType($elements[i]);
179 value = getFieldValue($elements[i], type);
180 if (typeof value !== 'undefined') {
181 // we only have single selects, fatten array
182 if (type === 'select') {
185 values[$elements[i].name] = value;
192 * Checks whether field has its default value
194 * @param {Element} field
195 * @param {String} type
198 function checkFieldDefault (field, type) {
199 var $field = $(field);
200 var field_id = $field.attr('id');
201 if (typeof defaultValues[field_id] === 'undefined') {
204 var isDefault = true;
205 var currentValue = getFieldValue($field, type);
206 if (type !== 'select') {
207 isDefault = currentValue === defaultValues[field_id];
209 // compare arrays, will work for our representation of select values
210 if (currentValue.length !== defaultValues[field_id].length) {
213 for (var i = 0; i < currentValue.length; i++) {
214 if (currentValue[i] !== defaultValues[field_id][i]) {
225 * Returns element's id prefix
226 * @param {Element} element
228 function getIdPrefix (element) {
229 return $(element).attr('id').replace(/[^-]+$/, '');
232 // ------------------------------------------------------------------
233 // Form validation and field operations
236 // form validator assignments
239 // form validator list
241 // regexp: numeric value
242 _regexp_numeric: /^[0-9]+$/,
243 // regexp: extract parts from PCRE expression
244 _regexp_pcre_extract: /(.)(.*)\1(.*)?/,
246 * Validates positive number
248 * @param {boolean} isKeyUp
250 PMA_validatePositiveNumber: function (isKeyUp) {
251 if (isKeyUp && this.value === '') {
254 var result = this.value !== '0' && validators._regexp_numeric.test(this.value);
255 return result ? true : PMA_messages.error_nan_p;
258 * Validates non-negative number
260 * @param {boolean} isKeyUp
262 PMA_validateNonNegativeNumber: function (isKeyUp) {
263 if (isKeyUp && this.value === '') {
266 var result = validators._regexp_numeric.test(this.value);
267 return result ? true : PMA_messages.error_nan_nneg;
270 * Validates port number
272 * @param {boolean} isKeyUp
274 PMA_validatePortNumber: function (isKeyUp) {
275 if (this.value === '') {
278 var result = validators._regexp_numeric.test(this.value) && this.value !== '0';
279 return result && this.value <= 65535 ? true : PMA_messages.error_incorrect_port;
282 * Validates value according to given regular expression
284 * @param {boolean} isKeyUp
285 * @param {string} regexp
287 PMA_validateByRegex: function (isKeyUp, regexp) {
288 if (isKeyUp && this.value === '') {
291 // convert PCRE regexp
292 var parts = regexp.match(validators._regexp_pcre_extract);
293 var valid = this.value.match(new RegExp(parts[2], parts[3])) !== null;
294 return valid ? true : PMA_messages.error_invalid_value;
297 * Validates upper bound for numeric inputs
299 * @param {boolean} isKeyUp
300 * @param {int} max_value
302 PMA_validateUpperBound: function (isKeyUp, max_value) {
303 var val = parseInt(this.value, 10);
307 return val <= max_value ? true : PMA_sprintf(PMA_messages.error_value_lte, max_value);
312 // fieldset validators
318 * Registers validator for given field
320 * @param {String} id field id
321 * @param {String} type validator (key in validators object)
322 * @param {boolean} onKeyUp whether fire on key up
323 * @param {Array} params validation function parameters
325 function validateField (id, type, onKeyUp, params) {
326 if (typeof validators[type] === 'undefined') {
329 if (typeof validate[id] === 'undefined') {
332 if (validate[id].length === 0) {
333 validate[id].push([type, params, onKeyUp]);
338 * Returns validation functions associated with form field
340 * @param {String} field_id form field id
341 * @param {boolean} onKeyUpOnly see validateField
343 * @return array of [function, parameters to be passed to function]
345 function getFieldValidators (field_id, onKeyUpOnly) {
346 // look for field bound validator
347 var name = field_id && field_id.match(/[^-]+$/)[0];
348 if (typeof validators._field[name] !== 'undefined') {
349 return [[validators._field[name], null]];
352 // look for registered validators
354 if (typeof validate[field_id] !== 'undefined') {
355 // validate[field_id]: array of [type, params, onKeyUp]
356 for (var i = 0, imax = validate[field_id].length; i < imax; i++) {
357 if (onKeyUpOnly && !validate[field_id][i][2]) {
360 functions.push([validators[validate[field_id][i][0]], validate[field_id][i][1]]);
368 * Displays errors for given form fields
370 * WARNING: created DOM elements must be identical with the ones made by
371 * PhpMyAdmin\Config\FormDisplayTemplate::displayInput()!
373 * @param {Object} error_list list of errors in the form {field id: error array}
375 function displayErrors (error_list) {
376 var tempIsEmpty = function (item) {
380 for (var field_id in error_list) {
381 var errors = error_list[field_id];
382 var $field = $('#' + field_id);
383 var isFieldset = $field.attr('tagName') === 'FIELDSET';
386 $errorCnt = $field.find('dl.errors');
388 $errorCnt = $field.siblings('.inline_errors');
391 // remove empty errors (used to clear error list)
392 errors = $.grep(errors, tempIsEmpty);
396 // checkboxes uses parent <span> for marking
397 var $fieldMarker = ($field.attr('type') === 'checkbox') ? $field.parent() : $field;
398 $fieldMarker[errors.length ? 'addClass' : 'removeClass']('field-error');
402 // if error container doesn't exist, create it
403 if ($errorCnt.length === 0) {
405 $errorCnt = $('<dl class="errors" />');
406 $field.find('table').before($errorCnt);
408 $errorCnt = $('<dl class="inline_errors" />');
409 $field.closest('td').append($errorCnt);
414 for (var i = 0, imax = errors.length; i < imax; i++) {
415 html += '<dd>' + errors[i] + '</dd>';
417 $errorCnt.html(html);
418 } else if ($errorCnt !== null) {
419 // remove useless error container
426 * Validates fields and fieldsets and call displayError function as required
428 function setDisplayError() {
429 var elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
430 // run all field validators
432 for (var i = 0; i < elements.length; i++) {
433 validate_field(elements[i], false, errors);
435 // run all fieldset validators
436 $('fieldset.optbox').each(function () {
437 validate_fieldset(this, false, errors);
439 displayErrors(errors);
443 * Validates fieldset and puts errors in 'errors' object
445 * @param {Element} fieldset
446 * @param {boolean} isKeyUp
447 * @param {Object} errors
449 function validate_fieldset (fieldset, isKeyUp, errors) {
450 var $fieldset = $(fieldset);
451 if ($fieldset.length && typeof validators._fieldset[$fieldset.attr('id')] !== 'undefined') {
452 var fieldset_errors = validators._fieldset[$fieldset.attr('id')].apply($fieldset[0], [isKeyUp]);
453 for (var field_id in fieldset_errors) {
454 if (typeof errors[field_id] === 'undefined') {
455 errors[field_id] = [];
457 if (typeof fieldset_errors[field_id] === 'string') {
458 fieldset_errors[field_id] = [fieldset_errors[field_id]];
460 $.merge(errors[field_id], fieldset_errors[field_id]);
466 * Validates form field and puts errors in 'errors' object
468 * @param {Element} field
469 * @param {boolean} isKeyUp
470 * @param {Object} errors
472 function validate_field (field, isKeyUp, errors) {
475 var $field = $(field);
476 var field_id = $field.attr('id');
477 errors[field_id] = [];
478 var functions = getFieldValidators(field_id, isKeyUp);
479 for (var i = 0; i < functions.length; i++) {
480 if (typeof functions[i][1] !== 'undefined' && functions[i][1] !== null) {
481 args = functions[i][1].slice(0);
485 args.unshift(isKeyUp);
486 result = functions[i][0].apply($field[0], args);
487 if (result !== true) {
488 if (typeof result === 'string') {
491 $.merge(errors[field_id], result);
497 * Validates form field and parent fieldset
499 * @param {Element} field
500 * @param {boolean} isKeyUp
502 function validate_field_and_fieldset (field, isKeyUp) {
503 var $field = $(field);
505 validate_field($field, isKeyUp, errors);
506 validate_fieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
507 displayErrors(errors);
510 function loadInlineConfig () {
511 if (!Array.isArray(configInlineParams)) {
514 for (var i = 0; i < configInlineParams.length; ++i) {
515 if (typeof configInlineParams[i] === 'function') {
516 configInlineParams[i]();
521 function setupValidation () {
523 configScriptLoaded = true;
524 if (configScriptLoaded && typeof configInlineParams !== 'undefined') {
527 // register validators and mark custom values
528 var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
529 $elements.each(function () {
532 $el.on('change', function () {
533 validate_field_and_fieldset(this, false);
536 var tagName = $el.attr('tagName');
537 // text fields can be validated after each change
538 if (tagName === 'INPUT' && $el.attr('type') === 'text') {
539 $el.keyup(function () {
540 validate_field_and_fieldset($el, true);
544 // disable textarea spellcheck
545 if (tagName === 'TEXTAREA') {
546 $el.attr('spellcheck', false);
550 // check whether we've refreshed a page and browser remembered modified
552 var $check_page_refresh = $('#check_page_refresh');
553 if ($check_page_refresh.length === 0 || $check_page_refresh.val() === '1') {
554 // run all field validators
556 for (var i = 0; i < $elements.length; i++) {
557 validate_field($elements[i], false, errors);
559 // run all fieldset validators
560 $('fieldset.optbox').each(function () {
561 validate_fieldset(this, false, errors);
564 displayErrors(errors);
565 } else if ($check_page_refresh) {
566 $check_page_refresh.val('1');
570 AJAX.registerOnload('config.js', function () {
575 // END: Form validation and field operations
576 // ------------------------------------------------------------------
578 // ------------------------------------------------------------------
585 * @param {String} tab_id
587 function setTab (tab_id) {
588 $('ul.tabs').each(function () {
590 if (!$this.find('li a[href="#' + tab_id + '"]').length) {
593 $this.find('li').removeClass('active').find('a[href="#' + tab_id + '"]').parent().addClass('active');
594 $this.parent().find('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
595 var hashValue = 'tab_' + tab_id;
596 location.hash = hashValue;
597 $this.parent().find('input[name=tab_hash]').val(hashValue);
601 function setupConfigTabs () {
602 var forms = $('form.config-form');
603 forms.each(function () {
605 var $tabs = $this.find('ul.tabs');
609 // add tabs events and activate one tab (the first one or indicated by location hash)
610 $tabs.find('li').removeClass('active');
612 .click(function (e) {
614 setTab($(this).attr('href').substr(1));
619 $this.find('div.tabs_contents fieldset').hide().filter(':first').show();
623 function adjustPrefsNotification () {
624 var $prefsAutoLoad = $('#prefs_autoload');
625 var $tableNameControl = $('#table_name_col_no');
626 var $prefsAutoShowing = ($prefsAutoLoad.css('display') !== 'none');
628 if ($prefsAutoShowing && $tableNameControl.length) {
629 $tableNameControl.css('top', '55px');
633 AJAX.registerOnload('config.js', function () {
635 adjustPrefsNotification();
637 // tab links handling, check each 200ms
638 // (works with history in FF, further browser support here would be an overkill)
640 var tab_check_fnc = function () {
641 if (location.hash !== prev_hash) {
642 prev_hash = location.hash;
643 if (prev_hash.match(/^#tab_[a-zA-Z0-9_]+$/)) {
644 // session ID is sometimes appended here
645 var hash = prev_hash.substr(5).split('&')[0];
646 if ($('#' + hash).length) {
653 setInterval(tab_check_fnc, 200);
658 // ------------------------------------------------------------------
660 // ------------------------------------------------------------------
661 // Form reset buttons
664 AJAX.registerOnload('config.js', function () {
665 $('.optbox input[type=button][name=submit_reset]').on('click', function () {
666 var fields = $(this).closest('fieldset').find('input, select, textarea');
667 for (var i = 0, imax = fields.length; i < imax; i++) {
668 setFieldValue(fields[i], getFieldType(fields[i]), defaultValues[fields[i].id]);
675 // END: Form reset buttons
676 // ------------------------------------------------------------------
678 // ------------------------------------------------------------------
679 // "Restore default" and "set value" buttons
683 * Restores field's default value
685 * @param {String} field_id
687 function restoreField (field_id) {
688 var $field = $('#' + field_id);
689 if ($field.length === 0 || defaultValues[field_id] === undefined) {
692 setFieldValue($field, getFieldType($field), defaultValues[field_id]);
695 function setupRestoreField () {
696 $('div.tabs_contents')
697 .on('mouseenter', '.restore-default, .set-value', function () {
698 $(this).css('opacity', 1);
700 .on('mouseleave', '.restore-default, .set-value', function () {
701 $(this).css('opacity', 0.25);
703 .on('click', '.restore-default, .set-value', function (e) {
705 var href = $(this).attr('href');
707 if ($(this).hasClass('restore-default')) {
709 restoreField(field_sel.substr(1));
711 field_sel = href.match(/^[^=]+/)[0];
712 var value = href.match(/\=(.+)$/)[1];
713 setFieldValue($(field_sel), 'text', value);
715 $(field_sel).trigger('change');
717 .find('.restore-default, .set-value')
718 // inline-block for IE so opacity inheritance works
719 .css({ display: 'inline-block', opacity: 0.25 });
722 AJAX.registerOnload('config.js', function () {
727 // END: "Restore default" and "set value" buttons
728 // ------------------------------------------------------------------
730 // ------------------------------------------------------------------
731 // User preferences import/export
734 AJAX.registerOnload('config.js', function () {
735 offerPrefsAutoimport();
736 var $radios = $('#import_local_storage, #export_local_storage');
737 if (!$radios.length) {
741 // enable JavaScript dependent fields
743 .prop('disabled', false)
744 .add('#export_text_file, #import_text_file')
746 var enable_id = $(this).attr('id');
748 if (enable_id.match(/local_storage$/)) {
749 disable_id = enable_id.replace(/local_storage$/, 'text_file');
751 disable_id = enable_id.replace(/text_file$/, 'local_storage');
753 $('#opts_' + disable_id).addClass('disabled').find('input').prop('disabled', true);
754 $('#opts_' + enable_id).removeClass('disabled').find('input').prop('disabled', false);
757 // detect localStorage state
758 var ls_supported = isStorageSupported('localStorage', true);
759 var ls_exists = ls_supported ? (window.localStorage.config || false) : false;
760 $('div.localStorage-' + (ls_supported ? 'un' : '') + 'supported').hide();
761 $('div.localStorage-' + (ls_exists ? 'empty' : 'exists')).hide();
765 $('form.prefs-form').change(function () {
767 var disabled = false;
769 disabled = $form.find('input[type=radio][value$=local_storage]').prop('checked');
770 } else if (!ls_exists && $form.attr('name') === 'prefs_import' &&
771 $('#import_local_storage')[0].checked
775 $form.find('input[type=submit]').prop('disabled', disabled);
776 }).submit(function (e) {
778 if ($form.attr('name') === 'prefs_export' && $('#export_local_storage')[0].checked) {
780 // use AJAX to read JSON settings and save them
781 savePrefsToLocalStorage($form);
782 } else if ($form.attr('name') === 'prefs_import' && $('#import_local_storage')[0].checked) {
783 // set 'json' input and submit form
784 $form.find('input[name=json]').val(window.localStorage.config);
788 $(document).on('click', 'div.click-hide-message', function () {
799 * Saves user preferences to localStorage
801 * @param {Element} form
803 function savePrefsToLocalStorage (form) {
805 var submit = $form.find('input[type=submit]');
806 submit.prop('disabled', true);
808 url: 'prefs_manage.php',
813 server: PMA_commonParams.get('server'),
814 submit_get_json: true
816 success: function (data) {
817 if (typeof data !== 'undefined' && data.success === true) {
818 window.localStorage.config = data.prefs;
819 window.localStorage.config_mtime = data.mtime;
820 window.localStorage.config_mtime_local = (new Date()).toUTCString();
822 $('div.localStorage-empty').hide();
823 $('div.localStorage-exists').show();
824 var group = $form.parent('.group');
825 group.css('height', group.height() + 'px');
827 $form.prev('.click-hide-message').show('fast');
829 PMA_ajaxShowMessage(data.error);
832 complete: function () {
833 submit.prop('disabled', false);
839 * Updates preferences timestamp in Import form
841 function updatePrefsDate () {
842 var d = new Date(window.localStorage.config_mtime_local);
843 var msg = PMA_messages.strSavedOn.replace(
845 PMA_formatDateTime(d)
847 $('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
851 * Prepares message which informs that localStorage preferences are available and can be imported or deleted
853 function offerPrefsAutoimport () {
854 var has_config = (isStorageSupported('localStorage')) && (window.localStorage.config || false);
855 var $cnt = $('#prefs_autoload');
856 if (!$cnt.length || !has_config) {
859 $cnt.find('a').click(function (e) {
862 if ($a.attr('href') === '#no') {
864 $.post('index.php', {
865 server: PMA_commonParams.get('server'),
866 prefs_autoload: 'hide'
869 } else if ($a.attr('href') === '#delete') {
871 localStorage.clear();
872 $.post('index.php', {
873 server: PMA_commonParams.get('server'),
874 prefs_autoload: 'hide'
878 $cnt.find('input[name=json]').val(window.localStorage.config);
879 $cnt.find('form').submit();
885 // END: User preferences import/export
886 // ------------------------------------------------------------------