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