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