Translation update done using Pootle.
[phpmyadmin-themes.git] / libraries / config / FormDisplay.class.php
blob9e84075c1f3a6aecf9946c53d89fb95b754b1e75
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Form management class, displays and processes forms
6 * Explanation of used terms:
7 * o work_path - original field path, eg. Servers/4/verbose
8 * o system_path - work_path modified so that it points to the first server, eg. Servers/1/verbose
9 * o translated_path - work_path modified for HTML field name, a path with
10 * slashes changed to hyphens, eg. Servers-4-verbose
12 * @package phpMyAdmin
15 /**
16 * Core libraries.
18 require_once './libraries/config/FormDisplay.tpl.php';
19 require_once './libraries/config/validate.lib.php';
20 require_once './libraries/js_escape.lib.php';
22 /**
23 * Form management class, displays and processes forms
24 * @package phpMyAdmin-setup
26 class FormDisplay
28 /**
29 * Form list
30 * @var Form[]
32 private $forms = array();
34 /**
35 * Stores validation errors, indexed by paths
36 * [ Form_name ] is an array of form errors
37 * [path] is a string storing error associated with single field
38 * @var array
40 private $errors = array();
42 /**
43 * Paths changed so that they can be used as HTML ids, indexed by paths
44 * @var array
46 private $translated_paths = array();
48 /**
49 * Server paths change indexes so we define maps from current server
50 * path to the first one, indexed by work path
51 * @var array
53 private $system_paths = array();
55 /**
56 * Language strings which will be sent to PMA_messages JS variable
57 * Will be looked up in $GLOBALS: str{value} or strSetup{value}
58 * @var array
60 private $js_lang_strings = array();
62 /**
63 * Tells whether forms have been validated
64 * @var bool
66 private $is_validated = true;
68 /**
69 * Dictionary with user preferences keys
70 * @var array
72 private $userprefs_keys;
74 /**
75 * Dictionary with disallowed user preferences keys
76 * @var array
78 private $userprefs_disallow;
80 public function __construct()
82 $this->js_lang_strings = array(
83 'error_nan_p' => __('Not a positive number'),
84 'error_nan_nneg' => __('Not a non-negative number'),
85 'error_incorrect_port' => __('Not a valid port number'),
86 'error_invalid_value' => __('Incorrect value'),
87 'error_value_lte' => __('Value must be equal or lower than %s'));
88 // initialize validators
89 PMA_config_get_validators();
92 /**
93 * Registers form in form manager
95 * @param string $form_name
96 * @param array $form
97 * @param int $server_id 0 if new server, validation; >= 1 if editing a server
99 public function registerForm($form_name, array $form, $server_id = null)
101 $this->forms[$form_name] = new Form($form_name, $form, $server_id);
102 $this->is_validated = false;
103 foreach ($this->forms[$form_name]->fields as $path) {
104 $work_path = $server_id === null
105 ? $path
106 : str_replace('Servers/1/', "Servers/$server_id/", $path);
107 $this->system_paths[$work_path] = $path;
108 $this->translated_paths[$work_path] = str_replace('/', '-', $work_path);
113 * Processes forms, returns true on successful save
115 * @param bool $allow_partial_save allows for partial form saving on failed validation
116 * @param bool $check_form_submit whether check for $_POST['submit_save']
117 * @return boolean
119 public function process($allow_partial_save = true, $check_form_submit = true)
121 if ($check_form_submit && !isset($_POST['submit_save'])) {
122 return false;
125 // save forms
126 if (count($this->forms) > 0) {
127 return $this->save(array_keys($this->forms), $allow_partial_save);
129 return false;
133 * Runs validation for all registered forms
135 * @uses ConfigFile::getInstance()
136 * @uses ConfigFile::getValue()
137 * @uses PMA_config_validate()
139 private function _validate()
141 if ($this->is_validated) {
142 return;
145 $cf = ConfigFile::getInstance();
146 $paths = array();
147 $values = array();
148 foreach ($this->forms as $form) {
149 /* @var $form Form */
150 $paths[] = $form->name;
151 // collect values and paths
152 foreach ($form->fields as $path) {
153 $work_path = array_search($path, $this->system_paths);
154 $values[$path] = $cf->getValue($work_path);
155 $paths[] = $path;
159 // run validation
160 $errors = PMA_config_validate($paths, $values, false);
162 // change error keys from canonical paths to work paths
163 if (is_array($errors) && count($errors) > 0) {
164 $this->errors = array();
165 foreach ($errors as $path => $error_list) {
166 $work_path = array_search($path, $this->system_paths);
167 // field error
168 if (!$work_path) {
169 // form error, fix path
170 $work_path = $path;
172 $this->errors[$work_path] = $error_list;
175 $this->is_validated = true;
179 * Outputs HTML for forms
181 * @uses ConfigFile::getInstance()
182 * @uses ConfigFile::get()
183 * @uses display_fieldset_bottom()
184 * @uses display_fieldset_top()
185 * @uses display_form_bottom()
186 * @uses display_form_top()
187 * @uses display_js()
188 * @uses display_tabs_bottom()
189 * @uses display_tabs_top()
190 * @uses js_validate()
191 * @uses PMA_config_get_validators()
192 * @uses PMA_jsFormat()
193 * @uses PMA_lang()
194 * @param bool $tabbed_form
195 * @param bool $show_restore_default whether show "restore default" button besides the input field
197 public function display($tabbed_form = false, $show_restore_default = false)
199 static $js_lang_sent = false;
201 $js = array();
202 $js_default = array();
203 $tabbed_form = $tabbed_form && (count($this->forms) > 1);
204 $validators = PMA_config_get_validators();
206 display_form_top();
208 if ($tabbed_form) {
209 $tabs = array();
210 foreach ($this->forms as $form) {
211 $tabs[$form->name] = PMA_lang("Form_$form->name");
213 display_tabs_top($tabs);
216 // valdiate only when we aren't displaying a "new server" form
217 $is_new_server = false;
218 foreach ($this->forms as $form) {
219 /* @var $form Form */
220 if ($form->index === 0) {
221 $is_new_server = true;
222 break;
225 if (!$is_new_server) {
226 $this->_validate();
229 // user preferences
230 $this->_loadUserprefsInfo();
232 // display forms
233 foreach ($this->forms as $form) {
234 /* @var $form Form */
235 $form_desc = isset($GLOBALS["strConfigForm_{$form->name}_desc"])
236 ? PMA_lang("Form_{$form->name}_desc")
237 : '';
238 $form_errors = isset($this->errors[$form->name])
239 ? $this->errors[$form->name] : null;
240 display_fieldset_top(PMA_lang("Form_$form->name"),
241 $form_desc, $form_errors, array('id' => $form->name));
243 foreach ($form->fields as $field => $path) {
244 $work_path = array_search($path, $this->system_paths);
245 $translated_path = $this->translated_paths[$work_path];
246 // always true/false for user preferences display
247 // otherwise null
248 $userprefs_allow = isset($this->userprefs_keys[$path])
249 ? !isset($this->userprefs_disallow[$path])
250 : null;
251 // display input
252 $this->_displayFieldInput($form, $field, $path, $work_path,
253 $translated_path, $show_restore_default, $userprefs_allow, $js_default);
254 // register JS validators for this field
255 if (isset($validators[$path])) {
256 js_validate($translated_path, $validators[$path], $js);
259 display_fieldset_bottom();
262 if ($tabbed_form) {
263 display_tabs_bottom();
265 display_form_bottom();
267 // if not already done, send strings used for valdiation to JavaScript
268 if (!$js_lang_sent) {
269 $js_lang_sent = true;
270 $js_lang = array();
271 foreach ($this->js_lang_strings as $strName => $strValue) {
272 $js_lang[] = "'$strName': '" . PMA_jsFormat($strValue, false) . '\'';
274 $js[] = "$.extend(PMA_messages, {\n\t" . implode(",\n\t", $js_lang) . '})';
277 $js[] = "$.extend(defaultValues, {\n\t" . implode(",\n\t", $js_default) . '})';
278 display_js($js);
282 * Prepares data for input field display and outputs HTML code
284 * @uses ConfigFile::get()
285 * @uses ConfigFile::getDefault()
286 * @uses ConfigFile::getInstance()
287 * @uses display_group_footer()
288 * @uses display_group_header()
289 * @uses display_input()
290 * @uses Form::getOptionType()
291 * @uses Form::getOptionValueList()
292 * @uses PMA_escapeJsString()
293 * @uses PMA_lang_desc()
294 * @uses PMA_lang_name()
295 * @param Form $form
296 * @param string $field field name as it appears in $form
297 * @param string $system_path field path, eg. Servers/1/verbose
298 * @param string $work_path work path, eg. Servers/4/verbose
299 * @param string $translated_path work path changed so that it can be used as XHTML id
300 * @param bool $show_restore_default whether show "restore default" button besides the input field
301 * @param mixed $userprefs_allow whether user preferences are enabled for this field
302 * (null - no support, true/false - enabled/disabled)
303 * @param array &$js_default array which stores JavaScript code to be displayed
305 private function _displayFieldInput(Form $form, $field, $system_path, $work_path,
306 $translated_path, $show_restore_default, $userprefs_allow, array &$js_default)
308 $name = PMA_lang_name($system_path);
309 $description = PMA_lang_name($system_path, 'desc', '');
311 $cf = ConfigFile::getInstance();
312 $value = $cf->get($work_path);
313 $value_default = $cf->getDefault($system_path);
314 $value_is_default = false;
315 if ($value === null || $value === $value_default) {
316 $value = $value_default;
317 $value_is_default = true;
320 $opts = array(
321 'doc' => $this->getDocLink($system_path),
322 'wiki' => $this->getWikiLink($system_path),
323 'show_restore_default' => $show_restore_default,
324 'userprefs_allow' => $userprefs_allow,
325 'userprefs_comment' => PMA_lang_name($system_path, 'cmt', ''));
326 if (isset($form->default[$system_path])) {
327 $opts['setvalue'] = $form->default[$system_path];
330 if (isset($this->errors[$work_path])) {
331 $opts['errors'] = $this->errors[$work_path];
333 switch ($form->getOptionType($field)) {
334 case 'string':
335 $type = 'text';
336 break;
337 case 'short_string':
338 $type = 'short_text';
339 break;
340 case 'double':
341 case 'integer':
342 $type = 'number_text';
343 break;
344 case 'boolean':
345 $type = 'checkbox';
346 break;
347 case 'select':
348 $type = 'select';
349 $opts['values'] = $form->getOptionValueList($form->fields[$field]);
350 break;
351 case 'array':
352 $type = 'list';
353 $value = (array) $value;
354 $value_default = (array) $value_default;
355 break;
356 case 'group':
357 if (substr($field, 7, 4) != 'end:') { // :group:end is changed to :group:end:{unique id} in Form class
358 display_group_header(substr($field, 7));
359 } else {
360 display_group_footer();
362 return;
363 case 'NULL':
364 trigger_error("Field $system_path has no type", E_USER_WARNING);
365 return;
368 // TrustedProxies requires changes before displaying
369 if ($system_path == 'TrustedProxies') {
370 foreach ($value as $ip => &$v) {
371 if (!preg_match('/^-\d+$/', $ip)) {
372 $v = $ip . ': ' . $v;
376 $this->_setComments($system_path, $opts);
378 // send default value to form's JS
379 $js_line = '\'' . $translated_path . '\': ';
380 switch ($type) {
381 case 'text':
382 case 'short_text':
383 case 'number_text':
384 $js_line .= '\'' . PMA_escapeJsString($value_default) . '\'';
385 break;
386 case 'checkbox':
387 $js_line .= $value_default ? 'true' : 'false';
388 break;
389 case 'select':
390 $value_default_js = is_bool($value_default)
391 ? (int) $value_default
392 : $value_default;
393 $js_line .= '[\'' . PMA_escapeJsString($value_default_js) . '\']';
394 break;
395 case 'list':
396 $js_line .= '\'' . PMA_escapeJsString(implode("\n", $value_default)) . '\'';
397 break;
399 $js_default[] = $js_line;
401 display_input($translated_path, $name, $description, $type,
402 $value, $value_is_default, $opts);
406 * Displays errors
408 * @uses display_errors()
409 * @uses PMA_lang_name()
411 public function displayErrors()
413 $this->_validate();
414 if (count($this->errors) == 0) {
415 return;
418 foreach ($this->errors as $system_path => $error_list) {
419 if (isset($this->system_paths[$system_path])) {
420 $path = $this->system_paths[$system_path];
421 $name = PMA_lang_name($path);
422 } else {
423 $name = $GLOBALS["strConfigForm_$system_path"];
425 display_errors($name, $error_list);
430 * Reverts erroneous fields to their default values
432 * @uses ConfigFile::getDefault()
433 * @uses ConfigFile::getInstance()
434 * @uses ConfigFile::set()
437 public function fixErrors()
439 $this->_validate();
440 if (count($this->errors) == 0) {
441 return;
444 $cf = ConfigFile::getInstance();
445 foreach (array_keys($this->errors) as $work_path) {
446 if (!isset($this->system_paths[$work_path])) {
447 continue;
449 $canonical_path = $this->system_paths[$work_path];
450 $cf->set($work_path, $cf->getDefault($canonical_path));
455 * Validates select field and casts $value to correct type
457 * @param string $value
458 * @param array $allowed
459 * @return bool
461 private function _validateSelect(&$value, array $allowed)
463 $value_cmp = is_bool($value)
464 ? (int) $value
465 : $value;
466 foreach ($allowed as $vk => $v) {
467 // equality comparison only if both values are numeric or not numeric
468 // (allows to skip 0 == 'string' equalling to true) or identity (for string-string)
469 if (($vk == $value && !(is_numeric($value_cmp) xor is_numeric($vk)))
470 || $vk === $value) {
471 settype($value, gettype($vk));
472 return true;
475 return false;
479 * Validates and saves form data to session
481 * @uses ConfigFile::get()
482 * @uses ConfigFile::getInstance()
483 * @uses ConfigFile::getServerCount()
484 * @uses ConfigFile::set()
485 * @uses Form::getOptionType()
486 * @uses Form::getOptionValueList()
487 * @uses PMA_lang_name()
488 * @param array|string $forms array of form names
489 * @param bool $allow_partial_save allows for partial form saving on failed validation
490 * @return boolean true on success (no errors and all saved)
492 public function save($forms, $allow_partial_save = true)
494 $result = true;
495 $cf = ConfigFile::getInstance();
496 $forms = (array) $forms;
498 $values = array();
499 $to_save = array();
500 $is_setup_script = defined('PMA_SETUP');
501 if ($is_setup_script) {
502 $this->_loadUserprefsInfo();
505 $this->errors = array();
506 foreach ($forms as $form) {
507 /* @var $form Form */
508 if (isset($this->forms[$form])) {
509 $form = $this->forms[$form];
510 } else {
511 continue;
513 // get current server id
514 $change_index = $form->index === 0
515 ? $cf->getServerCount() + 1
516 : false;
517 // grab POST values
518 foreach ($form->fields as $field => $system_path) {
519 $work_path = array_search($system_path, $this->system_paths);
520 $key = $this->translated_paths[$work_path];
521 $type = $form->getOptionType($field);
523 // skip groups
524 if ($type == 'group') {
525 continue;
528 // ensure the value is set
529 if (!isset($_POST[$key])) {
530 // checkboxes aren't set by browsers if they're off
531 if ($type == 'boolean') {
532 $_POST[$key] = false;
533 } else {
534 $this->errors[$form->name][] = sprintf(
535 __('Missing data for %s'),
536 '<i>' . PMA_lang_name($system_path) . '</i>');
537 $result = false;
538 continue;
542 // user preferences allow/disallow
543 if ($is_setup_script && isset($this->userprefs_keys[$system_path])) {
544 if (isset($this->userprefs_disallow[$system_path])
545 && isset($_POST[$key . '-userprefs-allow'])) {
546 unset($this->userprefs_disallow[$system_path]);
547 } else if (!isset($_POST[$key . '-userprefs-allow'])) {
548 $this->userprefs_disallow[$system_path] = true;
552 // cast variables to correct type
553 switch ($type) {
554 case 'double':
555 settype($_POST[$key], 'float');
556 break;
557 case 'boolean':
558 case 'integer':
559 if ($_POST[$key] !== '') {
560 settype($_POST[$key], $type);
562 break;
563 case 'select':
564 if (!$this->_validateSelect($_POST[$key], $form->getOptionValueList($system_path))) {
565 $this->errors[$work_path][] = __('Incorrect value');
566 $result = false;
567 continue;
569 break;
570 case 'string':
571 case 'short_string':
572 $_POST[$key] = trim($_POST[$key]);
573 break;
574 case 'array':
575 // eliminate empty values and ensure we have an array
576 $post_values = is_array($_POST[$key])
577 ? $_POST[$key]
578 : explode("\n", $_POST[$key]);
579 $_POST[$key] = array();
580 foreach ($post_values as $v) {
581 $v = trim($v);
582 if ($v !== '') {
583 $_POST[$key][] = $v;
586 break;
589 // now we have value with proper type
590 $values[$system_path] = $_POST[$key];
591 if ($change_index !== false) {
592 $work_path = str_replace("Servers/$form->index/",
593 "Servers/$change_index/", $work_path);
595 $to_save[$work_path] = $system_path;
599 // save forms
600 if ($allow_partial_save || empty($this->errors)) {
601 foreach ($to_save as $work_path => $path) {
602 // TrustedProxies requires changes before saving
603 if ($path == 'TrustedProxies') {
604 $proxies = array();
605 $i = 0;
606 foreach ($values[$path] as $value) {
607 $matches = array();
608 if (preg_match("/^(.+):(?:[ ]?)(\\w+)$/", $value, $matches)) {
609 // correct 'IP: HTTP header' pair
610 $ip = trim($matches[1]);
611 $proxies[$ip] = trim($matches[2]);
612 } else {
613 // save also incorrect values
614 $proxies["-$i"] = $value;
615 $i++;
618 $values[$path] = $proxies;
620 $cf->set($work_path, $values[$path], $path);
622 if ($is_setup_script) {
623 $cf->set('UserprefsDisallow', array_keys($this->userprefs_disallow));
627 // don't look for non-critical errors
628 $this->_validate();
630 return $result;
634 * Tells whether form validation failed
636 * @return boolean
638 public function hasErrors()
640 return count($this->errors) > 0;
645 * Returns link to documentation
647 * @param string $path
648 * @return string
650 public function getDocLink($path)
652 $test = substr($path, 0, 6);
653 if ($test == 'Import' || $test == 'Export') {
654 return '';
656 return 'Documentation.html#cfg_' . $this->_getOptName($path);
660 * Returns link to wiki
662 * @param string $path
663 * @return string
665 public function getWikiLink($path)
667 $opt_name = $this->_getOptName($path);
668 if (substr($opt_name, 0, 7) == 'Servers') {
669 $opt_name = substr($opt_name, 8);
670 if (strpos($opt_name, 'AllowDeny') === 0) {
671 $opt_name = str_replace('_', '_.28', $opt_name) . '.29';
674 $test = substr($path, 0, 6);
675 if ($test == 'Import') {
676 $opt_name = substr($opt_name, 7);
677 if ($opt_name == 'format') {
678 $opt_name = 'format_2';
681 if ($test == 'Export') {
682 $opt_name = substr($opt_name, 7);
684 return PMA_linkURL('http://wiki.phpmyadmin.net/pma/Config#' . $opt_name);
688 * Changes path so it can be used in URLs
690 * @param string $path
691 * @return string
693 private function _getOptName($path)
695 return str_replace(array('Servers/1/', '/'), array('Servers/', '_'), $path);
699 * Fills out {@link userprefs_keys} and {@link userprefs_disallow}
701 * @uses PMA_read_userprefs_fieldnames()
703 private function _loadUserprefsInfo()
705 if ($this->userprefs_keys === null) {
706 $this->userprefs_keys = array_flip(PMA_read_userprefs_fieldnames());
707 // read real config for user preferences display
708 $userprefs_disallow = defined('PMA_SETUP')
709 ? ConfigFile::getInstance()->get('UserprefsDisallow', array())
710 : $GLOBALS['cfg']['UserprefsDisallow'];
711 $this->userprefs_disallow = array_flip($userprefs_disallow);
716 * Sets field comments and warnings based on current environment
718 * @param string $system_path
719 * @param array $opts
721 private function _setComments($system_path, array &$opts)
723 // RecodingEngine - mark unavailable types
724 if ($system_path == 'RecodingEngine') {
725 $comment = '';
726 if (!function_exists('iconv')) {
727 $opts['values']['iconv'] .= ' (' . __('unavailable') . ')';
728 $comment = sprintf(__('"%s" requires %s extension'), 'iconv', 'iconv');
730 if (!function_exists('recode_string')) {
731 $opts['values']['recode'] .= ' (' . __('unavailable') . ')';
732 $comment .= ($comment ? ", " : '') . sprintf(__('"%s" requires %s extension'),
733 'recode', 'recode');
735 $opts['comment'] = $comment;
736 $opts['comment_warning'] = true;
738 // ZipDump, GZipDump, BZipDump - check function availability
739 if ($system_path == 'ZipDump' || $system_path == 'GZipDump' || $system_path == 'BZipDump') {
740 $comment = '';
741 $funcs = array(
742 'ZipDump' => array('zip_open', 'gzcompress'),
743 'GZipDump' => array('gzopen', 'gzencode'),
744 'BZipDump' => array('bzopen', 'bzcompress'));
745 if (!function_exists($funcs[$system_path][0])) {
746 $comment = sprintf(__('import will not work, missing function (%s)'),
747 $funcs[$system_path][0]);
749 if (!function_exists($funcs[$system_path][1])) {
750 $comment .= ($comment ? '; ' : '') . sprintf(__('export will not work, missing function (%s)'),
751 $funcs[$system_path][1]);
753 $opts['comment'] = $comment;
754 $opts['comment_warning'] = true;
756 if ($system_path == 'SQLQuery/Validate' && !$GLOBALS['cfg']['SQLValidator']['use']) {
757 $opts['comment'] = __('SQL Validator is disabled');
758 $opts['comment_warning'] = true;
760 if ($system_path == 'SQLValidator/use') {
761 if (!class_exists('SOAPClient')) {
762 @include_once 'SOAP/Client.php';
763 if (!class_exists('SOAP_Client')) {
764 $opts['comment'] = __('SOAP extension not found');
765 $opts['comment_warning'] = true;
769 if (!defined('PMA_SETUP')) {
770 if (($system_path == 'MaxDbList' || $system_path == 'MaxTableList'
771 || $system_path == 'QueryHistoryMax')) {
772 $opts['comment'] = sprintf(__('maximum %s'), $GLOBALS['cfg'][$system_path]);