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