Merge "Avoid bogus IE extension check errors in img_auth.php"
[lhc/web/wiklou.git] / includes / htmlform / HTMLFormField.php
1 <?php
2
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;
9
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;
19
20 /**
21 * @var bool If true will generate an empty div element with no label
22 * @since 1.22
23 */
24 protected $mShowEmptyLabels = true;
25
26 /**
27 * @var HTMLForm
28 */
29 public $mParent;
30
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.
35 *
36 * @param string $value the value to set the input to; eg a default
37 * text for a text input.
38 *
39 * @return string Valid HTML.
40 */
41 abstract function getInputHTML( $value );
42
43 /**
44 * Get a translated interface message
45 *
46 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
47 * and wfMessage() otherwise.
48 *
49 * Parameters are the same as wfMessage().
50 *
51 * @return Message
52 */
53 function msg() {
54 $args = func_get_args();
55
56 if ( $this->mParent ) {
57 $callback = array( $this->mParent, 'msg' );
58 } else {
59 $callback = 'wfMessage';
60 }
61
62 return call_user_func_array( $callback, $args );
63 }
64
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
69 *
70 * @param string $value The value the field was submitted with
71 * @param array $alldata The data collected from the form
72 *
73 * @return bool|string true on success, or String error to display.
74 */
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();
81 }
82
83 if ( isset( $this->mValidationCallback ) ) {
84 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
85 }
86
87 return true;
88 }
89
90 function filter( $value, $alldata ) {
91 if ( isset( $this->mFilterCallback ) ) {
92 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
93 }
94
95 return $value;
96 }
97
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?
101 *
102 * @return bool True to output a label, false to suppress
103 */
104 protected function needsLabel() {
105 return true;
106 }
107
108 /**
109 * Tell the field whether to generate a separate label element if its label
110 * is blank.
111 *
112 * @since 1.22
113 *
114 * @param bool $show Set to false to not generate a label.
115 * @return void
116 */
117 public function setShowEmptyLabel( $show ) {
118 $this->mShowEmptyLabels = $show;
119 }
120
121 /**
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.
124 *
125 * @param WebRequest $request
126 * @return string The value
127 */
128 function loadDataFromRequest( $request ) {
129 if ( $request->getCheck( $this->mName ) ) {
130 return $request->getText( $this->mName );
131 } else {
132 return $this->getDefault();
133 }
134 }
135
136 /**
137 * Initialise the object
138 *
139 * @param array $params Associative Array. See HTMLForm doc for syntax.
140 *
141 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
142 * @throws MWException
143 */
144 function __construct( $params ) {
145 $this->mParams = $params;
146
147 # Generate the label from a message, if possible
148 if ( isset( $params['label-message'] ) ) {
149 $msgInfo = $params['label-message'];
150
151 if ( is_array( $msgInfo ) ) {
152 $msg = array_shift( $msgInfo );
153 } else {
154 $msg = $msgInfo;
155 $msgInfo = array();
156 }
157
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'] );
165 }
166 } elseif ( isset( $params['label-raw'] ) ) {
167 $this->mLabel = $params['label-raw'];
168 }
169
170 $this->mName = "wp{$params['fieldname']}";
171 if ( isset( $params['name'] ) ) {
172 $this->mName = $params['name'];
173 }
174
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__ );
178 }
179
180 $this->mID = "mw-input-{$this->mName}";
181
182 if ( isset( $params['default'] ) ) {
183 $this->mDefault = $params['default'];
184 }
185
186 if ( isset( $params['id'] ) ) {
187 $id = $params['id'];
188 $validId = Sanitizer::escapeId( $id );
189
190 if ( $id != $validId ) {
191 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
192 }
193
194 $this->mID = $id;
195 }
196
197 if ( isset( $params['cssclass'] ) ) {
198 $this->mClass = $params['cssclass'];
199 }
200
201 if ( isset( $params['validation-callback'] ) ) {
202 $this->mValidationCallback = $params['validation-callback'];
203 }
204
205 if ( isset( $params['filter-callback'] ) ) {
206 $this->mFilterCallback = $params['filter-callback'];
207 }
208
209 if ( isset( $params['flatlist'] ) ) {
210 $this->mClass .= ' mw-htmlform-flatlist';
211 }
212
213 if ( isset( $params['hidelabel'] ) ) {
214 $this->mShowEmptyLabels = false;
215 }
216 }
217
218 /**
219 * Get the complete table row for the input, including help text,
220 * labels, and whatever.
221 *
222 * @param string $value The value to set the input to.
223 *
224 * @return string Complete HTML table row.
225 */
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();
232
233 if ( !empty( $this->mParams['vertical-label'] ) ) {
234 $cellAttributes['colspan'] = 2;
235 $verticalLabel = true;
236 } else {
237 $verticalLabel = false;
238 }
239
240 $label = $this->getLabelHtml( $cellAttributes );
241
242 $field = Html::rawElement(
243 'td',
244 array( 'class' => 'mw-input' ) + $cellAttributes,
245 $inputHtml . "\n$errors"
246 );
247
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 );
258 }
259
260 return $html . $helptext;
261 }
262
263 /**
264 * Get the complete div for the input, including help text,
265 * labels, and whatever.
266 * @since 1.20
267 *
268 * @param string $value The value to set the input to.
269 *
270 * @return string Complete HTML table row.
271 */
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 );
279
280 $outerDivClass = array(
281 'mw-input',
282 'mw-htmlform-nolabel' => ( $label === '' )
283 );
284
285 $field = Html::rawElement(
286 'div',
287 array( 'class' => $outerDivClass ) + $cellAttributes,
288 $inputHtml . "\n$errors"
289 );
290 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass, $errorClass );
291 if ( $this->mParent->isVForm() ) {
292 $divCssClasses[] = 'mw-ui-vform-div';
293 }
294 $html = Html::rawElement( 'div', array( 'class' => $divCssClasses ), $label . $field );
295 $html .= $helptext;
296
297 return $html;
298 }
299
300 /**
301 * Get the complete raw fields for the input, including help text,
302 * labels, and whatever.
303 * @since 1.20
304 *
305 * @param string $value The value to set the input to.
306 *
307 * @return string Complete HTML table row.
308 */
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 );
315
316 $html = "\n$errors";
317 $html .= $label;
318 $html .= $inputHtml;
319 $html .= $helptext;
320
321 return $html;
322 }
323
324 /**
325 * Generate help text HTML in table format
326 * @since 1.20
327 *
328 * @param string|null $helptext
329 * @return string
330 */
331 public function getHelpTextHtmlTable( $helptext ) {
332 if ( is_null( $helptext ) ) {
333 return '';
334 }
335
336 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ), $helptext );
337 $row = Html::rawElement( 'tr', array(), $row );
338
339 return $row;
340 }
341
342 /**
343 * Generate help text HTML in div format
344 * @since 1.20
345 *
346 * @param string|null $helptext
347 *
348 * @return string
349 */
350 public function getHelpTextHtmlDiv( $helptext ) {
351 if ( is_null( $helptext ) ) {
352 return '';
353 }
354
355 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
356
357 return $div;
358 }
359
360 /**
361 * Generate help text HTML formatted for raw output
362 * @since 1.20
363 *
364 * @param string|null $helptext
365 * @return string
366 */
367 public function getHelpTextHtmlRaw( $helptext ) {
368 return $this->getHelpTextHtmlDiv( $helptext );
369 }
370
371 /**
372 * Determine the help text to display
373 * @since 1.20
374 * @return string
375 */
376 public function getHelpText() {
377 $helptext = null;
378
379 if ( isset( $this->mParams['help-message'] ) ) {
380 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
381 }
382
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 );
387
388 if ( $msg->exists() ) {
389 if ( is_null( $helptext ) ) {
390 $helptext = '';
391 } else {
392 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
393 }
394 $helptext .= $msg->parse(); // Append message
395 }
396 }
397 } elseif ( isset( $this->mParams['help'] ) ) {
398 $helptext = $this->mParams['help'];
399 }
400
401 return $helptext;
402 }
403
404 /**
405 * Determine form errors to display and their classes
406 * @since 1.20
407 *
408 * @param string $value The value of the input
409 * @return array
410 */
411 public function getErrorsAndErrorClass( $value ) {
412 $errors = $this->validate( $value, $this->mParent->mFieldData );
413
414 if ( $errors === true ||
415 ( !$this->mParent->getRequest()->wasPosted() && $this->mParent->getMethod() === 'post' )
416 ) {
417 $errors = '';
418 $errorClass = '';
419 } else {
420 $errors = self::formatErrors( $errors );
421 $errorClass = 'mw-htmlform-invalid-input';
422 }
423
424 return array( $errors, $errorClass );
425 }
426
427 function getLabel() {
428 return is_null( $this->mLabel ) ? '' : $this->mLabel;
429 }
430
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();
435
436 if ( $this->needsLabel() ) {
437 $for['for'] = $this->mID;
438 }
439
440 $labelValue = trim( $this->getLabel() );
441 $hasLabel = false;
442 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
443 $hasLabel = true;
444 }
445
446 $displayFormat = $this->mParent->getDisplayFormat();
447 $html = '';
448
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 );
462 }
463 }
464
465 return $html;
466 }
467
468 function getDefault() {
469 if ( isset( $this->mDefault ) ) {
470 return $this->mDefault;
471 } else {
472 return null;
473 }
474 }
475
476 /**
477 * Returns the attributes required for the tooltip and accesskey.
478 *
479 * @return array Attributes
480 */
481 public function getTooltipAndAccessKey() {
482 if ( empty( $this->mParams['tooltip'] ) ) {
483 return array();
484 }
485
486 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
487 }
488
489 /**
490 * Returns the given attributes from the parameters
491 *
492 * @param array $list List of attributes to get
493 * @return array Attributes
494 */
495 public function getAttributes( array $list ) {
496 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
497
498 $ret = array();
499
500 foreach ( $list as $key ) {
501 if ( in_array( $key, $boolAttribs ) ) {
502 if ( !empty( $this->mParams[$key] ) ) {
503 $ret[$key] = '';
504 }
505 } elseif ( isset( $this->mParams[$key] ) ) {
506 $ret[$key] = $this->mParams[$key];
507 }
508 }
509
510 return $ret;
511 }
512
513 /**
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.
516 *
517 * @param array $options
518 * @return array
519 */
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 );
527 }
528 return $ret;
529 }
530
531 /**
532 * Recursively forces values in an array to strings, because issues arise
533 * with integer 0 as a value.
534 *
535 * @param array $array
536 * @return array
537 */
538 static function forceToStringRecursive( $array ) {
539 if ( is_array( $array ) ) {
540 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
541 } else {
542 return strval( $array );
543 }
544 }
545
546 /**
547 * Fetch the array of options from the field's parameters. In order, this
548 * checks 'options-messages', 'options', then 'options-message'.
549 *
550 * @return array|null Options array
551 */
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();
562
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;
580 }
581 } else {
582 # groupless reason list
583 $optgroup = false;
584 $this->mOptions[$option] = $option;
585 }
586 }
587 } else {
588 $this->mOptions = null;
589 }
590 }
591
592 return $this->mOptions;
593 }
594
595 /**
596 * flatten an array of options to a single array, for instance,
597 * a set of "<options>" inside "<optgroups>".
598 *
599 * @param array $options Associative Array with values either Strings or Arrays
600 * @return array Flattened input
601 */
602 public static function flattenOptions( $options ) {
603 $flatOpts = array();
604
605 foreach ( $options as $value ) {
606 if ( is_array( $value ) ) {
607 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
608 } else {
609 $flatOpts[] = $value;
610 }
611 }
612
613 return $flatOpts;
614 }
615
616 /**
617 * Formats one or more errors as accepted by field validation-callback.
618 *
619 * @param string|Message|array $errors Array of strings or Message instances
620 * @return string HTML
621 * @since 1.18
622 */
623 protected static function formatErrors( $errors ) {
624 if ( is_array( $errors ) && count( $errors ) === 1 ) {
625 $errors = array_shift( $errors );
626 }
627
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 );
635 }
636 }
637
638 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
639 } else {
640 if ( $errors instanceof Message ) {
641 $errors = $errors->parse();
642 }
643
644 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
645 }
646 }
647 }