fix import merge
[phpmyadmin.git] / libraries / config / FormDisplay.class.php
blob5a08f5e870e48f55a566feabd0f7a984d8564c03
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 $text = substr($field, 7);
358 if ($text != 'end') {
359 display_group_header($text);
360 } else {
361 display_group_footer();
363 return;
364 case 'NULL':
365 trigger_error("Field $system_path has no type", E_USER_WARNING);
366 return;
369 // TrustedProxies requires changes before displaying
370 if ($system_path == 'TrustedProxies') {
371 foreach ($value as $ip => &$v) {
372 if (!preg_match('/^-\d+$/', $ip)) {
373 $v = $ip . ': ' . $v;
377 $this->_setComments($system_path, $opts);
379 // send default value to form's JS
380 $js_line = '\'' . $translated_path . '\': ';
381 switch ($type) {
382 case 'text':
383 case 'short_text':
384 case 'number_text':
385 $js_line .= '\'' . PMA_escapeJsString($value_default) . '\'';
386 break;
387 case 'checkbox':
388 $js_line .= $value_default ? 'true' : 'false';
389 break;
390 case 'select':
391 $value_default_js = is_bool($value_default)
392 ? (int) $value_default
393 : $value_default;
394 $js_line .= '[\'' . PMA_escapeJsString($value_default_js) . '\']';
395 break;
396 case 'list':
397 $js_line .= '\'' . PMA_escapeJsString(implode("\n", $value_default)) . '\'';
398 break;
400 $js_default[] = $js_line;
402 display_input($translated_path, $name, $description, $type,
403 $value, $value_is_default, $opts);
407 * Displays errors
409 * @uses display_errors()
410 * @uses PMA_lang_name()
412 public function displayErrors()
414 $this->_validate();
415 if (count($this->errors) == 0) {
416 return;
419 foreach ($this->errors as $system_path => $error_list) {
420 if (isset($this->system_paths[$system_path])) {
421 $path = $this->system_paths[$system_path];
422 $name = PMA_lang_name($path);
423 } else {
424 $name = $GLOBALS["strConfigForm_$system_path"];
426 display_errors($name, $error_list);
431 * Reverts erroneous fields to their default values
433 * @uses ConfigFile::getDefault()
434 * @uses ConfigFile::getInstance()
435 * @uses ConfigFile::set()
438 public function fixErrors()
440 $this->_validate();
441 if (count($this->errors) == 0) {
442 return;
445 $cf = ConfigFile::getInstance();
446 foreach (array_keys($this->errors) as $work_path) {
447 if (!isset($this->system_paths[$work_path])) {
448 continue;
450 $canonical_path = $this->system_paths[$work_path];
451 $cf->set($work_path, $cf->getDefault($canonical_path));
456 * Validates select field and casts $value to correct type
458 * @param string $value
459 * @param array $allowed
460 * @return bool
462 private function _validateSelect(&$value, array $allowed)
464 $value_cmp = is_bool($value)
465 ? (int) $value
466 : $value;
467 foreach ($allowed as $vk => $v) {
468 // equality comparison only if both values are numeric or not numeric
469 // (allows to skip 0 == 'string' equalling to true) or identity (for string-string)
470 if (($vk == $value && !(is_numeric($value_cmp) xor is_numeric($vk)))
471 || $vk === $value) {
472 settype($value, gettype($v));
473 return true;
476 return false;
480 * Validates and saves form data to session
482 * @uses ConfigFile::get()
483 * @uses ConfigFile::getInstance()
484 * @uses ConfigFile::getServerCount()
485 * @uses ConfigFile::set()
486 * @uses Form::getOptionType()
487 * @uses Form::getOptionValueList()
488 * @uses PMA_lang_name()
489 * @param array|string $forms array of form names
490 * @param bool $allow_partial_save allows for partial form saving on failed validation
491 * @return boolean true on success (no errors and all saved)
493 public function save($forms, $allow_partial_save = true)
495 $result = true;
496 $cf = ConfigFile::getInstance();
497 $forms = (array) $forms;
499 $values = array();
500 $to_save = array();
501 $is_setup_script = defined('PMA_SETUP') && PMA_SETUP;
502 if ($is_setup_script) {
503 $this->_loadUserprefsInfo();
506 $this->errors = array();
507 foreach ($forms as $form) {
508 /* @var $form Form */
509 if (isset($this->forms[$form])) {
510 $form = $this->forms[$form];
511 } else {
512 continue;
514 // get current server id
515 $change_index = $form->index === 0
516 ? $cf->getServerCount() + 1
517 : false;
518 // grab POST values
519 foreach ($form->fields as $field => $system_path) {
520 $work_path = array_search($system_path, $this->system_paths);
521 $key = $this->translated_paths[$work_path];
522 $type = $form->getOptionType($field);
524 // skip groups
525 if ($type == 'group') {
526 continue;
529 // ensure the value is set
530 if (!isset($_POST[$key])) {
531 // checkboxes aren't set by browsers if they're off
532 if ($type == 'boolean') {
533 $_POST[$key] = false;
534 } else {
535 $this->errors[$form->name][] = sprintf(
536 __('Missing data for %s'),
537 '<i>' . PMA_lang_name($system_path) . '</i>');
538 $result = false;
539 continue;
543 // user preferences allow/disallow
544 if ($is_setup_script && isset($this->userprefs_keys[$system_path])) {
545 if (isset($this->userprefs_disallow[$system_path])
546 && isset($_POST[$key . '-userprefs-allow'])) {
547 unset($this->userprefs_disallow[$system_path]);
548 } else if (!isset($_POST[$key . '-userprefs-allow'])) {
549 $this->userprefs_disallow[$system_path] = true;
553 // cast variables to correct type
554 switch ($type) {
555 case 'double':
556 settype($_POST[$key], 'float');
557 break;
558 case 'boolean':
559 case 'integer':
560 if ($_POST[$key] !== '') {
561 settype($_POST[$key], $type);
563 break;
564 case 'select':
565 if (!$this->_validateSelect($_POST[$key], $form->getOptionValueList($system_path))) {
566 $this->errors[$work_path][] = __('Incorrect value');
567 $result = false;
568 continue;
570 break;
571 case 'string':
572 case 'short_string':
573 $_POST[$key] = trim($_POST[$key]);
574 break;
575 case 'array':
576 // eliminate empty values and ensure we have an array
577 $post_values = is_array($_POST[$key])
578 ? $_POST[$key]
579 : explode("\n", $_POST[$key]);
580 $_POST[$key] = array();
581 foreach ($post_values as $v) {
582 $v = trim($v);
583 if ($v !== '') {
584 $_POST[$key][] = $v;
587 break;
590 // now we have value with proper type
591 $values[$system_path] = $_POST[$key];
592 if ($change_index !== false) {
593 $work_path = str_replace("Servers/$form->index/",
594 "Servers/$change_index/", $work_path);
596 $to_save[$work_path] = $system_path;
600 // save forms
601 if ($allow_partial_save || empty($this->errors)) {
602 foreach ($to_save as $work_path => $path) {
603 // TrustedProxies requires changes before saving
604 if ($path == 'TrustedProxies') {
605 $proxies = array();
606 $i = 0;
607 foreach ($values[$path] as $value) {
608 $matches = array();
609 if (preg_match("/^(.+):(?:[ ]?)(\\w+)$/", $value, $matches)) {
610 // correct 'IP: HTTP header' pair
611 $ip = trim($matches[1]);
612 $proxies[$ip] = trim($matches[2]);
613 } else {
614 // save also incorrect values
615 $proxies["-$i"] = $value;
616 $i++;
619 $values[$path] = $proxies;
621 $cf->set($work_path, $values[$path], $path);
623 if ($is_setup_script) {
624 $cf->set('UserprefsDisallow', array_keys($this->userprefs_disallow));
628 // don't look for non-critical errors
629 $this->_validate();
631 return $result;
635 * Tells whether form validation failed
637 * @return boolean
639 public function hasErrors()
641 return count($this->errors) > 0;
646 * Returns link to documentation
648 * @param string $path
649 * @return string
651 public function getDocLink($path)
653 $test = substr($path, 0, 6);
654 if ($test == 'Import' || $test == 'Export') {
655 return '';
657 return 'Documentation.html#cfg_' . $this->_getOptName($path);
661 * Returns link to wiki
663 * @param string $path
664 * @return string
666 public function getWikiLink($path)
668 $opt_name = $this->_getOptName($path);
669 if (substr($opt_name, 0, 7) == 'Servers') {
670 $opt_name = substr($opt_name, 8);
671 if (strpos($opt_name, 'AllowDeny') === 0) {
672 $opt_name = str_replace('_', '_.28', $opt_name) . '.29';
675 $test = substr($path, 0, 6);
676 if ($test == 'Import') {
677 $opt_name = substr($opt_name, 7);
678 if ($opt_name == 'format') {
679 $opt_name = 'format_2';
682 if ($test == 'Export') {
683 $opt_name = substr($opt_name, 7);
685 return 'http://wiki.phpmyadmin.net/pma/Config#' . $opt_name;
689 * Changes path so it can be used in URLs
691 * @param string $path
692 * @return string
694 private function _getOptName($path)
696 return str_replace(array('Servers/1/', '/'), array('Servers/', '_'), $path);
700 * Fills out {@link userprefs_keys} and {@link userprefs_disallow}
702 * @uses PMA_read_userprefs_fieldnames()
704 private function _loadUserprefsInfo()
706 if ($this->userprefs_keys === null) {
707 $this->userprefs_keys = array_flip(PMA_read_userprefs_fieldnames());
708 // read real config for user preferences display
709 $userprefs_disallow = defined('PMA_SETUP') && PMA_SETUP
710 ? ConfigFile::getInstance()->get('UserprefsDisallow', array())
711 : $GLOBALS['cfg']['UserprefsDisallow'];
712 $this->userprefs_disallow = array_flip($userprefs_disallow);
717 * Sets field comments and warnings based on current environment
719 * @param string $system_path
720 * @param array $opts
722 private function _setComments($system_path, array &$opts)
724 // RecodingEngine - mark unavailable types
725 if ($system_path == 'RecodingEngine') {
726 $comment = '';
727 if (!function_exists('iconv')) {
728 $opts['values']['iconv'] .= ' (' . __('unavailable') . ')';
729 $comment = sprintf(__('"%s" requires %s extension'), 'iconv', 'iconv');
731 if (!function_exists('recode_string')) {
732 $opts['values']['recode'] .= ' (' . __('unavailable') . ')';
733 $comment .= ($comment ? ", " : '') . sprintf(__('"%s" requires %s extension'),
734 'recode', 'recode');
736 $opts['comment'] = $comment;
737 $opts['comment_warning'] = true;
739 // ZipDump, GZipDump, BZipDump - check function availability
740 if ($system_path == 'ZipDump' || $system_path == 'GZipDump' || $system_path == 'BZipDump') {
741 $comment = '';
742 $funcs = array(
743 'ZipDump' => array('zip_open', 'gzcompress'),
744 'GZipDump' => array('gzopen', 'gzencode'),
745 'BZipDump' => array('bzopen', 'bzcompress'));
746 if (!function_exists($funcs[$system_path][0])) {
747 $comment = sprintf(__('import will not work, missing function (%s)'),
748 $funcs[$system_path][0]);
750 if (!function_exists($funcs[$system_path][1])) {
751 $comment .= ($comment ? '; ' : '') . sprintf(__('export will not work, missing function (%s)'),
752 $funcs[$system_path][1]);
754 $opts['comment'] = $comment;
755 $opts['comment_warning'] = true;
757 if ($system_path == 'SQLQuery/Validate' && !$GLOBALS['cfg']['SQLValidator']['use']) {
758 $opts['comment'] = __('SQL Validator is disabled');
759 $opts['comment_warning'] = true;
761 if ($system_path == 'SQLValidator/use') {
762 if (!class_exists('SOAPClient')) {
763 @include_once 'SOAP/Client.php';
764 if (!class_exists('SOAP_Client')) {
765 $opts['comment'] = __('SOAP extension not found');
766 $opts['comment_warning'] = true;
770 if (!defined('PMA_SETUP') || !PMA_SETUP) {
771 if (($system_path == 'MaxDbList' || $system_path == 'MaxTableList'
772 || $system_path == 'QueryHistoryMax')) {
773 $opts['comment'] = sprintf(__('maximum %s'), $GLOBALS['cfg'][$system_path]);