MediaWiki  master
HTMLFormField.php
Go to the documentation of this file.
1 <?php
2 
7 abstract class HTMLFormField {
9  public $mParams;
10 
12  protected $mFilterCallback;
13  protected $mName;
14  protected $mDir;
15  protected $mLabel; # String label, as HTML. Set on construction.
16  protected $mID;
17  protected $mClass = '';
18  protected $mVFormClass = '';
19  protected $mHelpClass = false;
20  protected $mDefault;
24  protected $mOptions = false;
25  protected $mOptionsLabelsNotFromMessage = false;
26  protected $mHideIf = null;
27 
32  protected $mShowEmptyLabels = true;
33 
37  public $mParent;
38 
49  abstract public function getInputHTML( $value );
50 
58  public function getInputOOUI( $value ) {
59  return false;
60  }
61 
67  public function canDisplayErrors() {
68  return $this->hasVisibleOutput();
69  }
70 
83  public function msg( $key, ...$params ) {
84  if ( $this->mParent ) {
85  return $this->mParent->msg( $key, ...$params );
86  }
87  return wfMessage( $key, ...$params );
88  }
89 
96  public function hasVisibleOutput() {
97  return true;
98  }
99 
113  protected function getNearestFieldByName( $alldata, $name ) {
114  $tmp = $this->mName;
115  $thisKeys = [];
116  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
117  array_unshift( $thisKeys, $m[2] );
118  $tmp = $m[1];
119  }
120  if ( substr( $tmp, 0, 2 ) == 'wp' &&
121  !array_key_exists( $tmp, $alldata ) &&
122  array_key_exists( substr( $tmp, 2 ), $alldata )
123  ) {
124  // Adjust for name mangling.
125  $tmp = substr( $tmp, 2 );
126  }
127  array_unshift( $thisKeys, $tmp );
128 
129  $tmp = $name;
130  $nameKeys = [];
131  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
132  array_unshift( $nameKeys, $m[2] );
133  $tmp = $m[1];
134  }
135  array_unshift( $nameKeys, $tmp );
136 
137  $testValue = '';
138  for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
139  $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
140  $data = $alldata;
141  foreach ( $keys as $key ) {
142  if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
143  continue 2;
144  }
145  $data = $data[$key];
146  }
147  $testValue = (string)$data;
148  break;
149  }
150 
151  return $testValue;
152  }
153 
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 $i => $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 $i => $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 
269  public function isHidden( $alldata ) {
270  if ( !$this->mHideIf ) {
271  return false;
272  }
273 
274  return $this->isHiddenRecurse( $alldata, $this->mHideIf );
275  }
276 
287  public function cancelSubmit( $value, $alldata ) {
288  return false;
289  }
290 
302  public 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' );
312  }
313 
314  if ( isset( $this->mValidationCallback ) ) {
315  return ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
316  }
317 
318  return true;
319  }
320 
321  public function filter( $value, $alldata ) {
322  if ( isset( $this->mFilterCallback ) ) {
323  $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
324  }
325 
326  return $value;
327  }
328 
335  protected function needsLabel() {
336  return true;
337  }
338 
348  public function setShowEmptyLabel( $show ) {
349  $this->mShowEmptyLabels = $show;
350  }
351 
362  protected function isSubmitAttempt( WebRequest $request ) {
363  return $request->getCheck( 'wpEditToken' ) || $request->getCheck( 'wpFormIdentifier' );
364  }
365 
373  public function loadDataFromRequest( $request ) {
374  if ( $request->getCheck( $this->mName ) ) {
375  return $request->getText( $this->mName );
376  } else {
377  return $this->getDefault();
378  }
379  }
380 
389  public function __construct( $params ) {
390  $this->mParams = $params;
391 
392  if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
393  $this->mParent = $params['parent'];
394  }
395 
396  # Generate the label from a message, if possible
397  if ( isset( $params['label-message'] ) ) {
398  $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
399  } elseif ( isset( $params['label'] ) ) {
400  if ( $params['label'] === '&#160;' || $params['label'] === "\u{00A0}" ) {
401  // Apparently some things set &nbsp directly and in an odd format
402  $this->mLabel = "\u{00A0}";
403  } else {
404  $this->mLabel = htmlspecialchars( $params['label'] );
405  }
406  } elseif ( isset( $params['label-raw'] ) ) {
407  $this->mLabel = $params['label-raw'];
408  }
409 
410  $this->mName = "wp{$params['fieldname']}";
411  if ( isset( $params['name'] ) ) {
412  $this->mName = $params['name'];
413  }
414 
415  if ( isset( $params['dir'] ) ) {
416  $this->mDir = $params['dir'];
417  }
418 
419  $validName = urlencode( $this->mName );
420  $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
421  if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
422  throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
423  }
424 
425  $this->mID = "mw-input-{$this->mName}";
426 
427  if ( isset( $params['default'] ) ) {
428  $this->mDefault = $params['default'];
429  }
430 
431  if ( isset( $params['id'] ) ) {
432  $id = $params['id'];
433  $validId = urlencode( $id );
434 
435  if ( $id != $validId ) {
436  throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
437  }
438 
439  $this->mID = $id;
440  }
441 
442  if ( isset( $params['cssclass'] ) ) {
443  $this->mClass = $params['cssclass'];
444  }
445 
446  if ( isset( $params['csshelpclass'] ) ) {
447  $this->mHelpClass = $params['csshelpclass'];
448  }
449 
450  if ( isset( $params['validation-callback'] ) ) {
451  $this->mValidationCallback = $params['validation-callback'];
452  }
453 
454  if ( isset( $params['filter-callback'] ) ) {
455  $this->mFilterCallback = $params['filter-callback'];
456  }
457 
458  if ( isset( $params['hidelabel'] ) ) {
459  $this->mShowEmptyLabels = false;
460  }
461 
462  if ( isset( $params['hide-if'] ) ) {
463  $this->mHideIf = $params['hide-if'];
464  }
465  }
466 
475  public function getTableRow( $value ) {
476  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
477  $inputHtml = $this->getInputHTML( $value );
478  $fieldType = static::class;
479  $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
480  $cellAttributes = [];
481  $rowAttributes = [];
482  $rowClasses = '';
483 
484  if ( !empty( $this->mParams['vertical-label'] ) ) {
485  $cellAttributes['colspan'] = 2;
486  $verticalLabel = true;
487  } else {
488  $verticalLabel = false;
489  }
490 
491  $label = $this->getLabelHtml( $cellAttributes );
492 
493  $field = Html::rawElement(
494  'td',
495  [ 'class' => 'mw-input' ] + $cellAttributes,
496  $inputHtml . "\n$errors"
497  );
498 
499  if ( $this->mHideIf ) {
500  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
501  $rowClasses .= ' mw-htmlform-hide-if';
502  }
503 
504  if ( $verticalLabel ) {
505  $html = Html::rawElement( 'tr',
506  $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
507  $html .= Html::rawElement( 'tr',
508  $rowAttributes + [
509  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
510  ],
511  $field );
512  } else {
513  $html =
514  Html::rawElement( 'tr',
515  $rowAttributes + [
516  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
517  ],
518  $label . $field );
519  }
520 
521  return $html . $helptext;
522  }
523 
533  public function getDiv( $value ) {
534  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
535  $inputHtml = $this->getInputHTML( $value );
536  $fieldType = static::class;
537  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
538  $cellAttributes = [];
539  $label = $this->getLabelHtml( $cellAttributes );
540 
541  $outerDivClass = [
542  'mw-input',
543  'mw-htmlform-nolabel' => ( $label === '' )
544  ];
545 
546  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
547 
548  if ( $horizontalLabel ) {
549  $field = "\u{00A0}" . $inputHtml . "\n$errors";
550  } else {
551  $field = Html::rawElement(
552  'div',
553  // @phan-suppress-next-line PhanUselessBinaryAddRight
554  [ 'class' => $outerDivClass ] + $cellAttributes,
555  $inputHtml . "\n$errors"
556  );
557  }
558  $divCssClasses = [ "mw-htmlform-field-$fieldType",
559  $this->mClass, $this->mVFormClass, $errorClass ];
560 
561  $wrapperAttributes = [
562  'class' => $divCssClasses,
563  ];
564  if ( $this->mHideIf ) {
565  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
566  $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
567  }
568  $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
569  $html .= $helptext;
570 
571  return $html;
572  }
573 
582  public function getOOUI( $value ) {
583  $inputField = $this->getInputOOUI( $value );
584 
585  if ( !$inputField ) {
586  // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
587  // generate the whole field, label and errors and all, then wrap it in a Widget.
588  // It might look weird, but it'll work OK.
589  return $this->getFieldLayoutOOUI(
590  new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
591  [ 'align' => 'top' ]
592  );
593  }
594 
595  $infusable = true;
596  if ( is_string( $inputField ) ) {
597  // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
598  // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
599  // JavaScript doesn't know how to rebuilt the contents.
600  $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
601  $infusable = false;
602  }
603 
604  $fieldType = static::class;
605  $help = $this->getHelpText();
606  $errors = $this->getErrorsRaw( $value );
607  foreach ( $errors as &$error ) {
608  $error = new OOUI\HtmlSnippet( $error );
609  }
610 
611  $config = [
612  'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
613  'align' => $this->getLabelAlignOOUI(),
614  'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
615  'errors' => $errors,
616  'infusable' => $infusable,
617  'helpInline' => $this->isHelpInline(),
618  ];
619 
620  $preloadModules = false;
621 
622  if ( $infusable && $this->shouldInfuseOOUI() ) {
623  $preloadModules = true;
624  $config['classes'][] = 'mw-htmlform-field-autoinfuse';
625  }
626 
627  // the element could specify, that the label doesn't need to be added
628  $label = $this->getLabel();
629  if ( $label && $label !== "\u{00A0}" && $label !== '&#160;' ) {
630  $config['label'] = new OOUI\HtmlSnippet( $label );
631  }
632 
633  if ( $this->mHideIf ) {
634  $preloadModules = true;
635  $config['hideIf'] = $this->mHideIf;
636  }
637 
638  $config['modules'] = $this->getOOUIModules();
639 
640  if ( $preloadModules ) {
641  $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
642  $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
643  }
644 
645  return $this->getFieldLayoutOOUI( $inputField, $config );
646  }
647 
652  protected function getLabelAlignOOUI() {
653  return 'top';
654  }
655 
663  protected function getFieldLayoutOOUI( $inputField, $config ) {
664  if ( isset( $this->mClassWithButton ) ) {
665  $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
666  return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
667  }
668  return new HTMLFormFieldLayout( $inputField, $config );
669  }
670 
678  protected function shouldInfuseOOUI() {
679  // Always infuse fields with popup help text, since the interface for it is nicer with JS
680  return $this->getHelpText() !== null && !$this->isHelpInline();
681  }
682 
689  protected function getOOUIModules() {
690  return [];
691  }
692 
702  public function getRaw( $value ) {
703  list( $errors, ) = $this->getErrorsAndErrorClass( $value );
704  $inputHtml = $this->getInputHTML( $value );
705  $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
706  $cellAttributes = [];
707  $label = $this->getLabelHtml( $cellAttributes );
708 
709  $html = "\n$errors";
710  $html .= $label;
711  $html .= $inputHtml;
712  $html .= $helptext;
713 
714  return $html;
715  }
716 
725  public function getVForm( $value ) {
726  // Ewwww
727  $this->mVFormClass = ' mw-ui-vform-field';
728  return $this->getDiv( $value );
729  }
730 
737  public function getInline( $value ) {
738  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
739  $inputHtml = $this->getInputHTML( $value );
740  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
741  $cellAttributes = [];
742  $label = $this->getLabelHtml( $cellAttributes );
743 
744  $html = "\n" . $errors .
745  $label . "\u{00A0}" .
746  $inputHtml .
747  $helptext;
748 
749  return $html;
750  }
751 
759  public function getHelpTextHtmlTable( $helptext ) {
760  if ( $helptext === null ) {
761  return '';
762  }
763 
764  $rowAttributes = [];
765  if ( $this->mHideIf ) {
766  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
767  $rowAttributes['class'] = 'mw-htmlform-hide-if';
768  }
769 
770  $tdClasses = [ 'htmlform-tip' ];
771  if ( $this->mHelpClass !== false ) {
772  $tdClasses[] = $this->mHelpClass;
773  }
774  $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
775  $row = Html::rawElement( 'tr', $rowAttributes, $row );
776 
777  return $row;
778  }
779 
788  public function getHelpTextHtmlDiv( $helptext ) {
789  if ( $helptext === null ) {
790  return '';
791  }
792 
793  $wrapperAttributes = [
794  'class' => 'htmlform-tip',
795  ];
796  if ( $this->mHelpClass !== false ) {
797  $wrapperAttributes['class'] .= " {$this->mHelpClass}";
798  }
799  if ( $this->mHideIf ) {
800  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
801  $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
802  }
803  $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
804 
805  return $div;
806  }
807 
815  public function getHelpTextHtmlRaw( $helptext ) {
816  return $this->getHelpTextHtmlDiv( $helptext );
817  }
818 
824  public function getHelpText() {
825  $helptext = null;
826 
827  if ( isset( $this->mParams['help-message'] ) ) {
828  $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
829  }
830 
831  if ( isset( $this->mParams['help-messages'] ) ) {
832  foreach ( $this->mParams['help-messages'] as $msg ) {
833  $msg = $this->getMessage( $msg );
834 
835  if ( $msg->exists() ) {
836  if ( $helptext === null ) {
837  $helptext = '';
838  } else {
839  $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
840  }
841  $helptext .= $msg->parse(); // Append message
842  }
843  }
844  } elseif ( isset( $this->mParams['help'] ) ) {
845  $helptext = $this->mParams['help'];
846  }
847 
848  return $helptext;
849  }
850 
859  public function isHelpInline() {
860  return $this->mParams['help-inline'] ?? true;
861  }
862 
875  public function getErrorsAndErrorClass( $value ) {
876  $errors = $this->validate( $value, $this->mParent->mFieldData );
877 
878  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
879  $errors = '';
880  $errorClass = '';
881  } else {
882  $errors = self::formatErrors( $errors );
883  $errorClass = 'mw-htmlform-invalid-input';
884  }
885 
886  return [ $errors, $errorClass ];
887  }
888 
896  public function getErrorsRaw( $value ) {
897  $errors = $this->validate( $value, $this->mParent->mFieldData );
898 
899  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
900  $errors = [];
901  }
902 
903  if ( !is_array( $errors ) ) {
904  $errors = [ $errors ];
905  }
906  foreach ( $errors as &$error ) {
907  if ( $error instanceof Message ) {
908  $error = $error->parse();
909  }
910  }
911 
912  return $errors;
913  }
914 
918  public function getLabel() {
919  return $this->mLabel ?? '';
920  }
921 
922  public function getLabelHtml( $cellAttributes = [] ) {
923  # Don't output a for= attribute for labels with no associated input.
924  # Kind of hacky here, possibly we don't want these to be <label>s at all.
925  $for = [];
926 
927  if ( $this->needsLabel() ) {
928  $for['for'] = $this->mID;
929  }
930 
931  $labelValue = trim( $this->getLabel() );
932  $hasLabel = false;
933  if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
934  $hasLabel = true;
935  }
936 
937  $displayFormat = $this->mParent->getDisplayFormat();
938  $html = '';
939  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
940 
941  if ( $displayFormat === 'table' ) {
942  $html =
943  Html::rawElement( 'td',
944  [ 'class' => 'mw-label' ] + $cellAttributes,
945  Html::rawElement( 'label', $for, $labelValue ) );
946  } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
947  if ( $displayFormat === 'div' && !$horizontalLabel ) {
948  $html =
949  Html::rawElement( 'div',
950  [ 'class' => 'mw-label' ] + $cellAttributes,
951  Html::rawElement( 'label', $for, $labelValue ) );
952  } else {
953  $html = Html::rawElement( 'label', $for, $labelValue );
954  }
955  }
956 
957  return $html;
958  }
959 
960  public function getDefault() {
961  return $this->mDefault ?? null;
962  }
963 
969  public function getTooltipAndAccessKey() {
970  if ( empty( $this->mParams['tooltip'] ) ) {
971  return [];
972  }
973 
974  return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
975  }
976 
982  public function getTooltipAndAccessKeyOOUI() {
983  if ( empty( $this->mParams['tooltip'] ) ) {
984  return [];
985  }
986 
987  return [
988  'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
989  'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
990  ];
991  }
992 
999  public function getAttributes( array $list ) {
1000  static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1001 
1002  $ret = [];
1003  foreach ( $list as $key ) {
1004  if ( in_array( $key, $boolAttribs ) ) {
1005  if ( !empty( $this->mParams[$key] ) ) {
1006  $ret[$key] = '';
1007  }
1008  } elseif ( isset( $this->mParams[$key] ) ) {
1009  $ret[$key] = $this->mParams[$key];
1010  }
1011  }
1012 
1013  return $ret;
1014  }
1015 
1023  private function lookupOptionsKeys( $options ) {
1024  $ret = [];
1025  foreach ( $options as $key => $value ) {
1026  $key = $this->msg( $key )->plain();
1027  $ret[$key] = is_array( $value )
1028  ? $this->lookupOptionsKeys( $value )
1029  : strval( $value );
1030  }
1031  return $ret;
1032  }
1033 
1041  public static function forceToStringRecursive( $array ) {
1042  if ( is_array( $array ) ) {
1043  return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1044  } else {
1045  return strval( $array );
1046  }
1047  }
1048 
1055  public function getOptions() {
1056  if ( $this->mOptions === false ) {
1057  if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1058  $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
1059  } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1060  $this->mOptionsLabelsNotFromMessage = true;
1061  $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1062  } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1063  $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1064  $this->mOptions = Xml::listDropDownOptions( $message );
1065  } else {
1066  $this->mOptions = null;
1067  }
1068  }
1069 
1070  return $this->mOptions;
1071  }
1072 
1077  public function getOptionsOOUI() {
1078  $oldoptions = $this->getOptions();
1079 
1080  if ( $oldoptions === null ) {
1081  return null;
1082  }
1083 
1084  return Xml::listDropDownOptionsOoui( $oldoptions );
1085  }
1086 
1094  public static function flattenOptions( $options ) {
1095  $flatOpts = [];
1096 
1097  foreach ( $options as $value ) {
1098  if ( is_array( $value ) ) {
1099  $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1100  } else {
1101  $flatOpts[] = $value;
1102  }
1103  }
1104 
1105  return $flatOpts;
1106  }
1107 
1121  protected static function formatErrors( $errors ) {
1122  // Note: If you change the logic in this method, change
1123  // htmlform.Checker.js to match.
1124 
1125  if ( is_array( $errors ) && count( $errors ) === 1 ) {
1126  $errors = array_shift( $errors );
1127  }
1128 
1129  if ( is_array( $errors ) ) {
1130  $lines = [];
1131  foreach ( $errors as $error ) {
1132  if ( $error instanceof Message ) {
1133  $lines[] = Html::rawElement( 'li', [], $error->parse() );
1134  } else {
1135  $lines[] = Html::rawElement( 'li', [], $error );
1136  }
1137  }
1138 
1139  return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1140  } else {
1141  if ( $errors instanceof Message ) {
1142  $errors = $errors->parse();
1143  }
1144 
1145  return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1146  }
1147  }
1148 
1155  protected function getMessage( $value ) {
1156  $message = Message::newFromSpecifier( $value );
1157 
1158  if ( $this->mParent ) {
1159  $message->setContext( $this->mParent );
1160  }
1161 
1162  return $message;
1163  }
1164 
1171  public function skipLoadData( $request ) {
1172  return !empty( $this->mParams['nodata'] );
1173  }
1174 
1182  public function needsJSForHtml5FormValidation() {
1183  if ( $this->mHideIf ) {
1184  // This is probably more restrictive than it needs to be, but better safe than sorry
1185  return true;
1186  }
1187  return false;
1188  }
1189 }
HTMLFormField\getOptions
getOptions()
Fetch the array of options from the field's parameters.
Definition: HTMLFormField.php:1055
HTMLFormField\__construct
__construct( $params)
Initialise the object.
Definition: HTMLFormField.php:389
HTMLFormField\$mHelpClass
$mHelpClass
Definition: HTMLFormField.php:19
HTMLFormField\getTooltipAndAccessKeyOOUI
getTooltipAndAccessKeyOOUI()
Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
Definition: HTMLFormField.php:982
HTMLFormField\$mLabel
$mLabel
Definition: HTMLFormField.php:15
HTMLFormField\isHiddenRecurse
isHiddenRecurse(array $alldata, array $params)
Helper function for isHidden to handle recursive data structures.
Definition: HTMLFormField.php:162
Xml\listDropDownOptionsOoui
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:581
HTMLFormField\setShowEmptyLabel
setShowEmptyLabel( $show)
Tell the field whether to generate a separate label element if its label is blank.
Definition: HTMLFormField.php:348
HTMLFormField\getErrorsAndErrorClass
getErrorsAndErrorClass( $value)
Determine form errors to display and their classes.
Definition: HTMLFormField.php:875
HTMLFormField\validate
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.
Definition: HTMLFormField.php:302
HTMLFormActionFieldLayout
Definition: HTMLFormActionFieldLayout.php:3
HTMLFormField\formatErrors
static formatErrors( $errors)
Formats one or more errors as accepted by field validation-callback.
Definition: HTMLFormField.php:1121
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1263
HTMLFormField\hasVisibleOutput
hasVisibleOutput()
If this field has a user-visible output or not.
Definition: HTMLFormField.php:96
Message
HTMLFormField\getMessage
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
Definition: HTMLFormField.php:1155
HTMLFormField\getNearestFieldByName
getNearestFieldByName( $alldata, $name)
Fetch a field value from $alldata for the closest field matching a given name.
Definition: HTMLFormField.php:113
HTMLFormField\$mClass
$mClass
Definition: HTMLFormField.php:17
HTMLFormField\shouldInfuseOOUI
shouldInfuseOOUI()
Whether the field should be automatically infused.
Definition: HTMLFormField.php:678
HTMLFormField\needsLabel
needsLabel()
Should this field have a label, or is there no input element with the appropriate id for the label to...
Definition: HTMLFormField.php:335
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2192
HTMLFormField\$mDir
$mDir
Definition: HTMLFormField.php:14
HTMLFormField\skipLoadData
skipLoadData( $request)
Skip this field when collecting data.
Definition: HTMLFormField.php:1171
HTMLFormField\$mOptions
array bool null $mOptions
Definition: HTMLFormField.php:24
HTMLFormField\getTableRow
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:475
HTMLFormField\cancelSubmit
cancelSubmit( $value, $alldata)
Override this function if the control can somehow trigger a form submission that shouldn't actually s...
Definition: HTMLFormField.php:287
HTMLFormField\getLabelHtml
getLabelHtml( $cellAttributes=[])
Definition: HTMLFormField.php:922
HTMLFormField\canDisplayErrors
canDisplayErrors()
True if this field type is able to display errors; false if validation errors need to be displayed in...
Definition: HTMLFormField.php:67
HTMLFormField\getHelpTextHtmlTable
getHelpTextHtmlTable( $helptext)
Generate help text HTML in table format.
Definition: HTMLFormField.php:759
HTMLFormField\$mParent
HTMLForm null $mParent
Definition: HTMLFormField.php:37
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
HTMLFormField\getHelpText
getHelpText()
Determine the help text to display.
Definition: HTMLFormField.php:824
MWException
MediaWiki exception.
Definition: MWException.php:26
HTMLFormField\$mName
$mName
Definition: HTMLFormField.php:13
HTMLFormField\isHelpInline
isHelpInline()
Determine if the help text should be displayed inline.
Definition: HTMLFormField.php:859
HTMLFormField\getLabelAlignOOUI
getLabelAlignOOUI()
Get label alignment when generating field for OOUI.
Definition: HTMLFormField.php:652
HTMLFormField
The parent class to generate form fields.
Definition: HTMLFormField.php:7
HTMLFormField\lookupOptionsKeys
lookupOptionsKeys( $options)
Given an array of msg-key => value mappings, returns an array with keys being the message texts.
Definition: HTMLFormField.php:1023
$lines
$lines
Definition: router.php:61
HTMLFormField\$mDefault
$mDefault
Definition: HTMLFormField.php:20
HTMLFormField\needsJSForHtml5FormValidation
needsJSForHtml5FormValidation()
Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5 form ...
Definition: HTMLFormField.php:1182
HTMLFormField\filter
filter( $value, $alldata)
Definition: HTMLFormField.php:321
HTMLFormField\$mID
$mID
Definition: HTMLFormField.php:16
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:644
HTMLFormField\getOOUI
getOOUI( $value)
Get the OOUI version of the div.
Definition: HTMLFormField.php:582
HTMLFormField\isHidden
isHidden( $alldata)
Test whether this field is supposed to be hidden, based on the values of the other form fields.
Definition: HTMLFormField.php:269
HTMLFormField\$mValidationCallback
$mValidationCallback
Definition: HTMLFormField.php:11
HTMLFormField\getDefault
getDefault()
Definition: HTMLFormField.php:960
HTMLFormFieldLayout
Definition: HTMLFormFieldLayout.php:3
HTMLFormField\$mFilterCallback
$mFilterCallback
Definition: HTMLFormField.php:12
HTMLFormField\getFieldLayoutOOUI
getFieldLayoutOOUI( $inputField, $config)
Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
Definition: HTMLFormField.php:663
HTMLFormField\getLabel
getLabel()
Definition: HTMLFormField.php:918
HTMLFormField\getHelpTextHtmlRaw
getHelpTextHtmlRaw( $helptext)
Generate help text HTML formatted for raw output.
Definition: HTMLFormField.php:815
Linker\titleAttrib
static titleAttrib( $name, $options=null, array $msgParams=[])
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition: Linker.php:2023
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:43
HTMLFormField\getOOUIModules
getOOUIModules()
Get the list of extra ResourceLoader modules which must be loaded client-side before it's possible to...
Definition: HTMLFormField.php:689
HTMLFormField\getInputOOUI
getInputOOUI( $value)
Same as getInputHTML, but returns an OOUI object.
Definition: HTMLFormField.php:58
HTMLFormField\$mShowEmptyLabels
bool $mShowEmptyLabels
If true will generate an empty div element with no label.
Definition: HTMLFormField.php:32
HTMLFormField\getDiv
getDiv( $value)
Get the complete div for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:533
HTMLFormField\getVForm
getVForm( $value)
Get the complete field for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:725
HTMLFormField\$mParams
array array[] $mParams
Definition: HTMLFormField.php:9
HTMLFormField\getInputHTML
getInputHTML( $value)
This function must be implemented to return the HTML to generate the input object itself.
HTMLFormField\$mOptionsLabelsNotFromMessage
$mOptionsLabelsNotFromMessage
Definition: HTMLFormField.php:25
HTMLFormField\getRaw
getRaw( $value)
Get the complete raw fields for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:702
$keys
$keys
Definition: testCompression.php:69
HTMLFormField\getErrorsRaw
getErrorsRaw( $value)
Determine form errors to display, returning them in an array.
Definition: HTMLFormField.php:896
HTMLFormField\forceToStringRecursive
static forceToStringRecursive( $array)
Recursively forces values in an array to strings, because issues arise with integer 0 as a value.
Definition: HTMLFormField.php:1041
HTMLFormField\isSubmitAttempt
isSubmitAttempt(WebRequest $request)
Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to just v...
Definition: HTMLFormField.php:362
$help
$help
Definition: mcc.php:32
HTMLFormField\$mHideIf
$mHideIf
Definition: HTMLFormField.php:26
HTMLFormField\getTooltipAndAccessKey
getTooltipAndAccessKey()
Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
Definition: HTMLFormField.php:969
HTMLFormField\flattenOptions
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
Definition: HTMLFormField.php:1094
HTMLFormField\msg
msg( $key,... $params)
Get a translated interface message.
Definition: HTMLFormField.php:83
HTMLFormField\$mVFormClass
$mVFormClass
Definition: HTMLFormField.php:18
HTMLFormField\getHelpTextHtmlDiv
getHelpTextHtmlDiv( $helptext)
Generate help text HTML in div format.
Definition: HTMLFormField.php:788
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2071
HTMLFormField\getInline
getInline( $value)
Get the complete field as an inline element.
Definition: HTMLFormField.php:737
HTMLFormField\getOptionsOOUI
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
Definition: HTMLFormField.php:1077
Xml\listDropDownOptions
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:539
HTMLFormField\getAttributes
getAttributes(array $list)
Returns the given attributes from the parameters.
Definition: HTMLFormField.php:999
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:131
HTMLFormField\loadDataFromRequest
loadDataFromRequest( $request)
Get the value that this input has been set to from a posted form, or the input's default value if it ...
Definition: HTMLFormField.php:373