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 validate[id].push([type, params, onKeyUp]);
336 * Returns validation functions associated with form field
338 * @param {String} field_id form field id
339 * @param {boolean} onKeyUpOnly see validateField
341 * @return array of [function, parameters to be passed to function]
343 function getFieldValidators (field_id, onKeyUpOnly) {
344 // look for field bound validator
345 var name = field_id && field_id.match(/[^-]+$/)[0];
346 if (typeof validators._field[name] !== 'undefined') {
347 return [[validators._field[name], null]];
350 // look for registered validators
352 if (typeof validate[field_id] !== 'undefined') {
353 // validate[field_id]: array of [type, params, onKeyUp]
354 for (var i = 0, imax = validate[field_id].length; i < imax; i++) {
355 if (onKeyUpOnly && !validate[field_id][i][2]) {
358 functions.push([validators[validate[field_id][i][0]], validate[field_id][i][1]]);
366 * Displays errors for given form fields
368 * WARNING: created DOM elements must be identical with the ones made by
369 * PhpMyAdmin\Config\FormDisplayTemplate::displayInput()!
371 * @param {Object} error_list list of errors in the form {field id: error array}
373 function displayErrors (error_list) {
374 var tempIsEmpty = function (item) {
378 for (var field_id in error_list) {
379 var errors = error_list[field_id];
380 var $field = $('#' + field_id);
381 var isFieldset = $field.attr('tagName') === 'FIELDSET';
384 $errorCnt = $field.find('dl.errors');
386 $errorCnt = $field.siblings('.inline_errors');
389 // remove empty errors (used to clear error list)
390 errors = $.grep(errors, tempIsEmpty);
394 // checkboxes uses parent <span> for marking
395 var $fieldMarker = ($field.attr('type') === 'checkbox') ? $field.parent() : $field;
396 $fieldMarker[errors.length ? 'addClass' : 'removeClass']('field-error');
400 // if error container doesn't exist, create it
401 if ($errorCnt.length === 0) {
403 $errorCnt = $('<dl class="errors" />');
404 $field.find('table').before($errorCnt);
406 $errorCnt = $('<dl class="inline_errors" />');
407 $field.closest('td').append($errorCnt);
412 for (var i = 0, imax = errors.length; i < imax; i++) {
413 html += '<dd>' + errors[i] + '</dd>';
415 $errorCnt.html(html);
416 } else if ($errorCnt !== null) {
417 // remove useless error container
424 * Validates fieldset and puts errors in 'errors' object
426 * @param {Element} fieldset
427 * @param {boolean} isKeyUp
428 * @param {Object} errors
430 function validate_fieldset (fieldset, isKeyUp, errors) {
431 var $fieldset = $(fieldset);
432 if ($fieldset.length && typeof validators._fieldset[$fieldset.attr('id')] !== 'undefined') {
433 var fieldset_errors = validators._fieldset[$fieldset.attr('id')].apply($fieldset[0], [isKeyUp]);
434 for (var field_id in fieldset_errors) {
435 if (typeof errors[field_id] === 'undefined') {
436 errors[field_id] = [];
438 if (typeof fieldset_errors[field_id] === 'string') {
439 fieldset_errors[field_id] = [fieldset_errors[field_id]];
441 $.merge(errors[field_id], fieldset_errors[field_id]);
447 * Validates form field and puts errors in 'errors' object
449 * @param {Element} field
450 * @param {boolean} isKeyUp
451 * @param {Object} errors
453 function validate_field (field, isKeyUp, errors) {
456 var $field = $(field);
457 var field_id = $field.attr('id');
458 errors[field_id] = [];
459 var functions = getFieldValidators(field_id, isKeyUp);
460 for (var i = 0; i < functions.length; i++) {
461 if (typeof functions[i][1] !== 'undefined' && functions[i][1] !== null) {
462 args = functions[i][1].slice(0);
466 args.unshift(isKeyUp);
467 result = functions[i][0].apply($field[0], args);
468 if (result !== true) {
469 if (typeof result === 'string') {
472 $.merge(errors[field_id], result);
478 * Validates form field and parent fieldset
480 * @param {Element} field
481 * @param {boolean} isKeyUp
483 function validate_field_and_fieldset (field, isKeyUp) {
484 var $field = $(field);
486 validate_field($field, isKeyUp, errors);
487 validate_fieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
488 displayErrors(errors);
491 function loadInlineConfig () {
492 if (!Array.isArray(configInlineParams)) {
495 for (var i = 0; i < configInlineParams.length; ++i) {
496 if (typeof configInlineParams[i] === 'function') {
497 configInlineParams[i]();
502 function setupValidation () {
504 configScriptLoaded = true;
505 if (configScriptLoaded && typeof configInlineParams !== 'undefined') {
508 // register validators and mark custom values
509 var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
510 $elements.each(function () {
513 $el.on('change', function () {
514 validate_field_and_fieldset(this, false);
517 var tagName = $el.attr('tagName');
518 // text fields can be validated after each change
519 if (tagName === 'INPUT' && $el.attr('type') === 'text') {
520 $el.keyup(function () {
521 validate_field_and_fieldset($el, true);
525 // disable textarea spellcheck
526 if (tagName === 'TEXTAREA') {
527 $el.attr('spellcheck', false);
531 // check whether we've refreshed a page and browser remembered modified
533 var $check_page_refresh = $('#check_page_refresh');
534 if ($check_page_refresh.length === 0 || $check_page_refresh.val() === '1') {
535 // run all field validators
537 for (var i = 0; i < $elements.length; i++) {
538 validate_field($elements[i], false, errors);
540 // run all fieldset validators
541 $('fieldset.optbox').each(function () {
542 validate_fieldset(this, false, errors);
545 displayErrors(errors);
546 } else if ($check_page_refresh) {
547 $check_page_refresh.val('1');
551 AJAX.registerOnload('config.js', function () {
556 // END: Form validation and field operations
557 // ------------------------------------------------------------------
559 // ------------------------------------------------------------------
566 * @param {String} tab_id
568 function setTab (tab_id) {
569 $('ul.tabs').each(function () {
571 if (!$this.find('li a[href="#' + tab_id + '"]').length) {
574 $this.find('li').removeClass('active').find('a[href="#' + tab_id + '"]').parent().addClass('active');
575 $this.parent().find('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
576 var hashValue = 'tab_' + tab_id;
577 location.hash = hashValue;
578 $this.parent().find('input[name=tab_hash]').val(hashValue);
582 function setupConfigTabs () {
583 var forms = $('form.config-form');
584 forms.each(function () {
586 var $tabs = $this.find('ul.tabs');
590 // add tabs events and activate one tab (the first one or indicated by location hash)
591 $tabs.find('li').removeClass('active');
593 .click(function (e) {
595 setTab($(this).attr('href').substr(1));
600 $this.find('div.tabs_contents fieldset').hide().filter(':first').show();
604 function adjustPrefsNotification () {
605 var $prefsAutoLoad = $('#prefs_autoload');
606 var $tableNameControl = $('#table_name_col_no');
607 var $prefsAutoShowing = ($prefsAutoLoad.css('display') !== 'none');
609 if ($prefsAutoShowing && $tableNameControl.length) {
610 $tableNameControl.css('top', '55px');
614 AJAX.registerOnload('config.js', function () {
616 adjustPrefsNotification();
618 // tab links handling, check each 200ms
619 // (works with history in FF, further browser support here would be an overkill)
621 var tab_check_fnc = function () {
622 if (location.hash !== prev_hash) {
623 prev_hash = location.hash;
624 if (prev_hash.match(/^#tab_[a-zA-Z0-9_]+$/)) {
625 // session ID is sometimes appended here
626 var hash = prev_hash.substr(5).split('&')[0];
627 if ($('#' + hash).length) {
634 setInterval(tab_check_fnc, 200);
639 // ------------------------------------------------------------------
641 // ------------------------------------------------------------------
642 // Form reset buttons
645 AJAX.registerOnload('config.js', function () {
646 $('.optbox input[type=button][name=submit_reset]').on('click', function () {
647 var fields = $(this).closest('fieldset').find('input, select, textarea');
648 for (var i = 0, imax = fields.length; i < imax; i++) {
649 setFieldValue(fields[i], getFieldType(fields[i]), defaultValues[fields[i].id]);
655 // END: Form reset buttons
656 // ------------------------------------------------------------------
658 // ------------------------------------------------------------------
659 // "Restore default" and "set value" buttons
663 * Restores field's default value
665 * @param {String} field_id
667 function restoreField (field_id) {
668 var $field = $('#' + field_id);
669 if ($field.length === 0 || defaultValues[field_id] === undefined) {
672 setFieldValue($field, getFieldType($field), defaultValues[field_id]);
675 function setupRestoreField () {
676 $('div.tabs_contents')
677 .on('mouseenter', '.restore-default, .set-value', function () {
678 $(this).css('opacity', 1);
680 .on('mouseleave', '.restore-default, .set-value', function () {
681 $(this).css('opacity', 0.25);
683 .on('click', '.restore-default, .set-value', function (e) {
685 var href = $(this).attr('href');
687 if ($(this).hasClass('restore-default')) {
689 restoreField(field_sel.substr(1));
691 field_sel = href.match(/^[^=]+/)[0];
692 var value = href.match(/\=(.+)$/)[1];
693 setFieldValue($(field_sel), 'text', value);
695 $(field_sel).trigger('change');
697 .find('.restore-default, .set-value')
698 // inline-block for IE so opacity inheritance works
699 .css({ display: 'inline-block', opacity: 0.25 });
702 AJAX.registerOnload('config.js', function () {
707 // END: "Restore default" and "set value" buttons
708 // ------------------------------------------------------------------
710 // ------------------------------------------------------------------
711 // User preferences import/export
714 AJAX.registerOnload('config.js', function () {
715 offerPrefsAutoimport();
716 var $radios = $('#import_local_storage, #export_local_storage');
717 if (!$radios.length) {
721 // enable JavaScript dependent fields
723 .prop('disabled', false)
724 .add('#export_text_file, #import_text_file')
726 var enable_id = $(this).attr('id');
728 if (enable_id.match(/local_storage$/)) {
729 disable_id = enable_id.replace(/local_storage$/, 'text_file');
731 disable_id = enable_id.replace(/text_file$/, 'local_storage');
733 $('#opts_' + disable_id).addClass('disabled').find('input').prop('disabled', true);
734 $('#opts_' + enable_id).removeClass('disabled').find('input').prop('disabled', false);
737 // detect localStorage state
738 var ls_supported = isStorageSupported('localStorage', true);
739 var ls_exists = ls_supported ? (window.localStorage.config || false) : false;
740 $('div.localStorage-' + (ls_supported ? 'un' : '') + 'supported').hide();
741 $('div.localStorage-' + (ls_exists ? 'empty' : 'exists')).hide();
745 $('form.prefs-form').change(function () {
747 var disabled = false;
749 disabled = $form.find('input[type=radio][value$=local_storage]').prop('checked');
750 } else if (!ls_exists && $form.attr('name') === 'prefs_import' &&
751 $('#import_local_storage')[0].checked
755 $form.find('input[type=submit]').prop('disabled', disabled);
756 }).submit(function (e) {
758 if ($form.attr('name') === 'prefs_export' && $('#export_local_storage')[0].checked) {
760 // use AJAX to read JSON settings and save them
761 savePrefsToLocalStorage($form);
762 } else if ($form.attr('name') === 'prefs_import' && $('#import_local_storage')[0].checked) {
763 // set 'json' input and submit form
764 $form.find('input[name=json]').val(window.localStorage.config);
768 $(document).on('click', 'div.click-hide-message', function () {
779 * Saves user preferences to localStorage
781 * @param {Element} form
783 function savePrefsToLocalStorage (form) {
785 var submit = $form.find('input[type=submit]');
786 submit.prop('disabled', true);
788 url: 'prefs_manage.php',
793 server: PMA_commonParams.get('server'),
794 submit_get_json: true
796 success: function (data) {
797 if (typeof data !== 'undefined' && data.success === true) {
798 window.localStorage.config = data.prefs;
799 window.localStorage.config_mtime = data.mtime;
800 window.localStorage.config_mtime_local = (new Date()).toUTCString();
802 $('div.localStorage-empty').hide();
803 $('div.localStorage-exists').show();
804 var group = $form.parent('.group');
805 group.css('height', group.height() + 'px');
807 $form.prev('.click-hide-message').show('fast');
809 PMA_ajaxShowMessage(data.error);
812 complete: function () {
813 submit.prop('disabled', false);
819 * Updates preferences timestamp in Import form
821 function updatePrefsDate () {
822 var d = new Date(window.localStorage.config_mtime_local);
823 var msg = PMA_messages.strSavedOn.replace(
825 PMA_formatDateTime(d)
827 $('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
831 * Prepares message which informs that localStorage preferences are available and can be imported or deleted
833 function offerPrefsAutoimport () {
834 var has_config = (isStorageSupported('localStorage')) && (window.localStorage.config || false);
835 var $cnt = $('#prefs_autoload');
836 if (!$cnt.length || !has_config) {
839 $cnt.find('a').click(function (e) {
842 if ($a.attr('href') === '#no') {
844 $.post('index.php', {
845 server: PMA_commonParams.get('server'),
846 prefs_autoload: 'hide'
849 } else if ($a.attr('href') === '#delete') {
851 localStorage.clear();
852 $.post('index.php', {
853 server: PMA_commonParams.get('server'),
854 prefs_autoload: 'hide'
858 $cnt.find('input[name=json]').val(window.localStorage.config);
859 $cnt.find('form').submit();
865 // END: User preferences import/export
866 // ------------------------------------------------------------------