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