Merge "mw.loader: Improve error logging"
[mediawiki.git] / includes / htmlform / HTMLFormField.php
blobfdb392452ffb6bb398c2641a207bbfee0d6022d3
1 <?php
3 /**
4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
6 */
7 abstract class HTMLFormField {
8 public $mParams;
10 protected $mValidationCallback;
11 protected $mFilterCallback;
12 protected $mName;
13 protected $mLabel; # String label. Set on construction
14 protected $mID;
15 protected $mClass = '';
16 protected $mDefault;
17 protected $mOptions = false;
18 protected $mOptionsLabelsNotFromMessage = false;
20 /**
21 * @var bool If true will generate an empty div element with no label
22 * @since 1.22
24 protected $mShowEmptyLabels = true;
26 /**
27 * @var HTMLForm
29 public $mParent;
31 /**
32 * This function must be implemented to return the HTML to generate
33 * the input object itself. It should not implement the surrounding
34 * table cells/rows, or labels/help messages.
36 * @param string $value the value to set the input to; eg a default
37 * text for a text input.
39 * @return string Valid HTML.
41 abstract function getInputHTML( $value );
43 /**
44 * Get a translated interface message
46 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
47 * and wfMessage() otherwise.
49 * Parameters are the same as wfMessage().
51 * @return Message
53 function msg() {
54 $args = func_get_args();
56 if ( $this->mParent ) {
57 $callback = array( $this->mParent, 'msg' );
58 } else {
59 $callback = 'wfMessage';
62 return call_user_func_array( $callback, $args );
65 /**
66 * Override this function to add specific validation checks on the
67 * field input. Don't forget to call parent::validate() to ensure
68 * that the user-defined callback mValidationCallback is still run
70 * @param string $value The value the field was submitted with
71 * @param array $alldata The data collected from the form
73 * @return bool|string true on success, or String error to display.
75 function validate( $value, $alldata ) {
76 if ( isset( $this->mParams['required'] )
77 && $this->mParams['required'] !== false
78 && $value === ''
79 ) {
80 return $this->msg( 'htmlform-required' )->parse();
83 if ( isset( $this->mValidationCallback ) ) {
84 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
87 return true;
90 function filter( $value, $alldata ) {
91 if ( isset( $this->mFilterCallback ) ) {
92 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
95 return $value;
98 /**
99 * Should this field have a label, or is there no input element with the
100 * appropriate id for the label to point to?
102 * @return bool True to output a label, false to suppress
104 protected function needsLabel() {
105 return true;
109 * Tell the field whether to generate a separate label element if its label
110 * is blank.
112 * @since 1.22
114 * @param bool $show Set to false to not generate a label.
115 * @return void
117 public function setShowEmptyLabel( $show ) {
118 $this->mShowEmptyLabels = $show;
122 * Get the value that this input has been set to from a posted form,
123 * or the input's default value if it has not been set.
125 * @param WebRequest $request
126 * @return string The value
128 function loadDataFromRequest( $request ) {
129 if ( $request->getCheck( $this->mName ) ) {
130 return $request->getText( $this->mName );
131 } else {
132 return $this->getDefault();
137 * Initialise the object
139 * @param array $params Associative Array. See HTMLForm doc for syntax.
141 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
142 * @throws MWException
144 function __construct( $params ) {
145 $this->mParams = $params;
147 # Generate the label from a message, if possible
148 if ( isset( $params['label-message'] ) ) {
149 $msgInfo = $params['label-message'];
151 if ( is_array( $msgInfo ) ) {
152 $msg = array_shift( $msgInfo );
153 } else {
154 $msg = $msgInfo;
155 $msgInfo = array();
158 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
159 } elseif ( isset( $params['label'] ) ) {
160 if ( $params['label'] === '&#160;' ) {
161 // Apparently some things set &nbsp directly and in an odd format
162 $this->mLabel = '&#160;';
163 } else {
164 $this->mLabel = htmlspecialchars( $params['label'] );
166 } elseif ( isset( $params['label-raw'] ) ) {
167 $this->mLabel = $params['label-raw'];
170 $this->mName = "wp{$params['fieldname']}";
171 if ( isset( $params['name'] ) ) {
172 $this->mName = $params['name'];
175 $validName = Sanitizer::escapeId( $this->mName );
176 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
177 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
180 $this->mID = "mw-input-{$this->mName}";
182 if ( isset( $params['default'] ) ) {
183 $this->mDefault = $params['default'];
186 if ( isset( $params['id'] ) ) {
187 $id = $params['id'];
188 $validId = Sanitizer::escapeId( $id );
190 if ( $id != $validId ) {
191 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
194 $this->mID = $id;
197 if ( isset( $params['cssclass'] ) ) {
198 $this->mClass = $params['cssclass'];
201 if ( isset( $params['validation-callback'] ) ) {
202 $this->mValidationCallback = $params['validation-callback'];
205 if ( isset( $params['filter-callback'] ) ) {
206 $this->mFilterCallback = $params['filter-callback'];
209 if ( isset( $params['flatlist'] ) ) {
210 $this->mClass .= ' mw-htmlform-flatlist';
213 if ( isset( $params['hidelabel'] ) ) {
214 $this->mShowEmptyLabels = false;
219 * Get the complete table row for the input, including help text,
220 * labels, and whatever.
222 * @param string $value The value to set the input to.
224 * @return string Complete HTML table row.
226 function getTableRow( $value ) {
227 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
228 $inputHtml = $this->getInputHTML( $value );
229 $fieldType = get_class( $this );
230 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
231 $cellAttributes = array();
233 if ( !empty( $this->mParams['vertical-label'] ) ) {
234 $cellAttributes['colspan'] = 2;
235 $verticalLabel = true;
236 } else {
237 $verticalLabel = false;
240 $label = $this->getLabelHtml( $cellAttributes );
242 $field = Html::rawElement(
243 'td',
244 array( 'class' => 'mw-input' ) + $cellAttributes,
245 $inputHtml . "\n$errors"
248 if ( $verticalLabel ) {
249 $html = Html::rawElement( 'tr', array( 'class' => 'mw-htmlform-vertical-label' ), $label );
250 $html .= Html::rawElement( 'tr',
251 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
252 $field );
253 } else {
254 $html =
255 Html::rawElement( 'tr',
256 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
257 $label . $field );
260 return $html . $helptext;
264 * Get the complete div for the input, including help text,
265 * labels, and whatever.
266 * @since 1.20
268 * @param string $value The value to set the input to.
270 * @return string Complete HTML table row.
272 public function getDiv( $value ) {
273 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
274 $inputHtml = $this->getInputHTML( $value );
275 $fieldType = get_class( $this );
276 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
277 $cellAttributes = array();
278 $label = $this->getLabelHtml( $cellAttributes );
280 $outerDivClass = array(
281 'mw-input',
282 'mw-htmlform-nolabel' => ( $label === '' )
285 $field = Html::rawElement(
286 'div',
287 array( 'class' => $outerDivClass ) + $cellAttributes,
288 $inputHtml . "\n$errors"
290 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass, $errorClass );
291 if ( $this->mParent->isVForm() ) {
292 $divCssClasses[] = 'mw-ui-vform-div';
294 $html = Html::rawElement( 'div', array( 'class' => $divCssClasses ), $label . $field );
295 $html .= $helptext;
297 return $html;
301 * Get the complete raw fields for the input, including help text,
302 * labels, and whatever.
303 * @since 1.20
305 * @param string $value The value to set the input to.
307 * @return string Complete HTML table row.
309 public function getRaw( $value ) {
310 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
311 $inputHtml = $this->getInputHTML( $value );
312 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
313 $cellAttributes = array();
314 $label = $this->getLabelHtml( $cellAttributes );
316 $html = "\n$errors";
317 $html .= $label;
318 $html .= $inputHtml;
319 $html .= $helptext;
321 return $html;
325 * Generate help text HTML in table format
326 * @since 1.20
328 * @param string|null $helptext
329 * @return string
331 public function getHelpTextHtmlTable( $helptext ) {
332 if ( is_null( $helptext ) ) {
333 return '';
336 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ), $helptext );
337 $row = Html::rawElement( 'tr', array(), $row );
339 return $row;
343 * Generate help text HTML in div format
344 * @since 1.20
346 * @param string|null $helptext
348 * @return string
350 public function getHelpTextHtmlDiv( $helptext ) {
351 if ( is_null( $helptext ) ) {
352 return '';
355 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
357 return $div;
361 * Generate help text HTML formatted for raw output
362 * @since 1.20
364 * @param string|null $helptext
365 * @return string
367 public function getHelpTextHtmlRaw( $helptext ) {
368 return $this->getHelpTextHtmlDiv( $helptext );
372 * Determine the help text to display
373 * @since 1.20
374 * @return string
376 public function getHelpText() {
377 $helptext = null;
379 if ( isset( $this->mParams['help-message'] ) ) {
380 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
383 if ( isset( $this->mParams['help-messages'] ) ) {
384 foreach ( $this->mParams['help-messages'] as $name ) {
385 $helpMessage = (array)$name;
386 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
388 if ( $msg->exists() ) {
389 if ( is_null( $helptext ) ) {
390 $helptext = '';
391 } else {
392 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
394 $helptext .= $msg->parse(); // Append message
397 } elseif ( isset( $this->mParams['help'] ) ) {
398 $helptext = $this->mParams['help'];
401 return $helptext;
405 * Determine form errors to display and their classes
406 * @since 1.20
408 * @param string $value The value of the input
409 * @return array
411 public function getErrorsAndErrorClass( $value ) {
412 $errors = $this->validate( $value, $this->mParent->mFieldData );
414 if ( $errors === true ||
415 ( !$this->mParent->getRequest()->wasPosted() && $this->mParent->getMethod() === 'post' )
417 $errors = '';
418 $errorClass = '';
419 } else {
420 $errors = self::formatErrors( $errors );
421 $errorClass = 'mw-htmlform-invalid-input';
424 return array( $errors, $errorClass );
427 function getLabel() {
428 return is_null( $this->mLabel ) ? '' : $this->mLabel;
431 function getLabelHtml( $cellAttributes = array() ) {
432 # Don't output a for= attribute for labels with no associated input.
433 # Kind of hacky here, possibly we don't want these to be <label>s at all.
434 $for = array();
436 if ( $this->needsLabel() ) {
437 $for['for'] = $this->mID;
440 $labelValue = trim( $this->getLabel() );
441 $hasLabel = false;
442 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
443 $hasLabel = true;
446 $displayFormat = $this->mParent->getDisplayFormat();
447 $html = '';
449 if ( $displayFormat === 'table' ) {
450 $html =
451 Html::rawElement( 'td',
452 array( 'class' => 'mw-label' ) + $cellAttributes,
453 Html::rawElement( 'label', $for, $labelValue ) );
454 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
455 if ( $displayFormat === 'div' ) {
456 $html =
457 Html::rawElement( 'div',
458 array( 'class' => 'mw-label' ) + $cellAttributes,
459 Html::rawElement( 'label', $for, $labelValue ) );
460 } else {
461 $html = Html::rawElement( 'label', $for, $labelValue );
465 return $html;
468 function getDefault() {
469 if ( isset( $this->mDefault ) ) {
470 return $this->mDefault;
471 } else {
472 return null;
477 * Returns the attributes required for the tooltip and accesskey.
479 * @return array Attributes
481 public function getTooltipAndAccessKey() {
482 if ( empty( $this->mParams['tooltip'] ) ) {
483 return array();
486 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
490 * Returns the given attributes from the parameters
492 * @param array $list List of attributes to get
493 * @return array Attributes
495 public function getAttributes( array $list ) {
496 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
498 $ret = array();
500 foreach ( $list as $key ) {
501 if ( in_array( $key, $boolAttribs ) ) {
502 if ( !empty( $this->mParams[$key] ) ) {
503 $ret[$key] = '';
505 } elseif ( isset( $this->mParams[$key] ) ) {
506 $ret[$key] = $this->mParams[$key];
510 return $ret;
514 * Given an array of msg-key => value mappings, returns an array with keys
515 * being the message texts. It also forces values to strings.
517 * @param array $options
518 * @return array
520 private function lookupOptionsKeys( $options ) {
521 $ret = array();
522 foreach ( $options as $key => $value ) {
523 $key = $this->msg( $key )->plain();
524 $ret[$key] = is_array( $value )
525 ? $this->lookupOptionsKeys( $value )
526 : strval( $value );
528 return $ret;
532 * Recursively forces values in an array to strings, because issues arise
533 * with integer 0 as a value.
535 * @param array $array
536 * @return array
538 static function forceToStringRecursive( $array ) {
539 if ( is_array( $array ) ) {
540 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
541 } else {
542 return strval( $array );
547 * Fetch the array of options from the field's parameters. In order, this
548 * checks 'options-messages', 'options', then 'options-message'.
550 * @return array|null Options array
552 public function getOptions() {
553 if ( $this->mOptions === false ) {
554 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
555 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
556 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
557 $this->mOptionsLabelsNotFromMessage = true;
558 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
559 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
560 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
561 $message = $this->msg( $this->mParams['options-message'] )->inContentLanguage()->plain();
563 $optgroup = false;
564 $this->mOptions = array();
565 foreach ( explode( "\n", $message ) as $option ) {
566 $value = trim( $option );
567 if ( $value == '' ) {
568 continue;
569 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
570 # A new group is starting...
571 $value = trim( substr( $value, 1 ) );
572 $optgroup = $value;
573 } elseif ( substr( $value, 0, 2 ) == '**' ) {
574 # groupmember
575 $opt = trim( substr( $value, 2 ) );
576 if ( $optgroup === false ) {
577 $this->mOptions[$opt] = $opt;
578 } else {
579 $this->mOptions[$optgroup][$opt] = $opt;
581 } else {
582 # groupless reason list
583 $optgroup = false;
584 $this->mOptions[$option] = $option;
587 } else {
588 $this->mOptions = null;
592 return $this->mOptions;
596 * flatten an array of options to a single array, for instance,
597 * a set of "<options>" inside "<optgroups>".
599 * @param array $options Associative Array with values either Strings or Arrays
600 * @return array Flattened input
602 public static function flattenOptions( $options ) {
603 $flatOpts = array();
605 foreach ( $options as $value ) {
606 if ( is_array( $value ) ) {
607 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
608 } else {
609 $flatOpts[] = $value;
613 return $flatOpts;
617 * Formats one or more errors as accepted by field validation-callback.
619 * @param string|Message|array $errors Array of strings or Message instances
620 * @return string HTML
621 * @since 1.18
623 protected static function formatErrors( $errors ) {
624 if ( is_array( $errors ) && count( $errors ) === 1 ) {
625 $errors = array_shift( $errors );
628 if ( is_array( $errors ) ) {
629 $lines = array();
630 foreach ( $errors as $error ) {
631 if ( $error instanceof Message ) {
632 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
633 } else {
634 $lines[] = Html::rawElement( 'li', array(), $error );
638 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
639 } else {
640 if ( $errors instanceof Message ) {
641 $errors = $errors->parse();
644 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );