Revert "Login screen improvements and added favicon (#227)"
[openemr.git] / phpmyadmin / js / config.js
blob61e448129625ecef62675e1656085fe83c757f35
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * Functions used in configuration forms and on user preferences pages
4  */
6 /**
7  * Unbind all event handlers before tearing down a page
8  */
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');
17 });
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');
23 });
25 // default values for fields
26 var defaultValues = {};
28 /**
29  * Returns field type
30  *
31  * @param {Element} field
32  */
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') {
40         return 'select';
41     } else if (tagName == 'TEXTAREA') {
42         return 'text';
43     }
44     return '';
47 /**
48  * Enables or disables the "restore default value" button
49  *
50  * @param {Element} field
51  * @param {boolean} display
52  */
53 function setRestoreDefaultBtn(field, display)
55     var $el = $(field).closest('td').find('.restore-default img');
56     $el[display ? 'show' : 'hide']();
59 /**
60  * Marks field depending on its value (system default or custom)
61  *
62  * @param {Element} field
63  */
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');
76 /**
77  * Sets field value
78  *
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'
84  *
85  * @param {Element} field
86  * @param {String}  field_type  see {@link #getFieldType}
87  * @param {String|Boolean}  [value]
88  */
89 function setFieldValue(field, field_type, value)
91     var $field = $(field);
92     switch (field_type) {
93     case 'text':
94     case 'number':
95         $field.val(value !== undefined ? value : $field.attr('defaultValue'));
96         break;
97     case 'checkbox':
98         $field.prop('checked', (value !== undefined ? value : $field.attr('defaultChecked')));
99         break;
100     case 'select':
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;
106             }
107         } else {
108             for (i = 0; i < imax; i++) {
109                 options[i].selected = (value.indexOf(options[i].value) != -1);
110             }
111         }
112         break;
113     }
114     markField($field);
118  * Gets field value
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[]
128  */
129 function getFieldValue(field, field_type)
131     var $field = $(field);
132     switch (field_type) {
133     case 'text':
134     case 'number':
135         return $field.prop('value');
136     case 'checkbox':
137         return $field.prop('checked');
138     case 'select':
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);
144             }
145         }
146         return items;
147     }
148     return null;
152  * Returns values for all fields in fieldsets
153  */
154 function getAllValues()
156     var $elements = $('fieldset input, fieldset select, fieldset textarea');
157     var values = {};
158     var type, value;
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') {
165                 value = value[0];
166             }
167             values[$elements[i].name] = value;
168         }
169     }
170     return values;
174  * Checks whether field has its default value
176  * @param {Element} field
177  * @param {String}  type
178  * @return boolean
179  */
180 function checkFieldDefault(field, type)
182     var $field = $(field);
183     var field_id = $field.attr('id');
184     if (typeof defaultValues[field_id] == 'undefined') {
185         return true;
186     }
187     var isDefault = true;
188     var currentValue = getFieldValue($field, type);
189     if (type != 'select') {
190         isDefault = currentValue == defaultValues[field_id];
191     } else {
192         // compare arrays, will work for our representation of select values
193         if (currentValue.length != defaultValues[field_id].length) {
194             isDefault = false;
195         }
196         else {
197             for (var i = 0; i < currentValue.length; i++) {
198                 if (currentValue[i] != defaultValues[field_id][i]) {
199                     isDefault = false;
200                     break;
201                 }
202             }
203         }
204     }
205     return isDefault;
209  * Returns element's id prefix
210  * @param {Element} element
211  */
212 function getIdPrefix(element)
214     return $(element).attr('id').replace(/[^-]+$/, '');
217 // ------------------------------------------------------------------
218 // Form validation and field operations
221 // form validator assignments
222 var validate = {};
224 // form validator list
225 var validators = {
226     // regexp: numeric value
227     _regexp_numeric: /^[0-9]+$/,
228     // regexp: extract parts from PCRE expression
229     _regexp_pcre_extract: /(.)(.*)\1(.*)?/,
230     /**
231      * Validates positive number
232      *
233      * @param {boolean} isKeyUp
234      */
235     PMA_validatePositiveNumber: function (isKeyUp) {
236         if (isKeyUp && this.value === '') {
237             return true;
238         }
239         var result = this.value != '0' && validators._regexp_numeric.test(this.value);
240         return result ? true : PMA_messages.error_nan_p;
241     },
242     /**
243      * Validates non-negative number
244      *
245      * @param {boolean} isKeyUp
246      */
247     PMA_validateNonNegativeNumber: function (isKeyUp) {
248         if (isKeyUp && this.value === '') {
249             return true;
250         }
251         var result = validators._regexp_numeric.test(this.value);
252         return result ? true : PMA_messages.error_nan_nneg;
253     },
254     /**
255      * Validates port number
256      *
257      * @param {boolean} isKeyUp
258      */
259     PMA_validatePortNumber: function (isKeyUp) {
260         if (this.value === '') {
261             return true;
262         }
263         var result = validators._regexp_numeric.test(this.value) && this.value != '0';
264         return result && this.value <= 65535 ? true : PMA_messages.error_incorrect_port;
265     },
266     /**
267      * Validates value according to given regular expression
268      *
269      * @param {boolean} isKeyUp
270      * @param {string}  regexp
271      */
272     PMA_validateByRegex: function (isKeyUp, regexp) {
273         if (isKeyUp && this.value === '') {
274             return true;
275         }
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;
280     },
281     /**
282      * Validates upper bound for numeric inputs
283      *
284      * @param {boolean} isKeyUp
285      * @param {int} max_value
286      */
287     PMA_validateUpperBound: function (isKeyUp, max_value) {
288         var val = parseInt(this.value, 10);
289         if (isNaN(val)) {
290             return true;
291         }
292         return val <= max_value ? true : PMA_sprintf(PMA_messages.error_value_lte, max_value);
293     },
294     // field validators
295     _field: {
296     },
297     // fieldset validators
298     _fieldset: {
299     }
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
309  */
310 function validateField(id, type, onKeyUp, params)
312     if (typeof validators[type] == 'undefined') {
313         return;
314     }
315     if (typeof validate[id] == 'undefined') {
316         validate[id] = [];
317     }
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
326  * @type Array
327  * @return array of [function, parameters to be passed to function]
328  */
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]];
335     }
337     // look for registered validators
338     var functions = [];
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]) {
343                 continue;
344             }
345             functions.push([validators[validate[field_id][i][0]], validate[field_id][i][1]]);
346         }
347     }
349     return functions;
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}
359  */
360 function displayErrors(error_list)
362     var tempIsEmpty = function (item) {
363         return item !== '';
364     };
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';
370         var $errorCnt;
371         if (isFieldset) {
372             $errorCnt = $field.find('dl.errors');
373         } else {
374             $errorCnt = $field.siblings('.inline_errors');
375         }
377         // remove empty errors (used to clear error list)
378         errors = $.grep(errors, tempIsEmpty);
380         // CSS error class
381         if (!isFieldset) {
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');
385         }
387         if (errors.length) {
388             // if error container doesn't exist, create it
389             if ($errorCnt.length === 0) {
390                 if (isFieldset) {
391                     $errorCnt = $('<dl class="errors" />');
392                     $field.find('table').before($errorCnt);
393                 } else {
394                     $errorCnt = $('<dl class="inline_errors" />');
395                     $field.closest('td').append($errorCnt);
396                 }
397             }
399             var html = '';
400             for (var i = 0, imax = errors.length; i < imax; i++) {
401                 html += '<dd>' + errors[i] + '</dd>';
402             }
403             $errorCnt.html(html);
404         } else if ($errorCnt !== null) {
405             // remove useless error container
406             $errorCnt.remove();
407         }
408     }
412  * Validates fieldset and puts errors in 'errors' object
414  * @param {Element} fieldset
415  * @param {boolean} isKeyUp
416  * @param {Object}  errors
417  */
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] = [];
426             }
427             if (typeof fieldset_errors[field_id] == 'string') {
428                 fieldset_errors[field_id] = [fieldset_errors[field_id]];
429             }
430             $.merge(errors[field_id], fieldset_errors[field_id]);
431         }
432     }
436  * Validates form field and puts errors in 'errors' object
438  * @param {Element} field
439  * @param {boolean} isKeyUp
440  * @param {Object}  errors
441  */
442 function validate_field(field, isKeyUp, errors)
444     var args, result;
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);
452         } else {
453             args = [];
454         }
455         args.unshift(isKeyUp);
456         result = functions[i][0].apply($field[0], args);
457         if (result !== true) {
458             if (typeof result == 'string') {
459                 result = [result];
460             }
461             $.merge(errors[field_id], result);
462         }
463     }
467  * Validates form field and parent fieldset
469  * @param {Element} field
470  * @param {boolean} isKeyUp
471  */
472 function validate_field_and_fieldset(field, isKeyUp)
474     var $field = $(field);
475     var errors = {};
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)) {
483         return;
484     }
485     for (var i = 0; i < configInlineParams.length; ++i) {
486         if (typeof configInlineParams[i] === 'function') {
487             configInlineParams[i]();
488         }
489     }
492 function setupValidation() {
493     validate = {};
494     configScriptLoaded = true;
495     if (configScriptLoaded && typeof configInlineParams !== "undefined") {
496         loadInlineConfig();
497     }
498     // register validators and mark custom values
499     var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
500     $elements.each(function () {
501         markField(this);
502         var $el = $(this);
503         $el.bind('change', function () {
504             validate_field_and_fieldset(this, false);
505             markField(this);
506         });
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);
512                 markField($el);
513             });
514         }
515         // disable textarea spellcheck
516         if (tagName == 'TEXTAREA') {
517             $el.attr('spellcheck', false);
518         }
519     });
521     // check whether we've refreshed a page and browser remembered modified
522     // form values
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
526         var errors = {};
527         for (var i = 0; i < $elements.length; i++) {
528             validate_field($elements[i], false, errors);
529         }
530         // run all fieldset validators
531         $('fieldset.optbox').each(function () {
532             validate_fieldset(this, false, errors);
533         });
535         displayErrors(errors);
536     } else if ($check_page_refresh) {
537         $check_page_refresh.val('1');
538     }
541 AJAX.registerOnload('config.js', function () {
542     setupValidation();
546 // END: Form validation and field operations
547 // ------------------------------------------------------------------
549 // ------------------------------------------------------------------
550 // Tabbed forms
554  * Sets active tab
556  * @param {String} tab_id
557  */
558 function setTab(tab_id)
560     $('ul.tabs').each(function() {
561         var $this = $(this);
562         if (!$this.find('li a[href=#' + tab_id + ']').length) {
563             return;
564         }
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);
569     });
572 function setupConfigTabs() {
573     var forms = $('form.config-form');
574     forms.each(function() {
575         var $this = $(this);
576         var $tabs = $this.find('ul.tabs');
577         if (!$tabs.length) {
578             return;
579         }
580         // add tabs events and activate one tab (the first one or indicated by location hash)
581         $tabs.find('li').removeClass('active');
582         $tabs.find('a')
583             .click(function (e) {
584                 e.preventDefault();
585                 setTab($(this).attr('href').substr(1));
586             })
587             .filter(':first')
588             .parent()
589             .addClass('active');
590         $this.find('div.tabs_contents fieldset').hide().filter(':first').show();
591     });
594 AJAX.registerOnload('config.js', function () {
595     setupConfigTabs();
597     // tab links handling, check each 200ms
598     // (works with history in FF, further browser support here would be an overkill)
599     var prev_hash;
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));
605             }
606         }
607     };
608     tab_check_fnc();
609     setInterval(tab_check_fnc, 200);
613 // END: Tabbed forms
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]));
625         }
626     });
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
641  */
642 function restoreField(field_id)
644     var $field = $('#' + field_id);
645     if ($field.length === 0 || defaultValues[field_id] === undefined) {
646         return;
647     }
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);
655         })
656         .delegate('.restore-default, .set-value', 'mouseleave', function () {
657             $(this).css('opacity', 0.25);
658         })
659         .delegate('.restore-default, .set-value', 'click', function (e) {
660             e.preventDefault();
661             var href = $(this).attr('href');
662             var field_sel;
663             if ($(this).hasClass('restore-default')) {
664                 field_sel = href;
665                 restoreField(field_sel.substr(1));
666             } else {
667                 field_sel = href.match(/^[^=]+/)[0];
668                 var value = href.match(/\=(.+)$/)[1];
669                 setFieldValue($(field_sel), 'text', value);
670             }
671             $(field_sel).trigger('change');
672         })
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 () {
679     setupRestoreField();
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) {
694         return;
695     }
697     // enable JavaScript dependent fields
698     $radios
699         .prop('disabled', false)
700         .add('#export_text_file, #import_text_file')
701         .click(function () {
702             var enable_id = $(this).attr('id');
703             var disable_id;
704             if (enable_id.match(/local_storage$/)) {
705                 disable_id = enable_id.replace(/local_storage$/, 'text_file');
706             } else {
707                 disable_id = enable_id.replace(/text_file$/, 'local_storage');
708             }
709             $('#opts_' + disable_id).addClass('disabled').find('input').prop('disabled', true);
710             $('#opts_' + enable_id).removeClass('disabled').find('input').prop('disabled', false);
711         });
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();
718     if (ls_exists) {
719         updatePrefsDate();
720     }
721     $('form.prefs-form').change(function () {
722         var $form = $(this);
723         var disabled = false;
724         if (!ls_supported) {
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
728             ) {
729             disabled = true;
730         }
731         $form.find('input[type=submit]').prop('disabled', disabled);
732     }).submit(function (e) {
733         var $form = $(this);
734         if ($form.attr('name') == 'prefs_export' && $('#export_local_storage')[0].checked) {
735             e.preventDefault();
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);
741         }
742     });
744     $(document).on('click', 'div.click-hide-message', function () {
745         $(this)
746         .hide()
747         .parent('.group')
748         .css('height', '')
749         .next('form')
750         .show();
751     });
755  * Saves user preferences to localStorage
757  * @param {Element} form
758  */
759 function savePrefsToLocalStorage(form)
761     $form = $(form);
762     var submit = $form.find('input[type=submit]');
763     submit.prop('disabled', true);
764     $.ajax({
765         url: 'prefs_manage.php',
766         cache: false,
767         type: 'POST',
768         data: {
769             ajax_request: true,
770             server: $form.find('input[name=server]').val(),
771             token: $form.find('input[name=token]').val(),
772             submit_get_json: true
773         },
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();
779                 updatePrefsDate();
780                 $('div.localStorage-empty').hide();
781                 $('div.localStorage-exists').show();
782                 var group = $form.parent('.group');
783                 group.css('height', group.height() + 'px');
784                 $form.hide('fast');
785                 $form.prev('.click-hide-message').show('fast');
786             } else {
787                 PMA_ajaxShowMessage(data.error);
788             }
789         },
790         complete: function () {
791             submit.prop('disabled', false);
792         }
793     });
797  * Updates preferences timestamp in Import form
798  */
799 function updatePrefsDate()
801     var d = new Date(window.localStorage.config_mtime_local);
802     var msg = PMA_messages.strSavedOn.replace(
803         '@DATE@',
804         PMA_formatDateTime(d)
805     );
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
811  */
812 function offerPrefsAutoimport()
814     var has_config = (isStorageSupported('localStorage')) && (window.localStorage.config || false);
815     var $cnt = $('#prefs_autoload');
816     if (!$cnt.length || !has_config) {
817         return;
818     }
819     $cnt.find('a').click(function (e) {
820         e.preventDefault();
821         var $a = $(this);
822         if ($a.attr('href') == '#no') {
823             $cnt.remove();
824             $.post('index.php', {
825                 token: $cnt.find('input[name=token]').val(),
826                 prefs_autoload: 'hide'
827             });
828             return;
829         }
830         $cnt.find('input[name=json]').val(window.localStorage.config);
831         $cnt.find('form').submit();
832     });
833     $cnt.show();
837 // END: User preferences import/export
838 // ------------------------------------------------------------------