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