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)
16 window[type].setItem('PMATest', 'test');
17 // Check whether key-value pair was set successfully
18 if (window[type].getItem('PMATest') === 'test') {
19 // Supported, remove test variable from storage
20 window[type].removeItem('PMATest');
26 PMA_ajaxShowMessage(PMA_messages.strNoLocalStorage, false);
33 * Unbind all event handlers before tearing down a page
35 AJAX.registerTeardown('config.js', function () {
36 $('.optbox input[id], .optbox select[id], .optbox textarea[id]').off('change').off('keyup');
37 $('.optbox input[type=button][name=submit_reset]').off('click');
38 $('div.tabs_contents').off();
39 $('#import_local_storage, #export_local_storage').off('click');
40 $('form.prefs-form').off('change').off('submit');
41 $(document).off('click', 'div.click-hide-message');
42 $('#prefs_autoload').find('a').off('click');
45 AJAX.registerOnload('config.js', function () {
46 var $topmenu_upt = $('#topmenu2.user_prefs_tabs');
47 $topmenu_upt.find('li.active a').attr('rel', 'samepage');
48 $topmenu_upt.find('li:not(.active) a').attr('rel', 'newpage');
51 // default values for fields
52 var defaultValues = {};
57 * @param {Element} field
59 function getFieldType(field)
61 var $field = $(field);
62 var tagName = $field.prop('tagName');
63 if (tagName == 'INPUT') {
64 return $field.attr('type');
65 } else if (tagName == 'SELECT') {
67 } else if (tagName == 'TEXTAREA') {
74 * Enables or disables the "restore default value" button
76 * @param {Element} field
77 * @param {boolean} display
79 function setRestoreDefaultBtn(field, display)
81 var $el = $(field).closest('td').find('.restore-default img');
82 $el[display ? 'show' : 'hide']();
86 * Marks field depending on its value (system default or custom)
88 * @param {Element} field
90 function markField(field)
92 var $field = $(field);
93 var type = getFieldType($field);
94 var isDefault = checkFieldDefault($field, type);
96 // checkboxes uses parent <span> for marking
97 var $fieldMarker = (type == 'checkbox') ? $field.parent() : $field;
98 setRestoreDefaultBtn($field, !isDefault);
99 $fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
105 * value must be of type:
106 * o undefined (omitted) - restore default value (form default, not PMA default)
107 * o String - if field_type is 'text'
108 * o boolean - if field_type is 'checkbox'
109 * o Array of values - if field_type is 'select'
111 * @param {Element} field
112 * @param {String} field_type see {@link #getFieldType}
113 * @param {String|Boolean} [value]
115 function setFieldValue(field, field_type, value)
117 var $field = $(field);
118 switch (field_type) {
121 $field.val(value !== undefined ? value : $field.attr('defaultValue'));
124 $field.prop('checked', (value !== undefined ? value : $field.attr('defaultChecked')));
127 var options = $field.prop('options');
128 var i, imax = options.length;
129 if (value === undefined) {
130 for (i = 0; i < imax; i++) {
131 options[i].selected = options[i].defaultSelected;
134 for (i = 0; i < imax; i++) {
135 options[i].selected = (value.indexOf(options[i].value) != -1);
146 * Will return one of:
147 * o String - if type is 'text'
148 * o boolean - if type is 'checkbox'
149 * o Array of values - if type is 'select'
151 * @param {Element} field
152 * @param {String} field_type returned by {@link #getFieldType}
153 * @type Boolean|String|String[]
155 function getFieldValue(field, field_type)
157 var $field = $(field);
158 switch (field_type) {
161 return $field.prop('value');
163 return $field.prop('checked');
165 var options = $field.prop('options');
166 var i, imax = options.length, items = [];
167 for (i = 0; i < imax; i++) {
168 if (options[i].selected) {
169 items.push(options[i].value);
178 * Returns values for all fields in fieldsets
180 function getAllValues()
182 var $elements = $('fieldset input, fieldset select, fieldset textarea');
185 for (var i = 0; i < $elements.length; i++) {
186 type = getFieldType($elements[i]);
187 value = getFieldValue($elements[i], type);
188 if (typeof value != 'undefined') {
189 // we only have single selects, fatten array
190 if (type == 'select') {
193 values[$elements[i].name] = value;
200 * Checks whether field has its default value
202 * @param {Element} field
203 * @param {String} type
206 function checkFieldDefault(field, type)
208 var $field = $(field);
209 var field_id = $field.attr('id');
210 if (typeof defaultValues[field_id] == 'undefined') {
213 var isDefault = true;
214 var currentValue = getFieldValue($field, type);
215 if (type != 'select') {
216 isDefault = currentValue == defaultValues[field_id];
218 // compare arrays, will work for our representation of select values
219 if (currentValue.length != defaultValues[field_id].length) {
223 for (var i = 0; i < currentValue.length; i++) {
224 if (currentValue[i] != defaultValues[field_id][i]) {
235 * Returns element's id prefix
236 * @param {Element} element
238 function getIdPrefix(element)
240 return $(element).attr('id').replace(/[^-]+$/, '');
243 // ------------------------------------------------------------------
244 // Form validation and field operations
247 // form validator assignments
250 // form validator list
252 // regexp: numeric value
253 _regexp_numeric: /^[0-9]+$/,
254 // regexp: extract parts from PCRE expression
255 _regexp_pcre_extract: /(.)(.*)\1(.*)?/,
257 * Validates positive number
259 * @param {boolean} isKeyUp
261 PMA_validatePositiveNumber: function (isKeyUp) {
262 if (isKeyUp && this.value === '') {
265 var result = this.value != '0' && validators._regexp_numeric.test(this.value);
266 return result ? true : PMA_messages.error_nan_p;
269 * Validates non-negative number
271 * @param {boolean} isKeyUp
273 PMA_validateNonNegativeNumber: function (isKeyUp) {
274 if (isKeyUp && this.value === '') {
277 var result = validators._regexp_numeric.test(this.value);
278 return result ? true : PMA_messages.error_nan_nneg;
281 * Validates port number
283 * @param {boolean} isKeyUp
285 PMA_validatePortNumber: function (isKeyUp) {
286 if (this.value === '') {
289 var result = validators._regexp_numeric.test(this.value) && this.value != '0';
290 return result && this.value <= 65535 ? true : PMA_messages.error_incorrect_port;
293 * Validates value according to given regular expression
295 * @param {boolean} isKeyUp
296 * @param {string} regexp
298 PMA_validateByRegex: function (isKeyUp, regexp) {
299 if (isKeyUp && this.value === '') {
302 // convert PCRE regexp
303 var parts = regexp.match(validators._regexp_pcre_extract);
304 var valid = this.value.match(new RegExp(parts[2], parts[3])) !== null;
305 return valid ? true : PMA_messages.error_invalid_value;
308 * Validates upper bound for numeric inputs
310 * @param {boolean} isKeyUp
311 * @param {int} max_value
313 PMA_validateUpperBound: function (isKeyUp, max_value) {
314 var val = parseInt(this.value, 10);
318 return val <= max_value ? true : PMA_sprintf(PMA_messages.error_value_lte, max_value);
323 // fieldset validators
329 * Registers validator for given field
331 * @param {String} id field id
332 * @param {String} type validator (key in validators object)
333 * @param {boolean} onKeyUp whether fire on key up
334 * @param {Array} params validation function parameters
336 function validateField(id, type, onKeyUp, params)
338 if (typeof validators[type] == 'undefined') {
341 if (typeof validate[id] == 'undefined') {
344 validate[id].push([type, params, onKeyUp]);
348 * Returns validation functions associated with form field
350 * @param {String} field_id form field id
351 * @param {boolean} onKeyUpOnly see validateField
353 * @return array of [function, parameters to be passed to function]
355 function getFieldValidators(field_id, onKeyUpOnly)
357 // look for field bound validator
358 var name = field_id && field_id.match(/[^-]+$/)[0];
359 if (typeof validators._field[name] != 'undefined') {
360 return [[validators._field[name], null]];
363 // look for registered validators
365 if (typeof validate[field_id] != 'undefined') {
366 // validate[field_id]: array of [type, params, onKeyUp]
367 for (var i = 0, imax = validate[field_id].length; i < imax; i++) {
368 if (onKeyUpOnly && !validate[field_id][i][2]) {
371 functions.push([validators[validate[field_id][i][0]], validate[field_id][i][1]]);
379 * Displays errors for given form fields
381 * WARNING: created DOM elements must be identical with the ones made by
382 * display_input() in FormDisplay.tpl.php!
384 * @param {Object} error_list list of errors in the form {field id: error array}
386 function displayErrors(error_list)
388 var tempIsEmpty = function (item) {
392 for (var field_id in error_list) {
393 var errors = error_list[field_id];
394 var $field = $('#' + field_id);
395 var isFieldset = $field.attr('tagName') == 'FIELDSET';
398 $errorCnt = $field.find('dl.errors');
400 $errorCnt = $field.siblings('.inline_errors');
403 // remove empty errors (used to clear error list)
404 errors = $.grep(errors, tempIsEmpty);
408 // checkboxes uses parent <span> for marking
409 var $fieldMarker = ($field.attr('type') == 'checkbox') ? $field.parent() : $field;
410 $fieldMarker[errors.length ? 'addClass' : 'removeClass']('field-error');
414 // if error container doesn't exist, create it
415 if ($errorCnt.length === 0) {
417 $errorCnt = $('<dl class="errors" />');
418 $field.find('table').before($errorCnt);
420 $errorCnt = $('<dl class="inline_errors" />');
421 $field.closest('td').append($errorCnt);
426 for (var i = 0, imax = errors.length; i < imax; i++) {
427 html += '<dd>' + errors[i] + '</dd>';
429 $errorCnt.html(html);
430 } else if ($errorCnt !== null) {
431 // remove useless error container
438 * Validates fieldset and puts errors in 'errors' object
440 * @param {Element} fieldset
441 * @param {boolean} isKeyUp
442 * @param {Object} errors
444 function validate_fieldset(fieldset, isKeyUp, errors)
446 var $fieldset = $(fieldset);
447 if ($fieldset.length && typeof validators._fieldset[$fieldset.attr('id')] != 'undefined') {
448 var fieldset_errors = validators._fieldset[$fieldset.attr('id')].apply($fieldset[0], [isKeyUp]);
449 for (var field_id in fieldset_errors) {
450 if (typeof errors[field_id] == 'undefined') {
451 errors[field_id] = [];
453 if (typeof fieldset_errors[field_id] == 'string') {
454 fieldset_errors[field_id] = [fieldset_errors[field_id]];
456 $.merge(errors[field_id], fieldset_errors[field_id]);
462 * Validates form field and puts errors in 'errors' object
464 * @param {Element} field
465 * @param {boolean} isKeyUp
466 * @param {Object} errors
468 function validate_field(field, isKeyUp, errors)
471 var $field = $(field);
472 var field_id = $field.attr('id');
473 errors[field_id] = [];
474 var functions = getFieldValidators(field_id, isKeyUp);
475 for (var i = 0; i < functions.length; i++) {
476 if (typeof functions[i][1] !== 'undefined' && functions[i][1] !== null) {
477 args = functions[i][1].slice(0);
481 args.unshift(isKeyUp);
482 result = functions[i][0].apply($field[0], args);
483 if (result !== true) {
484 if (typeof result == 'string') {
487 $.merge(errors[field_id], result);
493 * Validates form field and parent fieldset
495 * @param {Element} field
496 * @param {boolean} isKeyUp
498 function validate_field_and_fieldset(field, isKeyUp)
500 var $field = $(field);
502 validate_field($field, isKeyUp, errors);
503 validate_fieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
504 displayErrors(errors);
507 function loadInlineConfig() {
508 if (!Array.isArray(configInlineParams)) {
511 for (var i = 0; i < configInlineParams.length; ++i) {
512 if (typeof configInlineParams[i] === 'function') {
513 configInlineParams[i]();
518 function setupValidation() {
520 configScriptLoaded = true;
521 if (configScriptLoaded && typeof configInlineParams !== "undefined") {
524 // register validators and mark custom values
525 var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
526 $elements.each(function () {
529 $el.on('change', function () {
530 validate_field_and_fieldset(this, false);
533 var tagName = $el.attr('tagName');
534 // text fields can be validated after each change
535 if (tagName == 'INPUT' && $el.attr('type') == 'text') {
536 $el.keyup(function () {
537 validate_field_and_fieldset($el, true);
541 // disable textarea spellcheck
542 if (tagName == 'TEXTAREA') {
543 $el.attr('spellcheck', false);
547 // check whether we've refreshed a page and browser remembered modified
549 var $check_page_refresh = $('#check_page_refresh');
550 if ($check_page_refresh.length === 0 || $check_page_refresh.val() == '1') {
551 // run all field validators
553 for (var i = 0; i < $elements.length; i++) {
554 validate_field($elements[i], false, errors);
556 // run all fieldset validators
557 $('fieldset.optbox').each(function () {
558 validate_fieldset(this, false, errors);
561 displayErrors(errors);
562 } else if ($check_page_refresh) {
563 $check_page_refresh.val('1');
567 AJAX.registerOnload('config.js', function () {
572 // END: Form validation and field operations
573 // ------------------------------------------------------------------
575 // ------------------------------------------------------------------
582 * @param {String} tab_id
584 function setTab(tab_id)
586 $('ul.tabs').each(function() {
588 if (!$this.find('li a[href="#' + tab_id + '"]').length) {
591 $this.find('li').removeClass('active').find('a[href="#' + tab_id + '"]').parent().addClass('active');
592 $this.parent().find('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
593 var hashValue = 'tab_' + tab_id;
594 location.hash = hashValue;
595 $this.parent().find('input[name=tab_hash]').val(hashValue);
599 function setupConfigTabs() {
600 var forms = $('form.config-form');
601 forms.each(function() {
603 var $tabs = $this.find('ul.tabs');
607 // add tabs events and activate one tab (the first one or indicated by location hash)
608 $tabs.find('li').removeClass('active');
610 .click(function (e) {
612 setTab($(this).attr('href').substr(1));
617 $this.find('div.tabs_contents fieldset').hide().filter(':first').show();
621 AJAX.registerOnload('config.js', function () {
624 // tab links handling, check each 200ms
625 // (works with history in FF, further browser support here would be an overkill)
627 var tab_check_fnc = function () {
628 if (location.hash != prev_hash) {
629 prev_hash = location.hash;
630 if (prev_hash.match(/^#tab_[a-zA-Z0-9_]+$/)) {
631 // session ID is sometimes appended here
632 var hash = prev_hash.substr(5).split('&')[0];
633 if ($('#' + hash).length) {
640 setInterval(tab_check_fnc, 200);
645 // ------------------------------------------------------------------
647 // ------------------------------------------------------------------
648 // Form reset buttons
651 AJAX.registerOnload('config.js', function () {
652 $('.optbox input[type=button][name=submit_reset]').click(function () {
653 var fields = $(this).closest('fieldset').find('input, select, textarea');
654 for (var i = 0, imax = fields.length; i < imax; i++) {
655 setFieldValue(fields[i], getFieldType(fields[i]));
661 // END: Form reset buttons
662 // ------------------------------------------------------------------
664 // ------------------------------------------------------------------
665 // "Restore default" and "set value" buttons
669 * Restores field's default value
671 * @param {String} field_id
673 function restoreField(field_id)
675 var $field = $('#' + field_id);
676 if ($field.length === 0 || defaultValues[field_id] === undefined) {
679 setFieldValue($field, getFieldType($field), defaultValues[field_id]);
682 function setupRestoreField() {
683 $('div.tabs_contents')
684 .on('mouseenter', '.restore-default, .set-value', function () {
685 $(this).css('opacity', 1);
687 .on('mouseleave', '.restore-default, .set-value', function () {
688 $(this).css('opacity', 0.25);
690 .on('click', '.restore-default, .set-value', function (e) {
692 var href = $(this).attr('href');
694 if ($(this).hasClass('restore-default')) {
696 restoreField(field_sel.substr(1));
698 field_sel = href.match(/^[^=]+/)[0];
699 var value = href.match(/\=(.+)$/)[1];
700 setFieldValue($(field_sel), 'text', value);
702 $(field_sel).trigger('change');
704 .find('.restore-default, .set-value')
705 // inline-block for IE so opacity inheritance works
706 .css({display: 'inline-block', opacity: 0.25});
709 AJAX.registerOnload('config.js', function () {
714 // END: "Restore default" and "set value" buttons
715 // ------------------------------------------------------------------
717 // ------------------------------------------------------------------
718 // User preferences import/export
721 AJAX.registerOnload('config.js', function () {
722 offerPrefsAutoimport();
723 var $radios = $('#import_local_storage, #export_local_storage');
724 if (!$radios.length) {
728 // enable JavaScript dependent fields
730 .prop('disabled', false)
731 .add('#export_text_file, #import_text_file')
733 var enable_id = $(this).attr('id');
735 if (enable_id.match(/local_storage$/)) {
736 disable_id = enable_id.replace(/local_storage$/, 'text_file');
738 disable_id = enable_id.replace(/text_file$/, 'local_storage');
740 $('#opts_' + disable_id).addClass('disabled').find('input').prop('disabled', true);
741 $('#opts_' + enable_id).removeClass('disabled').find('input').prop('disabled', false);
744 // detect localStorage state
745 var ls_supported = isStorageSupported('localStorage', true);
746 var ls_exists = ls_supported ? (window.localStorage.config || false) : false;
747 $('div.localStorage-' + (ls_supported ? 'un' : '') + 'supported').hide();
748 $('div.localStorage-' + (ls_exists ? 'empty' : 'exists')).hide();
752 $('form.prefs-form').change(function () {
754 var disabled = false;
756 disabled = $form.find('input[type=radio][value$=local_storage]').prop('checked');
757 } else if (!ls_exists && $form.attr('name') == 'prefs_import' &&
758 $('#import_local_storage')[0].checked
762 $form.find('input[type=submit]').prop('disabled', disabled);
763 }).submit(function (e) {
765 if ($form.attr('name') == 'prefs_export' && $('#export_local_storage')[0].checked) {
767 // use AJAX to read JSON settings and save them
768 savePrefsToLocalStorage($form);
769 } else if ($form.attr('name') == 'prefs_import' && $('#import_local_storage')[0].checked) {
770 // set 'json' input and submit form
771 $form.find('input[name=json]').val(window.localStorage.config);
775 $(document).on('click', 'div.click-hide-message', function () {
786 * Saves user preferences to localStorage
788 * @param {Element} form
790 function savePrefsToLocalStorage(form)
793 var submit = $form.find('input[type=submit]');
794 submit.prop('disabled', true);
796 url: 'prefs_manage.php',
801 server: PMA_commonParams.get('server'),
802 token: PMA_commonParams.get('token'),
803 submit_get_json: true
805 success: function (data) {
806 if (typeof data !== 'undefined' && data.success === true) {
807 window.localStorage.config = data.prefs;
808 window.localStorage.config_mtime = data.mtime;
809 window.localStorage.config_mtime_local = (new Date()).toUTCString();
811 $('div.localStorage-empty').hide();
812 $('div.localStorage-exists').show();
813 var group = $form.parent('.group');
814 group.css('height', group.height() + 'px');
816 $form.prev('.click-hide-message').show('fast');
818 PMA_ajaxShowMessage(data.error);
821 complete: function () {
822 submit.prop('disabled', false);
828 * Updates preferences timestamp in Import form
830 function updatePrefsDate()
832 var d = new Date(window.localStorage.config_mtime_local);
833 var msg = PMA_messages.strSavedOn.replace(
835 PMA_formatDateTime(d)
837 $('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
841 * Prepares message which informs that localStorage preferences are available and can be imported or deleted
843 function offerPrefsAutoimport()
845 var has_config = (isStorageSupported('localStorage')) && (window.localStorage.config || false);
846 var $cnt = $('#prefs_autoload');
847 if (!$cnt.length || !has_config) {
850 $cnt.find('a').click(function (e) {
853 if ($a.attr('href') == '#no') {
855 $.post('index.php', {
856 token: PMA_commonParams.get('token'),
857 server: PMA_commonParams.get('server'),
858 prefs_autoload: 'hide'
861 } else if ($a.attr('href') == '#delete') {
863 localStorage.clear();
864 $.post('index.php', {
865 token: PMA_commonParams.get('token'),
866 server: PMA_commonParams.get('server'),
867 prefs_autoload: 'hide'
871 $cnt.find('input[name=json]').val(window.localStorage.config);
872 $cnt.find('form').submit();
878 // END: User preferences import/export
879 // ------------------------------------------------------------------