2 /* vim: set expandtab sw=4 ts=4 sts=4: */
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,
9 * eg. Servers/1/verbose
10 * o translated_path - work_path modified for HTML field name, a path with
11 * slashes changed to hyphens, eg. Servers-4-verbose
19 require_once './libraries/config/FormDisplay.tpl.php';
20 require_once './libraries/config/validate.lib.php';
21 require_once './libraries/js_escape.lib.php';
24 * Form management class, displays and processes forms
34 private $_forms = array();
37 * Stores validation errors, indexed by paths
38 * [ Form_name ] is an array of form errors
39 * [path] is a string storing error associated with single field
42 private $_errors = array();
45 * Paths changed so that they can be used as HTML ids, indexed by paths
48 private $_translatedPaths = array();
51 * Server paths change indexes so we define maps from current server
52 * path to the first one, indexed by work path
55 private $_systemPaths = array();
58 * Language strings which will be sent to PMA_messages JS variable
59 * Will be looked up in $GLOBALS: str{value} or strSetup{value}
62 private $_jsLangStrings = array();
65 * Tells whether forms have been validated
68 private $_isValidated = true;
71 * Dictionary with user preferences keys
74 private $_userprefsKeys;
77 * Dictionary with disallowed user preferences keys
80 private $_userprefsDisallow;
85 public function __construct()
87 $this->_jsLangStrings
= array(
88 'error_nan_p' => __('Not a positive number'),
89 'error_nan_nneg' => __('Not a non-negative number'),
90 'error_incorrect_port' => __('Not a valid port number'),
91 'error_invalid_value' => __('Incorrect value'),
92 'error_value_lte' => __('Value must be equal or lower than %s'));
93 // initialize validators
94 PMA_config_get_validators();
98 * Registers form in form manager
100 * @param string $form_name
102 * @param int $server_id 0 if new server, validation; >= 1 if editing a server
106 public function registerForm($form_name, array $form, $server_id = null)
108 $this->_forms
[$form_name] = new Form($form_name, $form, $server_id);
109 $this->_isValidated
= false;
110 foreach ($this->_forms
[$form_name]->fields
as $path) {
111 $work_path = $server_id === null
113 : str_replace('Servers/1/', "Servers/$server_id/", $path);
114 $this->_systemPaths
[$work_path] = $path;
115 $this->_translatedPaths
[$work_path] = str_replace('/', '-', $work_path);
120 * Processes forms, returns true on successful save
122 * @param bool $allow_partial_save allows for partial form saving
123 * on failed validation
124 * @param bool $check_form_submit whether check for $_POST['submit_save']
126 * @return boolean whether processing was successful
128 public function process($allow_partial_save = true, $check_form_submit = true)
130 if ($check_form_submit && !isset($_POST['submit_save'])) {
135 if (count($this->_forms
) > 0) {
136 return $this->save(array_keys($this->_forms
), $allow_partial_save);
142 * Runs validation for all registered forms
146 private function _validate()
148 if ($this->_isValidated
) {
152 $cf = ConfigFile
::getInstance();
155 foreach ($this->_forms
as $form) {
156 /* @var $form Form */
157 $paths[] = $form->name
;
158 // collect values and paths
159 foreach ($form->fields
as $path) {
160 $work_path = array_search($path, $this->_systemPaths
);
161 $values[$path] = $cf->getValue($work_path);
167 $errors = PMA_config_validate($paths, $values, false);
169 // change error keys from canonical paths to work paths
170 if (is_array($errors) && count($errors) > 0) {
171 $this->_errors
= array();
172 foreach ($errors as $path => $error_list) {
173 $work_path = array_search($path, $this->_systemPaths
);
176 // form error, fix path
179 $this->_errors
[$work_path] = $error_list;
182 $this->_isValidated
= true;
186 * Outputs HTML for forms
188 * @param bool $tabbed_form
189 * @param bool $show_restore_default whether show "restore default" button
190 * besides the input field
194 public function display($tabbed_form = false, $show_restore_default = false)
196 static $js_lang_sent = false;
199 $js_default = array();
200 $tabbed_form = $tabbed_form && (count($this->_forms
) > 1);
201 $validators = PMA_config_get_validators();
203 PMA_displayFormTop();
207 foreach ($this->_forms
as $form) {
208 $tabs[$form->name
] = PMA_lang("Form_$form->name");
210 PMA_displayTabsTop($tabs);
213 // valdiate only when we aren't displaying a "new server" form
214 $is_new_server = false;
215 foreach ($this->_forms
as $form) {
216 /* @var $form Form */
217 if ($form->index
=== 0) {
218 $is_new_server = true;
222 if (!$is_new_server) {
227 $this->_loadUserprefsInfo();
230 foreach ($this->_forms
as $form) {
231 /* @var $form Form */
232 $form_desc = isset($GLOBALS["strConfigForm_{$form->name}_desc"])
233 ?
PMA_lang("Form_{$form->name}_desc")
235 $form_errors = isset($this->_errors
[$form->name
])
236 ?
$this->_errors
[$form->name
] : null;
237 PMA_displayFieldsetTop(
238 PMA_lang("Form_$form->name"),
241 array('id' => $form->name
)
244 foreach ($form->fields
as $field => $path) {
245 $work_path = array_search($path, $this->_systemPaths
);
246 $translated_path = $this->_translatedPaths
[$work_path];
247 // always true/false for user preferences display
249 $userprefs_allow = isset($this->_userprefsKeys
[$path])
250 ?
!isset($this->_userprefsDisallow
[$path])
253 $this->_displayFieldInput(
259 $show_restore_default,
263 // register JS validators for this field
264 if (isset($validators[$path])) {
265 PMA_addJsValidate($translated_path, $validators[$path], $js);
268 PMA_displayFieldsetBottom();
272 PMA_displayTabsBottom();
274 PMA_displayFormBottom();
276 // if not already done, send strings used for valdiation to JavaScript
277 if (!$js_lang_sent) {
278 $js_lang_sent = true;
280 foreach ($this->_jsLangStrings
as $strName => $strValue) {
281 $js_lang[] = "'$strName': '" . PMA_jsFormat($strValue, false) . '\'';
283 $js[] = "$.extend(PMA_messages, {\n\t" . implode(",\n\t", $js_lang) . '})';
286 $js[] = "$.extend(defaultValues, {\n\t" . implode(",\n\t", $js_default) . '})';
287 PMA_displayJavascript($js);
291 * Prepares data for input field display and outputs HTML code
294 * @param string $field field name as it appears in $form
295 * @param string $system_path field path, eg. Servers/1/verbose
296 * @param string $work_path work path, eg. Servers/4/verbose
297 * @param string $translated_path work path changed so that it can be
299 * @param bool $show_restore_default whether show "restore default" button
300 * besides the input field
301 * @param mixed $userprefs_allow whether user preferences are enabled
302 * for this field (null - no support,
303 * true/false - enabled/disabled)
304 * @param array &$js_default array which stores JavaScript code
309 private function _displayFieldInput(
310 Form
$form, $field, $system_path, $work_path,
311 $translated_path, $show_restore_default, $userprefs_allow, array &$js_default
313 $name = PMA_lang_name($system_path);
314 $description = PMA_lang_name($system_path, 'desc', '');
316 $cf = ConfigFile
::getInstance();
317 $value = $cf->get($work_path);
318 $value_default = $cf->getDefault($system_path);
319 $value_is_default = false;
320 if ($value === null ||
$value === $value_default) {
321 $value = $value_default;
322 $value_is_default = true;
326 'doc' => $this->getDocLink($system_path),
327 'wiki' => $this->getWikiLink($system_path),
328 'show_restore_default' => $show_restore_default,
329 'userprefs_allow' => $userprefs_allow,
330 'userprefs_comment' => PMA_lang_name($system_path, 'cmt', ''));
331 if (isset($form->default[$system_path])) {
332 $opts['setvalue'] = $form->default[$system_path];
335 if (isset($this->_errors
[$work_path])) {
336 $opts['errors'] = $this->_errors
[$work_path];
338 switch ($form->getOptionType($field)) {
343 $type = 'short_text';
347 $type = 'number_text';
354 $opts['values'] = $form->getOptionValueList($form->fields
[$field]);
358 $value = (array) $value;
359 $value_default = (array) $value_default;
362 // :group:end is changed to :group:end:{unique id} in Form class
363 if (substr($field, 7, 4) != 'end:') {
364 PMA_displayGroupHeader(substr($field, 7));
366 PMA_displayGroupFooter();
370 trigger_error("Field $system_path has no type", E_USER_WARNING
);
374 // TrustedProxies requires changes before displaying
375 if ($system_path == 'TrustedProxies') {
376 foreach ($value as $ip => &$v) {
377 if (!preg_match('/^-\d+$/', $ip)) {
378 $v = $ip . ': ' . $v;
382 $this->_setComments($system_path, $opts);
384 // send default value to form's JS
385 $js_line = '\'' . $translated_path . '\': ';
390 $js_line .= '\'' . PMA_escapeJsString($value_default) . '\'';
393 $js_line .= $value_default ?
'true' : 'false';
396 $value_default_js = is_bool($value_default)
397 ?
(int) $value_default
399 $js_line .= '[\'' . PMA_escapeJsString($value_default_js) . '\']';
402 $js_line .= '\'' . PMA_escapeJsString(implode("\n", $value_default))
406 $js_default[] = $js_line;
409 $translated_path, $name, $type, $value,
410 $description, $value_is_default, $opts
419 public function displayErrors()
422 if (count($this->_errors
) == 0) {
426 foreach ($this->_errors
as $system_path => $error_list) {
427 if (isset($this->_systemPaths
[$system_path])) {
428 $path = $this->_systemPaths
[$system_path];
429 $name = PMA_lang_name($path);
431 $name = $GLOBALS["strConfigForm_$system_path"];
433 PMA_displayErrors($name, $error_list);
438 * Reverts erroneous fields to their default values
442 public function fixErrors()
445 if (count($this->_errors
) == 0) {
449 $cf = ConfigFile
::getInstance();
450 foreach (array_keys($this->_errors
) as $work_path) {
451 if (!isset($this->_systemPaths
[$work_path])) {
454 $canonical_path = $this->_systemPaths
[$work_path];
455 $cf->set($work_path, $cf->getDefault($canonical_path));
460 * Validates select field and casts $value to correct type
462 * @param string $value
463 * @param array $allowed
467 private function _validateSelect(&$value, array $allowed)
469 $value_cmp = is_bool($value)
472 foreach ($allowed as $vk => $v) {
473 // equality comparison only if both values are numeric or not numeric
474 // (allows to skip 0 == 'string' equalling to true)
475 // or identity (for string-string)
476 if (($vk == $value && !(is_numeric($value_cmp) xor is_numeric($vk)))
479 // keep boolean value as boolean
480 if (!is_bool($value)) {
481 settype($value, gettype($vk));
490 * Validates and saves form data to session
492 * @param array|string $forms array of form names
493 * @param bool $allow_partial_save allows for partial form saving on
496 * @return boolean true on success (no errors and all saved)
498 public function save($forms, $allow_partial_save = true)
501 $cf = ConfigFile
::getInstance();
502 $forms = (array) $forms;
506 $is_setup_script = defined('PMA_SETUP');
507 if ($is_setup_script) {
508 $this->_loadUserprefsInfo();
511 $this->_errors
= array();
512 foreach ($forms as $form_name) {
513 /* @var $form Form */
514 if (isset($this->_forms
[$form_name])) {
515 $form = $this->_forms
[$form_name];
519 // get current server id
520 $change_index = $form->index
=== 0
521 ?
$cf->getServerCount() +
1
524 foreach ($form->fields
as $field => $system_path) {
525 $work_path = array_search($system_path, $this->_systemPaths
);
526 $key = $this->_translatedPaths
[$work_path];
527 $type = $form->getOptionType($field);
530 if ($type == 'group') {
534 // ensure the value is set
535 if (!isset($_POST[$key])) {
536 // checkboxes aren't set by browsers if they're off
537 if ($type == 'boolean') {
538 $_POST[$key] = false;
540 $this->_errors
[$form->name
][] = sprintf(
541 __('Missing data for %s'),
542 '<i>' . PMA_lang_name($system_path) . '</i>'
549 // user preferences allow/disallow
551 && isset($this->_userprefsKeys
[$system_path])
553 if (isset($this->_userprefsDisallow
[$system_path])
554 && isset($_POST[$key . '-userprefs-allow'])
556 unset($this->_userprefsDisallow
[$system_path]);
557 } else if (!isset($_POST[$key . '-userprefs-allow'])) {
558 $this->_userprefsDisallow
[$system_path] = true;
562 // cast variables to correct type
565 settype($_POST[$key], 'float');
569 if ($_POST[$key] !== '') {
570 settype($_POST[$key], $type);
574 // special treatment for NavigationBarIconic and PropertiesIconic
575 if ($key === 'NavigationBarIconic'
576 ||
$key === 'PropertiesIconic'
578 if ($_POST[$key] !== 'both') {
579 settype($_POST[$key], 'boolean');
582 $successfully_validated = $this->_validateSelect(
584 $form->getOptionValueList($system_path)
586 if (! $successfully_validated) {
587 $this->_errors
[$work_path][] = __('Incorrect value');
594 $_POST[$key] = trim($_POST[$key]);
597 // eliminate empty values and ensure we have an array
598 $post_values = is_array($_POST[$key])
600 : explode("\n", $_POST[$key]);
601 $_POST[$key] = array();
602 foreach ($post_values as $v) {
611 // now we have value with proper type
612 $values[$system_path] = $_POST[$key];
613 if ($change_index !== false) {
614 $work_path = str_replace(
615 "Servers/$form->index/",
616 "Servers/$change_index/", $work_path
619 $to_save[$work_path] = $system_path;
624 if ($allow_partial_save ||
empty($this->_errors
)) {
625 foreach ($to_save as $work_path => $path) {
626 // TrustedProxies requires changes before saving
627 if ($path == 'TrustedProxies') {
630 foreach ($values[$path] as $value) {
633 "/^(.+):(?:[ ]?)(\\w+)$/", $value, $matches
636 // correct 'IP: HTTP header' pair
637 $ip = trim($matches[1]);
638 $proxies[$ip] = trim($matches[2]);
640 // save also incorrect values
641 $proxies["-$i"] = $value;
645 $values[$path] = $proxies;
647 $cf->set($work_path, $values[$path], $path);
649 if ($is_setup_script) {
652 array_keys($this->_userprefsDisallow
)
657 // don't look for non-critical errors
664 * Tells whether form validation failed
668 public function hasErrors()
670 return count($this->_errors
) > 0;
675 * Returns link to documentation
677 * @param string $path
681 public function getDocLink($path)
683 $test = substr($path, 0, 6);
684 if ($test == 'Import' ||
$test == 'Export') {
687 return PMA_Util
::getDocuLink(
689 'cfg_' . $this->_getOptName($path)
694 * Returns link to wiki
696 * @param string $path
700 public function getWikiLink($path)
702 $opt_name = $this->_getOptName($path);
703 if (substr($opt_name, 0, 7) == 'Servers') {
704 $opt_name = substr($opt_name, 8);
705 if (strpos($opt_name, 'AllowDeny') === 0) {
706 $opt_name = str_replace('_', '_.28', $opt_name) . '.29';
709 $test = substr($path, 0, 6);
710 if ($test == 'Import') {
711 $opt_name = substr($opt_name, 7);
712 if ($opt_name == 'format') {
713 $opt_name = 'format_2';
716 if ($test == 'Export') {
717 $opt_name = substr($opt_name, 7);
719 return PMA_linkURL('http://wiki.phpmyadmin.net/pma/Config#' . $opt_name);
723 * Changes path so it can be used in URLs
725 * @param string $path
729 private function _getOptName($path)
731 return str_replace(array('Servers/1/', '/'), array('Servers/', '_'), $path);
735 * Fills out {@link userprefs_keys} and {@link userprefs_disallow}
739 private function _loadUserprefsInfo()
741 if ($this->_userprefsKeys
=== null) {
742 $this->_userprefsKeys
= array_flip(PMA_readUserprefsFieldNames());
743 // read real config for user preferences display
744 $userprefs_disallow = defined('PMA_SETUP')
745 ? ConfigFile
::getInstance()->get('UserprefsDisallow', array())
746 : $GLOBALS['cfg']['UserprefsDisallow'];
747 $this->_userprefsDisallow
= array_flip($userprefs_disallow);
752 * Sets field comments and warnings based on current environment
754 * @param string $system_path
759 private function _setComments($system_path, array &$opts)
761 // RecodingEngine - mark unavailable types
762 if ($system_path == 'RecodingEngine') {
764 if (!function_exists('iconv')) {
765 $opts['values']['iconv'] .= ' (' . __('unavailable') . ')';
767 __('"%s" requires %s extension'), 'iconv', 'iconv'
770 if (!function_exists('recode_string')) {
771 $opts['values']['recode'] .= ' (' . __('unavailable') . ')';
772 $comment .= ($comment ?
", " : '') . sprintf(
773 __('"%s" requires %s extension'),
777 $opts['comment'] = $comment;
778 $opts['comment_warning'] = true;
780 // ZipDump, GZipDump, BZipDump - check function availability
781 if ($system_path == 'ZipDump'
782 ||
$system_path == 'GZipDump'
783 ||
$system_path == 'BZipDump'
787 'ZipDump' => array('zip_open', 'gzcompress'),
788 'GZipDump' => array('gzopen', 'gzencode'),
789 'BZipDump' => array('bzopen', 'bzcompress'));
790 if (!function_exists($funcs[$system_path][0])) {
792 __('import will not work, missing function (%s)'),
793 $funcs[$system_path][0]
796 if (!function_exists($funcs[$system_path][1])) {
797 $comment .= ($comment ?
'; ' : '') . sprintf(
798 __('export will not work, missing function (%s)'),
799 $funcs[$system_path][1]
802 $opts['comment'] = $comment;
803 $opts['comment_warning'] = true;
805 if ($system_path == 'SQLQuery/Validate'
806 && ! $GLOBALS['cfg']['SQLValidator']['use']
808 $opts['comment'] = __('SQL Validator is disabled');
809 $opts['comment_warning'] = true;
811 if ($system_path == 'SQLValidator/use') {
812 if (!class_exists('SOAPClient')) {
813 @include_once
'SOAP/Client.php';
814 if (!class_exists('SOAP_Client')) {
815 $opts['comment'] = __('SOAP extension not found');
816 $opts['comment_warning'] = true;
820 if (!defined('PMA_SETUP')) {
821 if (($system_path == 'MaxDbList' ||
$system_path == 'MaxTableList'
822 ||
$system_path == 'QueryHistoryMax')
824 $opts['comment'] = sprintf(
825 __('maximum %s'), $GLOBALS['cfg'][$system_path]