Merge "Use Context in Article::delete for messages"
[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 $mHelpClass = false;
17 protected $mDefault;
18 protected $mOptions = false;
19 protected $mOptionsLabelsNotFromMessage = false;
20 protected $mHideIf = null;
21
22 /**
23 * @var bool If true will generate an empty div element with no label
24 * @since 1.22
25 */
26 protected $mShowEmptyLabels = true;
27
28 /**
29 * @var HTMLForm
30 */
31 public $mParent;
32
33 /**
34 * This function must be implemented to return the HTML to generate
35 * the input object itself. It should not implement the surrounding
36 * table cells/rows, or labels/help messages.
37 *
38 * @param string $value The value to set the input to; eg a default
39 * text for a text input.
40 *
41 * @return string Valid HTML.
42 */
43 abstract function getInputHTML( $value );
44
45 /**
46 * Get a translated interface message
47 *
48 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
49 * and wfMessage() otherwise.
50 *
51 * Parameters are the same as wfMessage().
52 *
53 * @return Message
54 */
55 function msg() {
56 $args = func_get_args();
57
58 if ( $this->mParent ) {
59 $callback = array( $this->mParent, 'msg' );
60 } else {
61 $callback = 'wfMessage';
62 }
63
64 return call_user_func_array( $callback, $args );
65 }
66
67
68 /**
69 * Fetch a field value from $alldata for the closest field matching a given
70 * name.
71 *
72 * This is complex because it needs to handle array fields like the user
73 * would expect. The general algorithm is to look for $name as a sibling
74 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
75 * that $name itself might be referencing an array.
76 *
77 * @param array $alldata
78 * @param string $name
79 * @return string
80 */
81 protected function getNearestFieldByName( $alldata, $name ) {
82 $tmp = $this->mName;
83 $thisKeys = array();
84 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
85 array_unshift( $thisKeys, $m[2] );
86 $tmp = $m[1];
87 }
88 if ( substr( $tmp, 0, 2 ) == 'wp' &&
89 !isset( $alldata[$tmp] ) &&
90 isset( $alldata[substr( $tmp, 2 )] )
91 ) {
92 // Adjust for name mangling.
93 $tmp = substr( $tmp, 2 );
94 }
95 array_unshift( $thisKeys, $tmp );
96
97 $tmp = $name;
98 $nameKeys = array();
99 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
100 array_unshift( $nameKeys, $m[2] );
101 $tmp = $m[1];
102 }
103 array_unshift( $nameKeys, $tmp );
104
105 $testValue = '';
106 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
107 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
108 $data = $alldata;
109 while ( $keys ) {
110 $key = array_shift( $keys );
111 if ( !is_array( $data ) || !isset( $data[$key] ) ) {
112 continue 2;
113 }
114 $data = $data[$key];
115 }
116 $testValue = (string)$data;
117 break;
118 }
119
120 return $testValue;
121 }
122
123 /**
124 * Helper function for isHidden to handle recursive data structures.
125 *
126 * @param array $alldata
127 * @param array $params
128 * @return bool
129 */
130 protected function isHiddenRecurse( array $alldata, array $params ) {
131 $origParams = $params;
132 $op = array_shift( $params );
133
134 try {
135 switch ( $op ) {
136 case 'AND':
137 foreach ( $params as $i => $p ) {
138 if ( !is_array( $p ) ) {
139 throw new MWException(
140 "Expected array, found " . gettype( $p ) . " at index $i"
141 );
142 }
143 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
144 return false;
145 }
146 }
147 return true;
148
149 case 'OR':
150 foreach ( $params as $p ) {
151 if ( !is_array( $p ) ) {
152 throw new MWException(
153 "Expected array, found " . gettype( $p ) . " at index $i"
154 );
155 }
156 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
157 return true;
158 }
159 }
160 return false;
161
162 case 'NAND':
163 foreach ( $params as $i => $p ) {
164 if ( !is_array( $p ) ) {
165 throw new MWException(
166 "Expected array, found " . gettype( $p ) . " at index $i"
167 );
168 }
169 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
170 return true;
171 }
172 }
173 return false;
174
175 case 'NOR':
176 foreach ( $params as $p ) {
177 if ( !is_array( $p ) ) {
178 throw new MWException(
179 "Expected array, found " . gettype( $p ) . " at index $i"
180 );
181 }
182 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
183 return false;
184 }
185 }
186 return true;
187
188 case 'NOT':
189 if ( count( $params ) !== 1 ) {
190 throw new MWException( "NOT takes exactly one parameter" );
191 }
192 $p = $params[0];
193 if ( !is_array( $p ) ) {
194 throw new MWException(
195 "Expected array, found " . gettype( $p ) . " at index 0"
196 );
197 }
198 return !$this->isHiddenRecurse( $alldata, $p );
199
200 case '===':
201 case '!==':
202 if ( count( $params ) !== 2 ) {
203 throw new MWException( "$op takes exactly two parameters" );
204 }
205 list( $field, $value ) = $params;
206 if ( !is_string( $field ) || !is_string( $value ) ) {
207 throw new MWException( "Parameters for $op must be strings" );
208 }
209 $testValue = $this->getNearestFieldByName( $alldata, $field );
210 switch ( $op ) {
211 case '===':
212 return ( $value === $testValue );
213 case '!==':
214 return ( $value !== $testValue );
215 }
216
217 default:
218 throw new MWException( "Unknown operation" );
219 }
220 } catch ( MWException $ex ) {
221 throw new MWException(
222 "Invalid hide-if specification for $this->mName: " .
223 $ex->getMessage() . " in " . var_export( $origParams, true ),
224 0, $ex
225 );
226 }
227 }
228
229 /**
230 * Test whether this field is supposed to be hidden, based on the values of
231 * the other form fields.
232 *
233 * @since 1.23
234 * @param array $alldata The data collected from the form
235 * @return bool
236 */
237 function isHidden( $alldata ) {
238 if ( !$this->mHideIf ) {
239 return false;
240 }
241
242 return $this->isHiddenRecurse( $alldata, $this->mHideIf );
243 }
244
245 /**
246 * Override this function if the control can somehow trigger a form
247 * submission that shouldn't actually submit the HTMLForm.
248 *
249 * @since 1.23
250 * @param string|array $value The value the field was submitted with
251 * @param array $alldata The data collected from the form
252 *
253 * @return bool True to cancel the submission
254 */
255 function cancelSubmit( $value, $alldata ) {
256 return false;
257 }
258
259 /**
260 * Override this function to add specific validation checks on the
261 * field input. Don't forget to call parent::validate() to ensure
262 * that the user-defined callback mValidationCallback is still run
263 *
264 * @param string|array $value The value the field was submitted with
265 * @param array $alldata The data collected from the form
266 *
267 * @return bool|string True on success, or String error to display, or
268 * false to fail validation without displaying an error.
269 */
270 function validate( $value, $alldata ) {
271 if ( $this->isHidden( $alldata ) ) {
272 return true;
273 }
274
275 if ( isset( $this->mParams['required'] )
276 && $this->mParams['required'] !== false
277 && $value === ''
278 ) {
279 return $this->msg( 'htmlform-required' )->parse();
280 }
281
282 if ( isset( $this->mValidationCallback ) ) {
283 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
284 }
285
286 return true;
287 }
288
289 function filter( $value, $alldata ) {
290 if ( isset( $this->mFilterCallback ) ) {
291 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
292 }
293
294 return $value;
295 }
296
297 /**
298 * Should this field have a label, or is there no input element with the
299 * appropriate id for the label to point to?
300 *
301 * @return bool True to output a label, false to suppress
302 */
303 protected function needsLabel() {
304 return true;
305 }
306
307 /**
308 * Tell the field whether to generate a separate label element if its label
309 * is blank.
310 *
311 * @since 1.22
312 *
313 * @param bool $show Set to false to not generate a label.
314 * @return void
315 */
316 public function setShowEmptyLabel( $show ) {
317 $this->mShowEmptyLabels = $show;
318 }
319
320 /**
321 * Get the value that this input has been set to from a posted form,
322 * or the input's default value if it has not been set.
323 *
324 * @param WebRequest $request
325 * @return string The value
326 */
327 function loadDataFromRequest( $request ) {
328 if ( $request->getCheck( $this->mName ) ) {
329 return $request->getText( $this->mName );
330 } else {
331 return $this->getDefault();
332 }
333 }
334
335 /**
336 * Initialise the object
337 *
338 * @param array $params Associative Array. See HTMLForm doc for syntax.
339 *
340 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
341 * @throws MWException
342 */
343 function __construct( $params ) {
344 $this->mParams = $params;
345
346 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
347 $this->mParent = $params['parent'];
348 }
349
350 # Generate the label from a message, if possible
351 if ( isset( $params['label-message'] ) ) {
352 $msgInfo = $params['label-message'];
353
354 if ( is_array( $msgInfo ) ) {
355 $msg = array_shift( $msgInfo );
356 } else {
357 $msg = $msgInfo;
358 $msgInfo = array();
359 }
360
361 $this->mLabel = $this->msg( $msg, $msgInfo )->parse();
362 } elseif ( isset( $params['label'] ) ) {
363 if ( $params['label'] === '&#160;' ) {
364 // Apparently some things set &nbsp directly and in an odd format
365 $this->mLabel = '&#160;';
366 } else {
367 $this->mLabel = htmlspecialchars( $params['label'] );
368 }
369 } elseif ( isset( $params['label-raw'] ) ) {
370 $this->mLabel = $params['label-raw'];
371 }
372
373 $this->mName = "wp{$params['fieldname']}";
374 if ( isset( $params['name'] ) ) {
375 $this->mName = $params['name'];
376 }
377
378 $validName = Sanitizer::escapeId( $this->mName );
379 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
380 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
381 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
382 }
383
384 $this->mID = "mw-input-{$this->mName}";
385
386 if ( isset( $params['default'] ) ) {
387 $this->mDefault = $params['default'];
388 }
389
390 if ( isset( $params['id'] ) ) {
391 $id = $params['id'];
392 $validId = Sanitizer::escapeId( $id );
393
394 if ( $id != $validId ) {
395 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
396 }
397
398 $this->mID = $id;
399 }
400
401 if ( isset( $params['cssclass'] ) ) {
402 $this->mClass = $params['cssclass'];
403 }
404
405 if ( isset( $params['csshelpclass'] ) ) {
406 $this->mHelpClass = $params['csshelpclass'];
407 }
408
409 if ( isset( $params['validation-callback'] ) ) {
410 $this->mValidationCallback = $params['validation-callback'];
411 }
412
413 if ( isset( $params['filter-callback'] ) ) {
414 $this->mFilterCallback = $params['filter-callback'];
415 }
416
417 if ( isset( $params['flatlist'] ) ) {
418 $this->mClass .= ' mw-htmlform-flatlist';
419 }
420
421 if ( isset( $params['hidelabel'] ) ) {
422 $this->mShowEmptyLabels = false;
423 }
424
425 if ( isset( $params['hide-if'] ) ) {
426 $this->mHideIf = $params['hide-if'];
427 }
428 }
429
430 /**
431 * Get the complete table row for the input, including help text,
432 * labels, and whatever.
433 *
434 * @param string $value The value to set the input to.
435 *
436 * @return string Complete HTML table row.
437 */
438 function getTableRow( $value ) {
439 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
440 $inputHtml = $this->getInputHTML( $value );
441 $fieldType = get_class( $this );
442 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
443 $cellAttributes = array();
444 $rowAttributes = array();
445 $rowClasses = '';
446
447 if ( !empty( $this->mParams['vertical-label'] ) ) {
448 $cellAttributes['colspan'] = 2;
449 $verticalLabel = true;
450 } else {
451 $verticalLabel = false;
452 }
453
454 $label = $this->getLabelHtml( $cellAttributes );
455
456 $field = Html::rawElement(
457 'td',
458 array( 'class' => 'mw-input' ) + $cellAttributes,
459 $inputHtml . "\n$errors"
460 );
461
462 if ( $this->mHideIf ) {
463 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
464 $rowClasses .= ' mw-htmlform-hide-if';
465 }
466
467 if ( $verticalLabel ) {
468 $html = Html::rawElement( 'tr',
469 $rowAttributes + array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
470 $html .= Html::rawElement( 'tr',
471 $rowAttributes + array(
472 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
473 ),
474 $field );
475 } else {
476 $html =
477 Html::rawElement( 'tr',
478 $rowAttributes + array(
479 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
480 ),
481 $label . $field );
482 }
483
484 return $html . $helptext;
485 }
486
487 /**
488 * Get the complete div for the input, including help text,
489 * labels, and whatever.
490 * @since 1.20
491 *
492 * @param string $value The value to set the input to.
493 *
494 * @return string Complete HTML table row.
495 */
496 public function getDiv( $value ) {
497 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
498 $inputHtml = $this->getInputHTML( $value );
499 $fieldType = get_class( $this );
500 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
501 $cellAttributes = array();
502 $label = $this->getLabelHtml( $cellAttributes );
503
504 $outerDivClass = array(
505 'mw-input',
506 'mw-htmlform-nolabel' => ( $label === '' )
507 );
508
509 $field = Html::rawElement(
510 'div',
511 array( 'class' => $outerDivClass ) + $cellAttributes,
512 $inputHtml . "\n$errors"
513 );
514 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass, $errorClass );
515 if ( $this->mParent->isVForm() ) {
516 $divCssClasses[] = 'mw-ui-vform-field';
517 }
518
519 $wrapperAttributes = array(
520 'class' => $divCssClasses,
521 );
522 if ( $this->mHideIf ) {
523 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
524 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
525 }
526 $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
527 $html .= $helptext;
528
529 return $html;
530 }
531
532 /**
533 * Get the complete raw fields for the input, including help text,
534 * labels, and whatever.
535 * @since 1.20
536 *
537 * @param string $value The value to set the input to.
538 *
539 * @return string Complete HTML table row.
540 */
541 public function getRaw( $value ) {
542 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
543 $inputHtml = $this->getInputHTML( $value );
544 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
545 $cellAttributes = array();
546 $label = $this->getLabelHtml( $cellAttributes );
547
548 $html = "\n$errors";
549 $html .= $label;
550 $html .= $inputHtml;
551 $html .= $helptext;
552
553 return $html;
554 }
555
556 /**
557 * Generate help text HTML in table format
558 * @since 1.20
559 *
560 * @param string|null $helptext
561 * @return string
562 */
563 public function getHelpTextHtmlTable( $helptext ) {
564 if ( is_null( $helptext ) ) {
565 return '';
566 }
567
568 $rowAttributes = array();
569 if ( $this->mHideIf ) {
570 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
571 $rowAttributes['class'] = 'mw-htmlform-hide-if';
572 }
573
574 $tdClasses = array( 'htmlform-tip' );
575 if ( $this->mHelpClass !== false ) {
576 $tdClasses[] = $this->mHelpClass;
577 }
578 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
579 $row = Html::rawElement( 'tr', $rowAttributes, $row );
580
581 return $row;
582 }
583
584 /**
585 * Generate help text HTML in div format
586 * @since 1.20
587 *
588 * @param string|null $helptext
589 *
590 * @return string
591 */
592 public function getHelpTextHtmlDiv( $helptext ) {
593 if ( is_null( $helptext ) ) {
594 return '';
595 }
596
597 $wrapperAttributes = array(
598 'class' => 'htmlform-tip',
599 );
600 if ( $this->mHelpClass !== false ) {
601 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
602 }
603 if ( $this->mHideIf ) {
604 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
605 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
606 }
607 $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
608
609 return $div;
610 }
611
612 /**
613 * Generate help text HTML formatted for raw output
614 * @since 1.20
615 *
616 * @param string|null $helptext
617 * @return string
618 */
619 public function getHelpTextHtmlRaw( $helptext ) {
620 return $this->getHelpTextHtmlDiv( $helptext );
621 }
622
623 /**
624 * Determine the help text to display
625 * @since 1.20
626 * @return string
627 */
628 public function getHelpText() {
629 $helptext = null;
630
631 if ( isset( $this->mParams['help-message'] ) ) {
632 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
633 }
634
635 if ( isset( $this->mParams['help-messages'] ) ) {
636 foreach ( $this->mParams['help-messages'] as $name ) {
637 $helpMessage = (array)$name;
638 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
639
640 if ( $msg->exists() ) {
641 if ( is_null( $helptext ) ) {
642 $helptext = '';
643 } else {
644 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
645 }
646 $helptext .= $msg->parse(); // Append message
647 }
648 }
649 } elseif ( isset( $this->mParams['help'] ) ) {
650 $helptext = $this->mParams['help'];
651 }
652
653 return $helptext;
654 }
655
656 /**
657 * Determine form errors to display and their classes
658 * @since 1.20
659 *
660 * @param string $value The value of the input
661 * @return array
662 */
663 public function getErrorsAndErrorClass( $value ) {
664 $errors = $this->validate( $value, $this->mParent->mFieldData );
665
666 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
667 $errors = '';
668 $errorClass = '';
669 } else {
670 $errors = self::formatErrors( $errors );
671 $errorClass = 'mw-htmlform-invalid-input';
672 }
673
674 return array( $errors, $errorClass );
675 }
676
677 function getLabel() {
678 return is_null( $this->mLabel ) ? '' : $this->mLabel;
679 }
680
681 function getLabelHtml( $cellAttributes = array() ) {
682 # Don't output a for= attribute for labels with no associated input.
683 # Kind of hacky here, possibly we don't want these to be <label>s at all.
684 $for = array();
685
686 if ( $this->needsLabel() ) {
687 $for['for'] = $this->mID;
688 }
689
690 $labelValue = trim( $this->getLabel() );
691 $hasLabel = false;
692 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
693 $hasLabel = true;
694 }
695
696 $displayFormat = $this->mParent->getDisplayFormat();
697 $html = '';
698
699 if ( $displayFormat === 'table' ) {
700 $html =
701 Html::rawElement( 'td',
702 array( 'class' => 'mw-label' ) + $cellAttributes,
703 Html::rawElement( 'label', $for, $labelValue ) );
704 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
705 if ( $displayFormat === 'div' ) {
706 $html =
707 Html::rawElement( 'div',
708 array( 'class' => 'mw-label' ) + $cellAttributes,
709 Html::rawElement( 'label', $for, $labelValue ) );
710 } else {
711 $html = Html::rawElement( 'label', $for, $labelValue );
712 }
713 }
714
715 return $html;
716 }
717
718 function getDefault() {
719 if ( isset( $this->mDefault ) ) {
720 return $this->mDefault;
721 } else {
722 return null;
723 }
724 }
725
726 /**
727 * Returns the attributes required for the tooltip and accesskey.
728 *
729 * @return array Attributes
730 */
731 public function getTooltipAndAccessKey() {
732 if ( empty( $this->mParams['tooltip'] ) ) {
733 return array();
734 }
735
736 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
737 }
738
739 /**
740 * Returns the given attributes from the parameters
741 *
742 * @param array $list List of attributes to get
743 * @return array Attributes
744 */
745 public function getAttributes( array $list ) {
746 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
747
748 $ret = array();
749
750 foreach ( $list as $key ) {
751 if ( in_array( $key, $boolAttribs ) ) {
752 if ( !empty( $this->mParams[$key] ) ) {
753 $ret[$key] = '';
754 }
755 } elseif ( isset( $this->mParams[$key] ) ) {
756 $ret[$key] = $this->mParams[$key];
757 }
758 }
759
760 return $ret;
761 }
762
763 /**
764 * Given an array of msg-key => value mappings, returns an array with keys
765 * being the message texts. It also forces values to strings.
766 *
767 * @param array $options
768 * @return array
769 */
770 private function lookupOptionsKeys( $options ) {
771 $ret = array();
772 foreach ( $options as $key => $value ) {
773 $key = $this->msg( $key )->plain();
774 $ret[$key] = is_array( $value )
775 ? $this->lookupOptionsKeys( $value )
776 : strval( $value );
777 }
778 return $ret;
779 }
780
781 /**
782 * Recursively forces values in an array to strings, because issues arise
783 * with integer 0 as a value.
784 *
785 * @param array $array
786 * @return array
787 */
788 static function forceToStringRecursive( $array ) {
789 if ( is_array( $array ) ) {
790 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
791 } else {
792 return strval( $array );
793 }
794 }
795
796 /**
797 * Fetch the array of options from the field's parameters. In order, this
798 * checks 'options-messages', 'options', then 'options-message'.
799 *
800 * @return array|null Options array
801 */
802 public function getOptions() {
803 if ( $this->mOptions === false ) {
804 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
805 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
806 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
807 $this->mOptionsLabelsNotFromMessage = true;
808 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
809 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
810 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
811 $message = $this->msg( $this->mParams['options-message'] )->inContentLanguage()->plain();
812
813 $optgroup = false;
814 $this->mOptions = array();
815 foreach ( explode( "\n", $message ) as $option ) {
816 $value = trim( $option );
817 if ( $value == '' ) {
818 continue;
819 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
820 # A new group is starting...
821 $value = trim( substr( $value, 1 ) );
822 $optgroup = $value;
823 } elseif ( substr( $value, 0, 2 ) == '**' ) {
824 # groupmember
825 $opt = trim( substr( $value, 2 ) );
826 if ( $optgroup === false ) {
827 $this->mOptions[$opt] = $opt;
828 } else {
829 $this->mOptions[$optgroup][$opt] = $opt;
830 }
831 } else {
832 # groupless reason list
833 $optgroup = false;
834 $this->mOptions[$option] = $option;
835 }
836 }
837 } else {
838 $this->mOptions = null;
839 }
840 }
841
842 return $this->mOptions;
843 }
844
845 /**
846 * flatten an array of options to a single array, for instance,
847 * a set of "<options>" inside "<optgroups>".
848 *
849 * @param array $options Associative Array with values either Strings or Arrays
850 * @return array Flattened input
851 */
852 public static function flattenOptions( $options ) {
853 $flatOpts = array();
854
855 foreach ( $options as $value ) {
856 if ( is_array( $value ) ) {
857 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
858 } else {
859 $flatOpts[] = $value;
860 }
861 }
862
863 return $flatOpts;
864 }
865
866 /**
867 * Formats one or more errors as accepted by field validation-callback.
868 *
869 * @param string|Message|array $errors Array of strings or Message instances
870 * @return string HTML
871 * @since 1.18
872 */
873 protected static function formatErrors( $errors ) {
874 if ( is_array( $errors ) && count( $errors ) === 1 ) {
875 $errors = array_shift( $errors );
876 }
877
878 if ( is_array( $errors ) ) {
879 $lines = array();
880 foreach ( $errors as $error ) {
881 if ( $error instanceof Message ) {
882 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
883 } else {
884 $lines[] = Html::rawElement( 'li', array(), $error );
885 }
886 }
887
888 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
889 } else {
890 if ( $errors instanceof Message ) {
891 $errors = $errors->parse();
892 }
893
894 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
895 }
896 }
897 }