MediaWiki  master
HTMLFormField.php
Go to the documentation of this file.
1 <?php
2 
9 abstract class HTMLFormField {
11  public $mParams;
12 
14  protected $mFilterCallback;
15  protected $mName;
16  protected $mDir;
17  protected $mLabel; # String label, as HTML. Set on construction.
18  protected $mID;
19  protected $mClass = '';
20  protected $mVFormClass = '';
21  protected $mHelpClass = false;
22  protected $mDefault;
26  protected $mOptions = false;
27  protected $mOptionsLabelsNotFromMessage = false;
31  protected $mCondState = [];
32  protected $mCondStateClass = [];
33 
38  protected $mShowEmptyLabels = true;
39 
43  public $mParent;
44 
55  abstract public function getInputHTML( $value );
56 
65  public function getInputOOUI( $value ) {
66  return false;
67  }
68 
75  public function canDisplayErrors() {
76  return $this->hasVisibleOutput();
77  }
78 
91  public function msg( $key, ...$params ) {
92  if ( $this->mParent ) {
93  return $this->mParent->msg( $key, ...$params );
94  }
95  return wfMessage( $key, ...$params );
96  }
97 
105  public function hasVisibleOutput() {
106  return true;
107  }
108 
122  protected function getNearestFieldByName( $alldata, $name ) {
123  $tmp = $this->mName;
124  $thisKeys = [];
125  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
126  array_unshift( $thisKeys, $m[2] );
127  $tmp = $m[1];
128  }
129  if ( substr( $tmp, 0, 2 ) == 'wp' &&
130  !array_key_exists( $tmp, $alldata ) &&
131  array_key_exists( substr( $tmp, 2 ), $alldata )
132  ) {
133  // Adjust for name mangling.
134  $tmp = substr( $tmp, 2 );
135  }
136  array_unshift( $thisKeys, $tmp );
137 
138  $tmp = $name;
139  $nameKeys = [];
140  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
141  array_unshift( $nameKeys, $m[2] );
142  $tmp = $m[1];
143  }
144  array_unshift( $nameKeys, $tmp );
145 
146  $testValue = '';
147  for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
148  $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
149  $data = $alldata;
150  foreach ( $keys as $key ) {
151  if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
152  continue 2;
153  }
154  $data = $data[$key];
155  }
156  $testValue = (string)$data;
157  break;
158  }
159 
160  return $testValue;
161  }
162 
171  protected function checkStateRecurse( array $alldata, array $params ) {
172  $origParams = $params;
173  $op = array_shift( $params );
174 
175  try {
176  switch ( $op ) {
177  case 'AND':
178  foreach ( $params as $i => $p ) {
179  if ( !is_array( $p ) ) {
180  throw new MWException(
181  "Expected array, found " . gettype( $p ) . " at index $i"
182  );
183  }
184  if ( !$this->checkStateRecurse( $alldata, $p ) ) {
185  return false;
186  }
187  }
188  return true;
189 
190  case 'OR':
191  foreach ( $params as $i => $p ) {
192  if ( !is_array( $p ) ) {
193  throw new MWException(
194  "Expected array, found " . gettype( $p ) . " at index $i"
195  );
196  }
197  if ( $this->checkStateRecurse( $alldata, $p ) ) {
198  return true;
199  }
200  }
201  return false;
202 
203  case 'NAND':
204  foreach ( $params as $i => $p ) {
205  if ( !is_array( $p ) ) {
206  throw new MWException(
207  "Expected array, found " . gettype( $p ) . " at index $i"
208  );
209  }
210  if ( !$this->checkStateRecurse( $alldata, $p ) ) {
211  return true;
212  }
213  }
214  return false;
215 
216  case 'NOR':
217  foreach ( $params as $i => $p ) {
218  if ( !is_array( $p ) ) {
219  throw new MWException(
220  "Expected array, found " . gettype( $p ) . " at index $i"
221  );
222  }
223  if ( $this->checkStateRecurse( $alldata, $p ) ) {
224  return false;
225  }
226  }
227  return true;
228 
229  case 'NOT':
230  if ( count( $params ) !== 1 ) {
231  throw new MWException( "NOT takes exactly one parameter" );
232  }
233  $p = $params[0];
234  if ( !is_array( $p ) ) {
235  throw new MWException(
236  "Expected array, found " . gettype( $p ) . " at index 0"
237  );
238  }
239  return !$this->checkStateRecurse( $alldata, $p );
240 
241  case '===':
242  case '!==':
243  if ( count( $params ) !== 2 ) {
244  throw new MWException( "$op takes exactly two parameters" );
245  }
246  list( $field, $value ) = $params;
247  if ( !is_string( $field ) || !is_string( $value ) ) {
248  throw new MWException( "Parameters for $op must be strings" );
249  }
250  $testValue = $this->getNearestFieldByName( $alldata, $field );
251  switch ( $op ) {
252  case '===':
253  return ( $value === $testValue );
254  case '!==':
255  return ( $value !== $testValue );
256  }
257  // fall-through, if $op is not added to both cases
258  default:
259  throw new MWException( "Unknown operation" );
260  }
261  } catch ( Exception $ex ) {
262  throw new MWException(
263  "Invalid hide-if specification for $this->mName: " .
264  $ex->getMessage() . " in " . var_export( $origParams, true ),
265  0, $ex
266  );
267  }
268  }
269 
278  public function isHidden( $alldata ) {
279  if ( !( $this->mCondState && isset( $this->mCondState['hide'] ) ) ) {
280  return false;
281  }
282 
283  return $this->checkStateRecurse( $alldata, $this->mCondState['hide'] );
284  }
285 
294  public function isDisabled( $alldata ) {
295  if ( $this->mParams['disabled'] ?? false ) {
296  return true;
297  }
298  $hidden = $this->isHidden( $alldata );
299  if ( !$this->mCondState || !isset( $this->mCondState['disable'] ) ) {
300  return $hidden;
301  }
302 
303  return $hidden || $this->checkStateRecurse( $alldata, $this->mCondState['disable'] );
304  }
305 
317  public function cancelSubmit( $value, $alldata ) {
318  return false;
319  }
320 
333  public function validate( $value, $alldata ) {
334  if ( $this->isHidden( $alldata ) ) {
335  return true;
336  }
337 
338  if ( isset( $this->mParams['required'] )
339  && $this->mParams['required'] !== false
340  && $value === ''
341  ) {
342  return $this->msg( 'htmlform-required' );
343  }
344 
345  if ( isset( $this->mValidationCallback ) ) {
346  return ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
347  }
348 
349  return true;
350  }
351 
360  public function filter( $value, $alldata ) {
361  if ( isset( $this->mFilterCallback ) ) {
362  $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
363  }
364 
365  return $value;
366  }
367 
375  protected function needsLabel() {
376  return true;
377  }
378 
388  public function setShowEmptyLabel( $show ) {
389  $this->mShowEmptyLabels = $show;
390  }
391 
402  protected function isSubmitAttempt( WebRequest $request ) {
403  return $request->getCheck( 'wpEditToken' ) || $request->getCheck( 'wpFormIdentifier' );
404  }
405 
414  public function loadDataFromRequest( $request ) {
415  if ( $request->getCheck( $this->mName ) ) {
416  return $request->getText( $this->mName );
417  } else {
418  return $this->getDefault();
419  }
420  }
421 
431  public function __construct( $params ) {
432  $this->mParams = $params;
433 
434  if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
435  $this->mParent = $params['parent'];
436  }
437 
438  # Generate the label from a message, if possible
439  if ( isset( $params['label-message'] ) ) {
440  $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
441  } elseif ( isset( $params['label'] ) ) {
442  if ( $params['label'] === '&#160;' || $params['label'] === "\u{00A0}" ) {
443  // Apparently some things set &nbsp directly and in an odd format
444  $this->mLabel = "\u{00A0}";
445  } else {
446  $this->mLabel = htmlspecialchars( $params['label'] );
447  }
448  } elseif ( isset( $params['label-raw'] ) ) {
449  $this->mLabel = $params['label-raw'];
450  }
451 
452  $this->mName = "wp{$params['fieldname']}";
453  if ( isset( $params['name'] ) ) {
454  $this->mName = $params['name'];
455  }
456 
457  if ( isset( $params['dir'] ) ) {
458  $this->mDir = $params['dir'];
459  }
460 
461  $this->mID = "mw-input-{$this->mName}";
462 
463  if ( isset( $params['default'] ) ) {
464  $this->mDefault = $params['default'];
465  }
466 
467  if ( isset( $params['id'] ) ) {
468  $this->mID = $params['id'];
469  }
470 
471  if ( isset( $params['cssclass'] ) ) {
472  $this->mClass = $params['cssclass'];
473  }
474 
475  if ( isset( $params['csshelpclass'] ) ) {
476  $this->mHelpClass = $params['csshelpclass'];
477  }
478 
479  if ( isset( $params['validation-callback'] ) ) {
480  $this->mValidationCallback = $params['validation-callback'];
481  }
482 
483  if ( isset( $params['filter-callback'] ) ) {
484  $this->mFilterCallback = $params['filter-callback'];
485  }
486 
487  if ( isset( $params['hidelabel'] ) ) {
488  $this->mShowEmptyLabels = false;
489  }
490 
491  if ( isset( $params['hide-if'] ) && $params['hide-if'] ) {
492  $this->mCondState['hide'] = $params['hide-if'];
493  $this->mCondStateClass[] = 'mw-htmlform-hide-if';
494  }
495  if ( !( isset( $params['disabled'] ) && $params['disabled'] ) &&
496  isset( $params['disable-if'] ) && $params['disable-if']
497  ) {
498  $this->mCondState['disable'] = $params['disable-if'];
499  $this->mCondStateClass[] = 'mw-htmlform-disable-if';
500  }
501  }
502 
512  public function getTableRow( $value ) {
513  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
514  $inputHtml = $this->getInputHTML( $value );
515  $fieldType = $this->getClassName();
516  $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
517  $cellAttributes = [];
518  $rowAttributes = [];
519  $rowClasses = '';
520 
521  if ( !empty( $this->mParams['vertical-label'] ) ) {
522  $cellAttributes['colspan'] = 2;
523  $verticalLabel = true;
524  } else {
525  $verticalLabel = false;
526  }
527 
528  $label = $this->getLabelHtml( $cellAttributes );
529 
530  $field = Html::rawElement(
531  'td',
532  [ 'class' => 'mw-input' ] + $cellAttributes,
533  $inputHtml . "\n$errors"
534  );
535 
536  if ( $this->mCondState ) {
537  $rowAttributes['data-cond-state'] = FormatJson::encode( $this->mCondState );
538  $rowClasses .= implode( ' ', $this->mCondStateClass );
539  }
540 
541  if ( $verticalLabel ) {
542  $html = Html::rawElement( 'tr',
543  $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
544  $html .= Html::rawElement( 'tr',
545  $rowAttributes + [
546  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
547  ],
548  $field );
549  } else {
550  $html = Html::rawElement( 'tr',
551  $rowAttributes + [
552  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
553  ],
554  $label . $field );
555  }
556 
557  return $html . $helptext;
558  }
559 
570  public function getDiv( $value ) {
571  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
572  $inputHtml = $this->getInputHTML( $value );
573  $fieldType = $this->getClassName();
574  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
575  $cellAttributes = [];
576  $label = $this->getLabelHtml( $cellAttributes );
577 
578  $outerDivClass = [
579  'mw-input',
580  'mw-htmlform-nolabel' => ( $label === '' )
581  ];
582 
583  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
584 
585  if ( $horizontalLabel ) {
586  $field = "\u{00A0}" . $inputHtml . "\n$errors";
587  } else {
588  $field = Html::rawElement(
589  'div',
590  // @phan-suppress-next-line PhanUselessBinaryAddRight
591  [ 'class' => $outerDivClass ] + $cellAttributes,
592  $inputHtml . "\n$errors"
593  );
594  }
595  $divCssClasses = [ "mw-htmlform-field-$fieldType",
596  $this->mClass, $this->mVFormClass, $errorClass ];
597 
598  $wrapperAttributes = [
599  'class' => $divCssClasses,
600  ];
601  if ( $this->mCondState ) {
602  $wrapperAttributes['data-cond-state'] = FormatJson::encode( $this->mCondState );
603  $wrapperAttributes['class'] = array_merge( $wrapperAttributes['class'], $this->mCondStateClass );
604  }
605  $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
606  $html .= $helptext;
607 
608  return $html;
609  }
610 
620  public function getOOUI( $value ) {
621  $inputField = $this->getInputOOUI( $value );
622 
623  if ( !$inputField ) {
624  // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
625  // generate the whole field, label and errors and all, then wrap it in a Widget.
626  // It might look weird, but it'll work OK.
627  return $this->getFieldLayoutOOUI(
628  new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
629  [ 'align' => 'top' ]
630  );
631  }
632 
633  $infusable = true;
634  if ( is_string( $inputField ) ) {
635  // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
636  // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
637  // JavaScript doesn't know how to rebuilt the contents.
638  $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
639  $infusable = false;
640  }
641 
642  $fieldType = $this->getClassName();
643  $help = $this->getHelpText();
644  $errors = $this->getErrorsRaw( $value );
645  foreach ( $errors as &$error ) {
646  $error = new OOUI\HtmlSnippet( $error );
647  }
648 
649  $config = [
650  'classes' => [ "mw-htmlform-field-$fieldType" ],
651  'align' => $this->getLabelAlignOOUI(),
652  'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
653  'errors' => $errors,
654  'infusable' => $infusable,
655  'helpInline' => $this->isHelpInline(),
656  ];
657  if ( $this->mClass !== '' ) {
658  $config['classes'][] = $this->mClass;
659  }
660 
661  $preloadModules = false;
662 
663  if ( $infusable && $this->shouldInfuseOOUI() ) {
664  $preloadModules = true;
665  $config['classes'][] = 'mw-htmlform-autoinfuse';
666  }
667  if ( $this->mCondState ) {
668  $config['classes'] = array_merge( $config['classes'], $this->mCondStateClass );
669  }
670 
671  // the element could specify, that the label doesn't need to be added
672  $label = $this->getLabel();
673  if ( $label && $label !== "\u{00A0}" && $label !== '&#160;' ) {
674  $config['label'] = new OOUI\HtmlSnippet( $label );
675  }
676 
677  if ( $this->mCondState ) {
678  $preloadModules = true;
679  $config['condState'] = $this->mCondState;
680  }
681 
682  $config['modules'] = $this->getOOUIModules();
683 
684  if ( $preloadModules ) {
685  $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
686  $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
687  }
688 
689  return $this->getFieldLayoutOOUI( $inputField, $config );
690  }
691 
699  protected function getClassName() {
700  $name = explode( '\\', static::class );
701  return end( $name );
702  }
703 
709  protected function getLabelAlignOOUI() {
710  return 'top';
711  }
712 
720  protected function getFieldLayoutOOUI( $inputField, $config ) {
721  if ( isset( $this->mClassWithButton ) ) {
722  $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
723  return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
724  }
725  return new HTMLFormFieldLayout( $inputField, $config );
726  }
727 
736  protected function shouldInfuseOOUI() {
737  // Always infuse fields with popup help text, since the interface for it is nicer with JS
738  return $this->getHelpText() !== null && !$this->isHelpInline();
739  }
740 
748  protected function getOOUIModules() {
749  return [];
750  }
751 
762  public function getRaw( $value ) {
763  list( $errors, ) = $this->getErrorsAndErrorClass( $value );
764  $inputHtml = $this->getInputHTML( $value );
765  $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
766  $cellAttributes = [];
767  $label = $this->getLabelHtml( $cellAttributes );
768 
769  $html = "\n$errors";
770  $html .= $label;
771  $html .= $inputHtml;
772  $html .= $helptext;
773 
774  return $html;
775  }
776 
786  public function getVForm( $value ) {
787  // Ewwww
788  $this->mVFormClass = ' mw-ui-vform-field';
789  return $this->getDiv( $value );
790  }
791 
799  public function getInline( $value ) {
800  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
801  $inputHtml = $this->getInputHTML( $value );
802  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
803  $cellAttributes = [];
804  $label = $this->getLabelHtml( $cellAttributes );
805 
806  $html = "\n" . $errors .
807  $label . "\u{00A0}" .
808  $inputHtml .
809  $helptext;
810 
811  return $html;
812  }
813 
821  public function getHelpTextHtmlTable( $helptext ) {
822  if ( $helptext === null ) {
823  return '';
824  }
825 
826  $rowAttributes = [];
827  if ( $this->mCondState ) {
828  $rowAttributes['data-cond-state'] = FormatJson::encode( $this->mCondState );
829  $rowAttributes['class'] = $this->mCondStateClass;
830  }
831 
832  $tdClasses = [ 'htmlform-tip' ];
833  if ( $this->mHelpClass !== false ) {
834  $tdClasses[] = $this->mHelpClass;
835  }
836  $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
837  $row = Html::rawElement( 'tr', $rowAttributes, $row );
838 
839  return $row;
840  }
841 
850  public function getHelpTextHtmlDiv( $helptext ) {
851  if ( $helptext === null ) {
852  return '';
853  }
854 
855  $wrapperAttributes = [
856  'class' => [ 'htmlform-tip' ],
857  ];
858  if ( $this->mHelpClass !== false ) {
859  $wrapperAttributes['class'][] = $this->mHelpClass;
860  }
861  if ( $this->mCondState ) {
862  $wrapperAttributes['data-cond-state'] = FormatJson::encode( $this->mCondState );
863  $wrapperAttributes['class'] = array_merge( $wrapperAttributes['class'], $this->mCondStateClass );
864  }
865  $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
866 
867  return $div;
868  }
869 
877  public function getHelpTextHtmlRaw( $helptext ) {
878  return $this->getHelpTextHtmlDiv( $helptext );
879  }
880 
887  public function getHelpText() {
888  $helptext = null;
889 
890  if ( isset( $this->mParams['help-message'] ) ) {
891  $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
892  }
893 
894  if ( isset( $this->mParams['help-messages'] ) ) {
895  foreach ( $this->mParams['help-messages'] as $msg ) {
896  $msg = $this->getMessage( $msg );
897 
898  if ( $msg->exists() ) {
899  if ( $helptext === null ) {
900  $helptext = '';
901  } else {
902  $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
903  }
904  $helptext .= $msg->parse(); // Append message
905  }
906  }
907  } elseif ( isset( $this->mParams['help'] ) ) {
908  $helptext = $this->mParams['help'];
909  }
910 
911  return $helptext;
912  }
913 
922  public function isHelpInline() {
923  return $this->mParams['help-inline'] ?? true;
924  }
925 
938  public function getErrorsAndErrorClass( $value ) {
939  $errors = $this->validate( $value, $this->mParent->mFieldData );
940 
941  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
942  $errors = '';
943  $errorClass = '';
944  } else {
945  $errors = self::formatErrors( $errors );
946  $errorClass = 'mw-htmlform-invalid-input';
947  }
948 
949  return [ $errors, $errorClass ];
950  }
951 
959  public function getErrorsRaw( $value ) {
960  $errors = $this->validate( $value, $this->mParent->mFieldData );
961 
962  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
963  $errors = [];
964  }
965 
966  if ( !is_array( $errors ) ) {
967  $errors = [ $errors ];
968  }
969  foreach ( $errors as &$error ) {
970  if ( $error instanceof Message ) {
971  $error = $error->parse();
972  }
973  }
974 
975  return $errors;
976  }
977 
982  public function getLabel() {
983  return $this->mLabel ?? '';
984  }
985 
992  public function getLabelHtml( $cellAttributes = [] ) {
993  # Don't output a for= attribute for labels with no associated input.
994  # Kind of hacky here, possibly we don't want these to be <label>s at all.
995  $for = [];
996 
997  if ( $this->needsLabel() ) {
998  $for['for'] = $this->mID;
999  }
1000 
1001  $labelValue = trim( $this->getLabel() );
1002  $hasLabel = false;
1003  if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1004  $hasLabel = true;
1005  }
1006 
1007  $displayFormat = $this->mParent->getDisplayFormat();
1008  $html = '';
1009  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
1010 
1011  if ( $displayFormat === 'table' ) {
1012  $html =
1013  Html::rawElement( 'td',
1014  [ 'class' => 'mw-label' ] + $cellAttributes,
1015  Html::rawElement( 'label', $for, $labelValue ) );
1016  } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1017  if ( $displayFormat === 'div' && !$horizontalLabel ) {
1018  $html =
1019  Html::rawElement( 'div',
1020  [ 'class' => 'mw-label' ] + $cellAttributes,
1021  Html::rawElement( 'label', $for, $labelValue ) );
1022  } else {
1023  $html = Html::rawElement( 'label', $for, $labelValue );
1024  }
1025  }
1026 
1027  return $html;
1028  }
1029 
1034  public function getDefault() {
1035  return $this->mDefault ?? null;
1036  }
1037 
1043  public function getTooltipAndAccessKey() {
1044  if ( empty( $this->mParams['tooltip'] ) ) {
1045  return [];
1046  }
1047 
1048  return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1049  }
1050 
1056  public function getTooltipAndAccessKeyOOUI() {
1057  if ( empty( $this->mParams['tooltip'] ) ) {
1058  return [];
1059  }
1060 
1061  return [
1062  'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1063  'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1064  ];
1065  }
1066 
1074  public function getAttributes( array $list ) {
1075  static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1076 
1077  $ret = [];
1078  foreach ( $list as $key ) {
1079  if ( in_array( $key, $boolAttribs ) ) {
1080  if ( !empty( $this->mParams[$key] ) ) {
1081  $ret[$key] = '';
1082  }
1083  } elseif ( isset( $this->mParams[$key] ) ) {
1084  $ret[$key] = $this->mParams[$key];
1085  }
1086  }
1087 
1088  return $ret;
1089  }
1090 
1100  private function lookupOptionsKeys( $options, $needsParse ) {
1101  $ret = [];
1102  foreach ( $options as $key => $value ) {
1103  $msg = $this->msg( $key );
1104  $key = $needsParse ? $msg->parse() : $msg->plain();
1105  $ret[$key] = is_array( $value )
1106  ? $this->lookupOptionsKeys( $value, $needsParse )
1107  : strval( $value );
1108  }
1109  return $ret;
1110  }
1111 
1119  public static function forceToStringRecursive( $array ) {
1120  if ( is_array( $array ) ) {
1121  return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1122  } else {
1123  return strval( $array );
1124  }
1125  }
1126 
1133  public function getOptions() {
1134  if ( $this->mOptions === false ) {
1135  if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1136  $needsParse = $this->mParams['options-messages-parse'] ?? false;
1137  if ( $needsParse ) {
1138  $this->mOptionsLabelsNotFromMessage = true;
1139  }
1140  $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'], $needsParse );
1141  } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1142  $this->mOptionsLabelsNotFromMessage = true;
1143  $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1144  } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1145  $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1146  $this->mOptions = Xml::listDropDownOptions( $message );
1147  } else {
1148  $this->mOptions = null;
1149  }
1150  }
1151 
1152  return $this->mOptions;
1153  }
1154 
1160  public function getOptionsOOUI() {
1161  $oldoptions = $this->getOptions();
1162 
1163  if ( $oldoptions === null ) {
1164  return null;
1165  }
1166 
1167  return Xml::listDropDownOptionsOoui( $oldoptions );
1168  }
1169 
1177  public static function flattenOptions( $options ) {
1178  $flatOpts = [];
1179 
1180  foreach ( $options as $value ) {
1181  if ( is_array( $value ) ) {
1182  $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1183  } else {
1184  $flatOpts[] = $value;
1185  }
1186  }
1187 
1188  return $flatOpts;
1189  }
1190 
1204  protected static function formatErrors( $errors ) {
1205  if ( is_array( $errors ) && count( $errors ) === 1 ) {
1206  $errors = array_shift( $errors );
1207  }
1208 
1209  if ( is_array( $errors ) ) {
1210  $lines = [];
1211  foreach ( $errors as $error ) {
1212  if ( $error instanceof Message ) {
1213  $lines[] = Html::rawElement( 'li', [], $error->parse() );
1214  } else {
1215  $lines[] = Html::rawElement( 'li', [], $error );
1216  }
1217  }
1218 
1219  $errors = Html::rawElement( 'ul', [], implode( "\n", $lines ) );
1220  } else {
1221  if ( $errors instanceof Message ) {
1222  $errors = $errors->parse();
1223  }
1224  }
1225 
1226  return Html::rawElement( 'div', [ 'class' => 'errorbox' ], $errors );
1227  }
1228 
1235  protected function getMessage( $value ) {
1236  $message = Message::newFromSpecifier( $value );
1237 
1238  if ( $this->mParent ) {
1239  $message->setContext( $this->mParent );
1240  }
1241 
1242  return $message;
1243  }
1244 
1252  public function skipLoadData( $request ) {
1253  return !empty( $this->mParams['nodata'] );
1254  }
1255 
1263  public function needsJSForHtml5FormValidation() {
1264  if ( $this->mCondState ) {
1265  // This is probably more restrictive than it needs to be, but better safe than sorry
1266  return true;
1267  }
1268  return false;
1269  }
1270 }
HTMLFormField\getOptions
getOptions()
Fetch the array of options from the field's parameters.
Definition: HTMLFormField.php:1133
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:399
HTMLFormField\__construct
__construct( $params)
Initialise the object.
Definition: HTMLFormField.php:431
HTMLFormField\$mHelpClass
$mHelpClass
Definition: HTMLFormField.php:21
HTMLFormField\getTooltipAndAccessKeyOOUI
getTooltipAndAccessKeyOOUI()
Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
Definition: HTMLFormField.php:1056
HTMLFormField\getClassName
getClassName()
Gets the non namespaced class name.
Definition: HTMLFormField.php:699
HTMLFormField\$mLabel
$mLabel
Definition: HTMLFormField.php:17
Xml\listDropDownOptionsOoui
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:596
HTMLFormField\setShowEmptyLabel
setShowEmptyLabel( $show)
Tell the field whether to generate a separate label element if its label is blank.
Definition: HTMLFormField.php:388
HTMLFormField\getErrorsAndErrorClass
getErrorsAndErrorClass( $value)
Determine form errors to display and their classes.
Definition: HTMLFormField.php:938
HTMLFormField\validate
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.
Definition: HTMLFormField.php:333
HTMLFormActionFieldLayout
Definition: HTMLFormActionFieldLayout.php:6
HTMLFormField\formatErrors
static formatErrors( $errors)
Formats one or more errors as accepted by field validation-callback.
Definition: HTMLFormField.php:1204
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1167
HTMLFormField\hasVisibleOutput
hasVisibleOutput()
If this field has a user-visible output or not.
Definition: HTMLFormField.php:105
HTMLFormField\getMessage
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
Definition: HTMLFormField.php:1235
HTMLFormField\getNearestFieldByName
getNearestFieldByName( $alldata, $name)
Fetch a field value from $alldata for the closest field matching a given name.
Definition: HTMLFormField.php:122
HTMLFormField\$mClass
$mClass
Definition: HTMLFormField.php:19
HTMLFormField\shouldInfuseOOUI
shouldInfuseOOUI()
Whether the field should be automatically infused.
Definition: HTMLFormField.php:736
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:375
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2220
HTMLFormField\$mCondState
array $mCondState
Array to hold params for 'hide-if' or 'disable-if' statements.
Definition: HTMLFormField.php:31
HTMLFormField\$mDir
$mDir
Definition: HTMLFormField.php:16
HTMLFormField\skipLoadData
skipLoadData( $request)
Skip this field when collecting data.
Definition: HTMLFormField.php:1252
HTMLFormField\$mOptions
array bool null $mOptions
Definition: HTMLFormField.php:26
HTMLFormField\lookupOptionsKeys
lookupOptionsKeys( $options, $needsParse)
Given an array of msg-key => value mappings, returns an array with keys being the message texts.
Definition: HTMLFormField.php:1100
HTMLFormField\getTableRow
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:512
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:317
HTMLFormField\getLabelHtml
getLabelHtml( $cellAttributes=[])
Definition: HTMLFormField.php:992
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:75
HTMLFormField\getHelpTextHtmlTable
getHelpTextHtmlTable( $helptext)
Generate help text HTML in table format.
Definition: HTMLFormField.php:821
HTMLFormField\$mParent
HTMLForm null $mParent
Definition: HTMLFormField.php:43
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:96
HTMLFormField\getHelpText
getHelpText()
Determine the help text to display.
Definition: HTMLFormField.php:887
MWException
MediaWiki exception.
Definition: MWException.php:29
HTMLFormField\$mName
$mName
Definition: HTMLFormField.php:15
HTMLFormField\isHelpInline
isHelpInline()
Determine if the help text should be displayed inline.
Definition: HTMLFormField.php:922
HTMLFormField\getLabelAlignOOUI
getLabelAlignOOUI()
Get label alignment when generating field for OOUI.
Definition: HTMLFormField.php:709
HTMLFormField
The parent class to generate form fields.
Definition: HTMLFormField.php:9
HTMLFormField\$mDefault
$mDefault
Definition: HTMLFormField.php:22
HTMLFormField\isDisabled
isDisabled( $alldata)
Test whether this field is supposed to be disabled, based on the values of the other form fields.
Definition: HTMLFormField.php:294
HTMLFormField\needsJSForHtml5FormValidation
needsJSForHtml5FormValidation()
Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5 form ...
Definition: HTMLFormField.php:1263
HTMLFormField\filter
filter( $value, $alldata)
Definition: HTMLFormField.php:360
HTMLFormField\$mID
$mID
Definition: HTMLFormField.php:18
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:677
HTMLFormField\getOOUI
getOOUI( $value)
Get the OOUI version of the div.
Definition: HTMLFormField.php:620
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:278
HTMLFormField\$mValidationCallback
$mValidationCallback
Definition: HTMLFormField.php:13
HTMLFormField\getDefault
getDefault()
Definition: HTMLFormField.php:1034
HTMLFormFieldLayout
Definition: HTMLFormFieldLayout.php:6
HTMLFormField\$mFilterCallback
$mFilterCallback
Definition: HTMLFormField.php:14
HTMLFormField\getFieldLayoutOOUI
getFieldLayoutOOUI( $inputField, $config)
Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
Definition: HTMLFormField.php:720
HTMLFormField\getLabel
getLabel()
Definition: HTMLFormField.php:982
HTMLFormField\$mCondStateClass
$mCondStateClass
Definition: HTMLFormField.php:32
HTMLFormField\getHelpTextHtmlRaw
getHelpTextHtmlRaw( $helptext)
Generate help text HTML formatted for raw output.
Definition: HTMLFormField.php:877
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:2041
$lines
if(!file_exists( $CREDITS)) $lines
Definition: updateCredits.php:45
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:748
HTMLFormField\getInputOOUI
getInputOOUI( $value)
Same as getInputHTML, but returns an OOUI object.
Definition: HTMLFormField.php:65
HTMLFormField\$mShowEmptyLabels
bool $mShowEmptyLabels
If true will generate an empty div element with no label.
Definition: HTMLFormField.php:38
HTMLFormField\getDiv
getDiv( $value)
Get the complete div for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:570
HTMLFormField\getVForm
getVForm( $value)
Get the complete field for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:786
HTMLFormField\$mParams
array array[] $mParams
Definition: HTMLFormField.php:11
HTMLFormField\getInputHTML
getInputHTML( $value)
This function must be implemented to return the HTML to generate the input object itself.
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:213
HTMLFormField\$mOptionsLabelsNotFromMessage
$mOptionsLabelsNotFromMessage
Definition: HTMLFormField.php:27
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:139
HTMLFormField\getRaw
getRaw( $value)
Get the complete raw fields for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:762
$keys
$keys
Definition: testCompression.php:72
HTMLFormField\getErrorsRaw
getErrorsRaw( $value)
Determine form errors to display, returning them in an array.
Definition: HTMLFormField.php:959
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:1119
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:402
$help
$help
Definition: mcc.php:32
HTMLFormField\getTooltipAndAccessKey
getTooltipAndAccessKey()
Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
Definition: HTMLFormField.php:1043
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:1177
HTMLFormField\msg
msg( $key,... $params)
Get a translated interface message.
Definition: HTMLFormField.php:91
HTMLFormField\$mVFormClass
$mVFormClass
Definition: HTMLFormField.php:20
HTMLFormField\getHelpTextHtmlDiv
getHelpTextHtmlDiv( $helptext)
Generate help text HTML in div format.
Definition: HTMLFormField.php:850
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2089
HTMLFormField\getInline
getInline( $value)
Get the complete field as an inline element.
Definition: HTMLFormField.php:799
HTMLFormField\getOptionsOOUI
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
Definition: HTMLFormField.php:1160
HTMLFormField\checkStateRecurse
checkStateRecurse(array $alldata, array $params)
Helper function for isHidden and isDisabled to handle recursive data structures.
Definition: HTMLFormField.php:171
Xml\listDropDownOptions
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:546
HTMLFormField\getAttributes
getAttributes(array $list)
Returns the given attributes from the parameters.
Definition: HTMLFormField.php:1074
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:149
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:414