1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Functions used in configuration forms and on user preferences pages
7 * Unbind all event handlers before tearing down a page
9 AJAX.registerTeardown('config.js', function () {
10 $('.optbox input[id], .optbox select[id], .optbox textarea[id]').unbind('change').unbind('keyup');
11 $('.optbox input[type=button][name=submit_reset]').unbind('click');
12 $('div.tabs_contents').undelegate();
13 $('#import_local_storage, #export_local_storage').unbind('click');
14 $('form.prefs-form').unbind('change').unbind('submit');
15 $(document).off('click', 'div.click-hide-message');
16 $('#prefs_autoload').find('a').unbind('click');
19 AJAX.registerOnload('config.js', function () {
20 var $topmenu_upt = $('#topmenu2.user_prefs_tabs');
21 $topmenu_upt.find('li.active a').attr('rel', 'samepage');
22 $topmenu_upt.find('li:not(.active) a').attr('rel', 'newpage');
25 // default values for fields
26 var defaultValues = {};
31 * @param {Element} field
33 function getFieldType(field)
35 var $field = $(field);
36 var tagName = $field.prop('tagName');
37 if (tagName == 'INPUT') {
38 return $field.attr('type');
39 } else if (tagName == 'SELECT') {
41 } else if (tagName == 'TEXTAREA') {
48 * Enables or disables the "restore default value" button
50 * @param {Element} field
51 * @param {boolean} display
53 function setRestoreDefaultBtn(field, display)
55 var $el = $(field).closest('td').find('.restore-default img');
56 $el[display ? 'show' : 'hide']();
60 * Marks field depending on its value (system default or custom)
62 * @param {Element} field
64 function markField(field)
66 var $field = $(field);
67 var type = getFieldType($field);
68 var isDefault = checkFieldDefault($field, type);
70 // checkboxes uses parent <span> for marking
71 var $fieldMarker = (type == 'checkbox') ? $field.parent() : $field;
72 setRestoreDefaultBtn($field, !isDefault);
73 $fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
79 * value must be of type:
80 * o undefined (omitted) - restore default value (form default, not PMA default)
81 * o String - if field_type is 'text'
82 * o boolean - if field_type is 'checkbox'
83 * o Array of values - if field_type is 'select'
85 * @param {Element} field
86 * @param {String} field_type see {@link #getFieldType}
87 * @param {String|Boolean} [value]
89 function setFieldValue(field, field_type, value)
91 var $field = $(field);
95 $field.val(value !== undefined ? value : $field.attr('defaultValue'));
98 $field.prop('checked', (value !== undefined ? value : $field.attr('defaultChecked')));
101 var options = $field.prop('options');
102 var i, imax = options.length;
103 if (value === undefined) {
104 for (i = 0; i < imax; i++) {
105 options[i].selected = options[i].defaultSelected;
108 for (i = 0; i < imax; i++) {
109 options[i].selected = (value.indexOf(options[i].value) != -1);
120 * Will return one of:
121 * o String - if type is 'text'
122 * o boolean - if type is 'checkbox'
123 * o Array of values - if type is 'select'
125 * @param {Element} field
126 * @param {String} field_type returned by {@link #getFieldType}
127 * @type Boolean|String|String[]
129 function getFieldValue(field, field_type)
131 var $field = $(field);
132 switch (field_type) {
135 return $field.prop('value');
137 return $field.prop('checked');
139 var options = $field.prop('options');
140 var i, imax = options.length, items = [];
141 for (i = 0; i < imax; i++) {
142 if (options[i].selected) {
143 items.push(options[i].value);
152 * Returns values for all fields in fieldsets
154 function getAllValues()
156 var $elements = $('fieldset input, fieldset select, fieldset textarea');
159 for (var i = 0; i < $elements.length; i++) {
160 type = getFieldType($elements[i]);
161 value = getFieldValue($elements[i], type);
162 if (typeof value != 'undefined') {
163 // we only have single selects, fatten array
164 if (type == 'select') {
167 values[$elements[i].name] = value;
174 * Checks whether field has its default value
176 * @param {Element} field
177 * @param {String} type
180 function checkFieldDefault(field, type)
182 var $field = $(field);
183 var field_id = $field.attr('id');
184 if (typeof defaultValues[field_id] == 'undefined') {
187 var isDefault = true;
188 var currentValue = getFieldValue($field, type);
189 if (type != 'select') {
190 isDefault = currentValue == defaultValues[field_id];
192 // compare arrays, will work for our representation of select values
193 if (currentValue.length != defaultValues[field_id].length) {
197 for (var i = 0; i < currentValue.length; i++) {
198 if (currentValue[i] != defaultValues[field_id][i]) {
209 * Returns element's id prefix
210 * @param {Element} element
212 function getIdPrefix(element)
214 return $(element).attr('id').replace(/[^-]+$/, '');
217 // ------------------------------------------------------------------
218 // Form validation and field operations
221 // form validator assignments
224 // form validator list
226 // regexp: numeric value
227 _regexp_numeric: /^[0-9]+$/,
228 // regexp: extract parts from PCRE expression
229 _regexp_pcre_extract: /(.)(.*)\1(.*)?/,
231 * Validates positive number
233 * @param {boolean} isKeyUp
235 PMA_validatePositiveNumber: function (isKeyUp) {
236 if (isKeyUp && this.value === '') {
239 var result = this.value != '0' && validators._regexp_numeric.test(this.value);
240 return result ? true : PMA_messages.error_nan_p;
243 * Validates non-negative number
245 * @param {boolean} isKeyUp
247 PMA_validateNonNegativeNumber: function (isKeyUp) {
248 if (isKeyUp && this.value === '') {
251 var result = validators._regexp_numeric.test(this.value);
252 return result ? true : PMA_messages.error_nan_nneg;
255 * Validates port number
257 * @param {boolean} isKeyUp
259 PMA_validatePortNumber: function (isKeyUp) {
260 if (this.value === '') {
263 var result = validators._regexp_numeric.test(this.value) && this.value != '0';
264 return result && this.value <= 65535 ? true : PMA_messages.error_incorrect_port;
267 * Validates value according to given regular expression
269 * @param {boolean} isKeyUp
270 * @param {string} regexp
272 PMA_validateByRegex: function (isKeyUp, regexp) {
273 if (isKeyUp && this.value === '') {
276 // convert PCRE regexp
277 var parts = regexp.match(validators._regexp_pcre_extract);
278 var valid = this.value.match(new RegExp(parts[2], parts[3])) !== null;
279 return valid ? true : PMA_messages.error_invalid_value;
282 * Validates upper bound for numeric inputs
284 * @param {boolean} isKeyUp
285 * @param {int} max_value
287 PMA_validateUpperBound: function (isKeyUp, max_value) {
288 var val = parseInt(this.value, 10);
292 return val <= max_value ? true : PMA_sprintf(PMA_messages.error_value_lte, max_value);
297 // fieldset validators
303 * Registers validator for given field
305 * @param {String} id field id
306 * @param {String} type validator (key in validators object)
307 * @param {boolean} onKeyUp whether fire on key up
308 * @param {Array} params validation function parameters
310 function validateField(id, type, onKeyUp, params)
312 if (typeof validators[type] == 'undefined') {
315 if (typeof validate[id] == 'undefined') {
318 validate[id].push([type, params, onKeyUp]);
322 * Returns validation functions associated with form field
324 * @param {String} field_id form field id
325 * @param {boolean} onKeyUpOnly see validateField
327 * @return array of [function, parameters to be passed to function]
329 function getFieldValidators(field_id, onKeyUpOnly)
331 // look for field bound validator
332 var name = field_id && field_id.match(/[^-]+$/)[0];
333 if (typeof validators._field[name] != 'undefined') {
334 return [[validators._field[name], null]];
337 // look for registered validators
339 if (typeof validate[field_id] != 'undefined') {
340 // validate[field_id]: array of [type, params, onKeyUp]
341 for (var i = 0, imax = validate[field_id].length; i < imax; i++) {
342 if (onKeyUpOnly && !validate[field_id][i][2]) {
345 functions.push([validators[validate[field_id][i][0]], validate[field_id][i][1]]);
353 * Displays errors for given form fields
355 * WARNING: created DOM elements must be identical with the ones made by
356 * display_input() in FormDisplay.tpl.php!
358 * @param {Object} error_list list of errors in the form {field id: error array}
360 function displayErrors(error_list)
362 var tempIsEmpty = function (item) {
366 for (var field_id in error_list) {
367 var errors = error_list[field_id];
368 var $field = $('#' + field_id);
369 var isFieldset = $field.attr('tagName') == 'FIELDSET';
372 $errorCnt = $field.find('dl.errors');
374 $errorCnt = $field.siblings('.inline_errors');
377 // remove empty errors (used to clear error list)
378 errors = $.grep(errors, tempIsEmpty);
382 // checkboxes uses parent <span> for marking
383 var $fieldMarker = ($field.attr('type') == 'checkbox') ? $field.parent() : $field;
384 $fieldMarker[errors.length ? 'addClass' : 'removeClass']('field-error');
388 // if error container doesn't exist, create it
389 if ($errorCnt.length === 0) {
391 $errorCnt = $('<dl class="errors" />');
392 $field.find('table').before($errorCnt);
394 $errorCnt = $('<dl class="inline_errors" />');
395 $field.closest('td').append($errorCnt);
400 for (var i = 0, imax = errors.length; i < imax; i++) {
401 html += '<dd>' + errors[i] + '</dd>';
403 $errorCnt.html(html);
404 } else if ($errorCnt !== null) {
405 // remove useless error container
412 * Validates fieldset and puts errors in 'errors' object
414 * @param {Element} fieldset
415 * @param {boolean} isKeyUp
416 * @param {Object} errors
418 function validate_fieldset(fieldset, isKeyUp, errors)
420 var $fieldset = $(fieldset);
421 if ($fieldset.length && typeof validators._fieldset[$fieldset.attr('id')] != 'undefined') {
422 var fieldset_errors = validators._fieldset[$fieldset.attr('id')].apply($fieldset[0], [isKeyUp]);
423 for (var field_id in fieldset_errors) {
424 if (typeof errors[field_id] == 'undefined') {
425 errors[field_id] = [];
427 if (typeof fieldset_errors[field_id] == 'string') {
428 fieldset_errors[field_id] = [fieldset_errors[field_id]];
430 $.merge(errors[field_id], fieldset_errors[field_id]);
436 * Validates form field and puts errors in 'errors' object
438 * @param {Element} field
439 * @param {boolean} isKeyUp
440 * @param {Object} errors
442 function validate_field(field, isKeyUp, errors)
445 var $field = $(field);
446 var field_id = $field.attr('id');
447 errors[field_id] = [];
448 var functions = getFieldValidators(field_id, isKeyUp);
449 for (var i = 0; i < functions.length; i++) {
450 if (typeof functions[i][1] !== 'undefined' && functions[i][1] !== null) {
451 args = functions[i][1].slice(0);
455 args.unshift(isKeyUp);
456 result = functions[i][0].apply($field[0], args);
457 if (result !== true) {
458 if (typeof result == 'string') {
461 $.merge(errors[field_id], result);
467 * Validates form field and parent fieldset
469 * @param {Element} field
470 * @param {boolean} isKeyUp
472 function validate_field_and_fieldset(field, isKeyUp)
474 var $field = $(field);
476 validate_field($field, isKeyUp, errors);
477 validate_fieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
478 displayErrors(errors);
481 function loadInlineConfig() {
482 if (!Array.isArray(configInlineParams)) {
485 for (var i = 0; i < configInlineParams.length; ++i) {
486 if (typeof configInlineParams[i] === 'function') {
487 configInlineParams[i]();
492 function setupValidation() {
494 configScriptLoaded = true;
495 if (configScriptLoaded && typeof configInlineParams !== "undefined") {
498 // register validators and mark custom values
499 var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
500 $elements.each(function () {
503 $el.bind('change', function () {
504 validate_field_and_fieldset(this, false);
507 var tagName = $el.attr('tagName');
508 // text fields can be validated after each change
509 if (tagName == 'INPUT' && $el.attr('type') == 'text') {
510 $el.keyup(function () {
511 validate_field_and_fieldset($el, true);
515 // disable textarea spellcheck
516 if (tagName == 'TEXTAREA') {
517 $el.attr('spellcheck', false);
521 // check whether we've refreshed a page and browser remembered modified
523 var $check_page_refresh = $('#check_page_refresh');
524 if ($check_page_refresh.length === 0 || $check_page_refresh.val() == '1') {
525 // run all field validators
527 for (var i = 0; i < $elements.length; i++) {
528 validate_field($elements[i], false, errors);
530 // run all fieldset validators
531 $('fieldset.optbox').each(function () {
532 validate_fieldset(this, false, errors);
535 displayErrors(errors);
536 } else if ($check_page_refresh) {
537 $check_page_refresh.val('1');
541 AJAX.registerOnload('config.js', function () {
546 // END: Form validation and field operations
547 // ------------------------------------------------------------------
549 // ------------------------------------------------------------------
556 * @param {String} tab_id
558 function setTab(tab_id)
560 $('ul.tabs').each(function() {
562 if (!$this.find('li a[href=#' + tab_id + ']').length) {
565 $this.find('li').removeClass('active').find('a[href=#' + tab_id + ']').parent().addClass('active');
566 $this.parent().find('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
567 location.hash = 'tab_' + tab_id;
568 $this.parent().find('input[name=tab_hash]').val(location.hash);
572 function setupConfigTabs() {
573 var forms = $('form.config-form');
574 forms.each(function() {
576 var $tabs = $this.find('ul.tabs');
580 // add tabs events and activate one tab (the first one or indicated by location hash)
581 $tabs.find('li').removeClass('active');
583 .click(function (e) {
585 setTab($(this).attr('href').substr(1));
590 $this.find('div.tabs_contents fieldset').hide().filter(':first').show();
594 AJAX.registerOnload('config.js', function () {
597 // tab links handling, check each 200ms
598 // (works with history in FF, further browser support here would be an overkill)
600 var tab_check_fnc = function () {
601 if (location.hash != prev_hash) {
602 prev_hash = location.hash;
603 if (location.hash.match(/^#tab_.+/) && $('#' + location.hash.substr(5)).length) {
604 setTab(location.hash.substr(5));
609 setInterval(tab_check_fnc, 200);
614 // ------------------------------------------------------------------
616 // ------------------------------------------------------------------
617 // Form reset buttons
620 AJAX.registerOnload('config.js', function () {
621 $('.optbox input[type=button][name=submit_reset]').click(function () {
622 var fields = $(this).closest('fieldset').find('input, select, textarea');
623 for (var i = 0, imax = fields.length; i < imax; i++) {
624 setFieldValue(fields[i], getFieldType(fields[i]));
630 // END: Form reset buttons
631 // ------------------------------------------------------------------
633 // ------------------------------------------------------------------
634 // "Restore default" and "set value" buttons
638 * Restores field's default value
640 * @param {String} field_id
642 function restoreField(field_id)
644 var $field = $('#' + field_id);
645 if ($field.length === 0 || defaultValues[field_id] === undefined) {
648 setFieldValue($field, getFieldType($field), defaultValues[field_id]);
651 function setupRestoreField() {
652 $('div.tabs_contents')
653 .delegate('.restore-default, .set-value', 'mouseenter', function () {
654 $(this).css('opacity', 1);
656 .delegate('.restore-default, .set-value', 'mouseleave', function () {
657 $(this).css('opacity', 0.25);
659 .delegate('.restore-default, .set-value', 'click', function (e) {
661 var href = $(this).attr('href');
663 if ($(this).hasClass('restore-default')) {
665 restoreField(field_sel.substr(1));
667 field_sel = href.match(/^[^=]+/)[0];
668 var value = href.match(/\=(.+)$/)[1];
669 setFieldValue($(field_sel), 'text', value);
671 $(field_sel).trigger('change');
673 .find('.restore-default, .set-value')
674 // inline-block for IE so opacity inheritance works
675 .css({display: 'inline-block', opacity: 0.25});
678 AJAX.registerOnload('config.js', function () {
683 // END: "Restore default" and "set value" buttons
684 // ------------------------------------------------------------------
686 // ------------------------------------------------------------------
687 // User preferences import/export
690 AJAX.registerOnload('config.js', function () {
691 offerPrefsAutoimport();
692 var $radios = $('#import_local_storage, #export_local_storage');
693 if (!$radios.length) {
697 // enable JavaScript dependent fields
699 .prop('disabled', false)
700 .add('#export_text_file, #import_text_file')
702 var enable_id = $(this).attr('id');
704 if (enable_id.match(/local_storage$/)) {
705 disable_id = enable_id.replace(/local_storage$/, 'text_file');
707 disable_id = enable_id.replace(/text_file$/, 'local_storage');
709 $('#opts_' + disable_id).addClass('disabled').find('input').prop('disabled', true);
710 $('#opts_' + enable_id).removeClass('disabled').find('input').prop('disabled', false);
713 // detect localStorage state
714 var ls_supported = isStorageSupported('localStorage');
715 var ls_exists = ls_supported ? (window.localStorage.config || false) : false;
716 $('div.localStorage-' + (ls_supported ? 'un' : '') + 'supported').hide();
717 $('div.localStorage-' + (ls_exists ? 'empty' : 'exists')).hide();
721 $('form.prefs-form').change(function () {
723 var disabled = false;
725 disabled = $form.find('input[type=radio][value$=local_storage]').prop('checked');
726 } else if (!ls_exists && $form.attr('name') == 'prefs_import' &&
727 $('#import_local_storage')[0].checked
731 $form.find('input[type=submit]').prop('disabled', disabled);
732 }).submit(function (e) {
734 if ($form.attr('name') == 'prefs_export' && $('#export_local_storage')[0].checked) {
736 // use AJAX to read JSON settings and save them
737 savePrefsToLocalStorage($form);
738 } else if ($form.attr('name') == 'prefs_import' && $('#import_local_storage')[0].checked) {
739 // set 'json' input and submit form
740 $form.find('input[name=json]').val(window.localStorage.config);
744 $(document).on('click', 'div.click-hide-message', function () {
755 * Saves user preferences to localStorage
757 * @param {Element} form
759 function savePrefsToLocalStorage(form)
762 var submit = $form.find('input[type=submit]');
763 submit.prop('disabled', true);
765 url: 'prefs_manage.php',
770 server: $form.find('input[name=server]').val(),
771 token: $form.find('input[name=token]').val(),
772 submit_get_json: true
774 success: function (data) {
775 if (typeof data !== 'undefined' && data.success === true) {
776 window.localStorage.config = data.prefs;
777 window.localStorage.config_mtime = data.mtime;
778 window.localStorage.config_mtime_local = (new Date()).toUTCString();
780 $('div.localStorage-empty').hide();
781 $('div.localStorage-exists').show();
782 var group = $form.parent('.group');
783 group.css('height', group.height() + 'px');
785 $form.prev('.click-hide-message').show('fast');
787 PMA_ajaxShowMessage(data.error);
790 complete: function () {
791 submit.prop('disabled', false);
797 * Updates preferences timestamp in Import form
799 function updatePrefsDate()
801 var d = new Date(window.localStorage.config_mtime_local);
802 var msg = PMA_messages.strSavedOn.replace(
804 PMA_formatDateTime(d)
806 $('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
810 * Prepares message which informs that localStorage preferences are available and can be imported
812 function offerPrefsAutoimport()
814 var has_config = (isStorageSupported('localStorage')) && (window.localStorage.config || false);
815 var $cnt = $('#prefs_autoload');
816 if (!$cnt.length || !has_config) {
819 $cnt.find('a').click(function (e) {
822 if ($a.attr('href') == '#no') {
824 $.post('index.php', {
825 token: $cnt.find('input[name=token]').val(),
826 prefs_autoload: 'hide'
830 $cnt.find('input[name=json]').val(window.localStorage.config);
831 $cnt.find('form').submit();
837 // END: User preferences import/export
838 // ------------------------------------------------------------------