MediaWiki  master
HTMLFormField.php
Go to the documentation of this file.
1 <?php
2 
4 
11 abstract class HTMLFormField {
13  public $mParams;
14 
16  protected $mFilterCallback;
17  protected $mName;
18  protected $mDir;
19  protected $mLabel; # String label, as HTML. Set on construction.
20  protected $mID;
21  protected $mClass = '';
22  protected $mVFormClass = '';
23  protected $mHelpClass = false;
24  protected $mDefault;
28  protected $mOptions = false;
29  protected $mOptionsLabelsNotFromMessage = false;
30  protected $mHideIf = null;
31 
36  protected $mShowEmptyLabels = true;
37 
41  public $mParent;
42 
53  abstract public function getInputHTML( $value );
54 
63  public function getInputOOUI( $value ) {
64  return false;
65  }
66 
73  public function canDisplayErrors() {
74  return $this->hasVisibleOutput();
75  }
76 
89  public function msg( $key, ...$params ) {
90  if ( $this->mParent ) {
91  return $this->mParent->msg( $key, ...$params );
92  }
93  return wfMessage( $key, ...$params );
94  }
95 
103  public function hasVisibleOutput() {
104  return true;
105  }
106 
120  protected function getNearestFieldByName( $alldata, $name ) {
121  $tmp = $this->mName;
122  $thisKeys = [];
123  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
124  array_unshift( $thisKeys, $m[2] );
125  $tmp = $m[1];
126  }
127  if ( substr( $tmp, 0, 2 ) == 'wp' &&
128  !array_key_exists( $tmp, $alldata ) &&
129  array_key_exists( substr( $tmp, 2 ), $alldata )
130  ) {
131  // Adjust for name mangling.
132  $tmp = substr( $tmp, 2 );
133  }
134  array_unshift( $thisKeys, $tmp );
135 
136  $tmp = $name;
137  $nameKeys = [];
138  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
139  array_unshift( $nameKeys, $m[2] );
140  $tmp = $m[1];
141  }
142  array_unshift( $nameKeys, $tmp );
143 
144  $testValue = '';
145  for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
146  $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
147  $data = $alldata;
148  foreach ( $keys as $key ) {
149  if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
150  continue 2;
151  }
152  $data = $data[$key];
153  }
154  $testValue = (string)$data;
155  break;
156  }
157 
158  return $testValue;
159  }
160 
169  protected function isHiddenRecurse( array $alldata, array $params ) {
170  $origParams = $params;
171  $op = array_shift( $params );
172 
173  try {
174  switch ( $op ) {
175  case 'AND':
176  foreach ( $params as $i => $p ) {
177  if ( !is_array( $p ) ) {
178  throw new MWException(
179  "Expected array, found " . gettype( $p ) . " at index $i"
180  );
181  }
182  if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
183  return false;
184  }
185  }
186  return true;
187 
188  case 'OR':
189  foreach ( $params as $i => $p ) {
190  if ( !is_array( $p ) ) {
191  throw new MWException(
192  "Expected array, found " . gettype( $p ) . " at index $i"
193  );
194  }
195  if ( $this->isHiddenRecurse( $alldata, $p ) ) {
196  return true;
197  }
198  }
199  return false;
200 
201  case 'NAND':
202  foreach ( $params as $i => $p ) {
203  if ( !is_array( $p ) ) {
204  throw new MWException(
205  "Expected array, found " . gettype( $p ) . " at index $i"
206  );
207  }
208  if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
209  return true;
210  }
211  }
212  return false;
213 
214  case 'NOR':
215  foreach ( $params as $i => $p ) {
216  if ( !is_array( $p ) ) {
217  throw new MWException(
218  "Expected array, found " . gettype( $p ) . " at index $i"
219  );
220  }
221  if ( $this->isHiddenRecurse( $alldata, $p ) ) {
222  return false;
223  }
224  }
225  return true;
226 
227  case 'NOT':
228  if ( count( $params ) !== 1 ) {
229  throw new MWException( "NOT takes exactly one parameter" );
230  }
231  $p = $params[0];
232  if ( !is_array( $p ) ) {
233  throw new MWException(
234  "Expected array, found " . gettype( $p ) . " at index 0"
235  );
236  }
237  return !$this->isHiddenRecurse( $alldata, $p );
238 
239  case '===':
240  case '!==':
241  if ( count( $params ) !== 2 ) {
242  throw new MWException( "$op takes exactly two parameters" );
243  }
244  list( $field, $value ) = $params;
245  if ( !is_string( $field ) || !is_string( $value ) ) {
246  throw new MWException( "Parameters for $op must be strings" );
247  }
248  $testValue = $this->getNearestFieldByName( $alldata, $field );
249  switch ( $op ) {
250  case '===':
251  return ( $value === $testValue );
252  case '!==':
253  return ( $value !== $testValue );
254  }
255  // fall-through, if $op is not added to both cases
256  default:
257  throw new MWException( "Unknown operation" );
258  }
259  } catch ( Exception $ex ) {
260  throw new MWException(
261  "Invalid hide-if specification for $this->mName: " .
262  $ex->getMessage() . " in " . var_export( $origParams, true ),
263  0, $ex
264  );
265  }
266  }
267 
276  public function isHidden( $alldata ) {
277  if ( !$this->mHideIf ) {
278  return false;
279  }
280 
281  return $this->isHiddenRecurse( $alldata, $this->mHideIf );
282  }
283 
295  public function cancelSubmit( $value, $alldata ) {
296  return false;
297  }
298 
311  public function validate( $value, $alldata ) {
312  if ( $this->isHidden( $alldata ) ) {
313  return true;
314  }
315 
316  if ( isset( $this->mParams['required'] )
317  && $this->mParams['required'] !== false
318  && $value === ''
319  ) {
320  return $this->msg( 'htmlform-required' );
321  }
322 
323  if ( isset( $this->mValidationCallback ) ) {
324  return ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
325  }
326 
327  return true;
328  }
329 
338  public function filter( $value, $alldata ) {
339  if ( isset( $this->mFilterCallback ) ) {
340  $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
341  }
342 
343  return $value;
344  }
345 
353  protected function needsLabel() {
354  return true;
355  }
356 
366  public function setShowEmptyLabel( $show ) {
367  $this->mShowEmptyLabels = $show;
368  }
369 
380  protected function isSubmitAttempt( WebRequest $request ) {
381  return $request->getCheck( CsrfTokenSet::DEFAULT_FIELD_NAME ) ||
382  $request->getCheck( 'wpFormIdentifier' );
383  }
384 
393  public function loadDataFromRequest( $request ) {
394  if ( $request->getCheck( $this->mName ) ) {
395  return $request->getText( $this->mName );
396  } else {
397  return $this->getDefault();
398  }
399  }
400 
410  public function __construct( $params ) {
411  $this->mParams = $params;
412 
413  if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
414  $this->mParent = $params['parent'];
415  }
416 
417  # Generate the label from a message, if possible
418  if ( isset( $params['label-message'] ) ) {
419  $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
420  } elseif ( isset( $params['label'] ) ) {
421  if ( $params['label'] === '&#160;' || $params['label'] === "\u{00A0}" ) {
422  // Apparently some things set &nbsp directly and in an odd format
423  $this->mLabel = "\u{00A0}";
424  } else {
425  $this->mLabel = htmlspecialchars( $params['label'] );
426  }
427  } elseif ( isset( $params['label-raw'] ) ) {
428  $this->mLabel = $params['label-raw'];
429  }
430 
431  $this->mName = "wp{$params['fieldname']}";
432  if ( isset( $params['name'] ) ) {
433  $this->mName = $params['name'];
434  }
435 
436  if ( isset( $params['dir'] ) ) {
437  $this->mDir = $params['dir'];
438  }
439 
440  $validName = urlencode( $this->mName );
441  $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
442  if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
443  throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
444  }
445 
446  $this->mID = "mw-input-{$this->mName}";
447 
448  if ( isset( $params['default'] ) ) {
449  $this->mDefault = $params['default'];
450  }
451 
452  if ( isset( $params['id'] ) ) {
453  $id = $params['id'];
454  $validId = urlencode( $id );
455 
456  if ( $id != $validId ) {
457  throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
458  }
459 
460  $this->mID = $id;
461  }
462 
463  if ( isset( $params['cssclass'] ) ) {
464  $this->mClass = $params['cssclass'];
465  }
466 
467  if ( isset( $params['csshelpclass'] ) ) {
468  $this->mHelpClass = $params['csshelpclass'];
469  }
470 
471  if ( isset( $params['validation-callback'] ) ) {
472  $this->mValidationCallback = $params['validation-callback'];
473  }
474 
475  if ( isset( $params['filter-callback'] ) ) {
476  $this->mFilterCallback = $params['filter-callback'];
477  }
478 
479  if ( isset( $params['hidelabel'] ) ) {
480  $this->mShowEmptyLabels = false;
481  }
482 
483  if ( isset( $params['hide-if'] ) ) {
484  $this->mHideIf = $params['hide-if'];
485  }
486  }
487 
497  public function getTableRow( $value ) {
498  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
499  $inputHtml = $this->getInputHTML( $value );
500  $fieldType = $this->getClassName();
501  $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
502  $cellAttributes = [];
503  $rowAttributes = [];
504  $rowClasses = '';
505 
506  if ( !empty( $this->mParams['vertical-label'] ) ) {
507  $cellAttributes['colspan'] = 2;
508  $verticalLabel = true;
509  } else {
510  $verticalLabel = false;
511  }
512 
513  $label = $this->getLabelHtml( $cellAttributes );
514 
515  $field = Html::rawElement(
516  'td',
517  [ 'class' => 'mw-input' ] + $cellAttributes,
518  $inputHtml . "\n$errors"
519  );
520 
521  if ( $this->mHideIf ) {
522  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
523  $rowClasses .= ' mw-htmlform-hide-if';
524  }
525 
526  if ( $verticalLabel ) {
527  $html = Html::rawElement( 'tr',
528  $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
529  $html .= Html::rawElement( 'tr',
530  $rowAttributes + [
531  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
532  ],
533  $field );
534  } else {
535  $html =
536  Html::rawElement( 'tr',
537  $rowAttributes + [
538  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
539  ],
540  $label . $field );
541  }
542 
543  return $html . $helptext;
544  }
545 
556  public function getDiv( $value ) {
557  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
558  $inputHtml = $this->getInputHTML( $value );
559  $fieldType = $this->getClassName();
560  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
561  $cellAttributes = [];
562  $label = $this->getLabelHtml( $cellAttributes );
563 
564  $outerDivClass = [
565  'mw-input',
566  'mw-htmlform-nolabel' => ( $label === '' )
567  ];
568 
569  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
570 
571  if ( $horizontalLabel ) {
572  $field = "\u{00A0}" . $inputHtml . "\n$errors";
573  } else {
574  $field = Html::rawElement(
575  'div',
576  // @phan-suppress-next-line PhanUselessBinaryAddRight
577  [ 'class' => $outerDivClass ] + $cellAttributes,
578  $inputHtml . "\n$errors"
579  );
580  }
581  $divCssClasses = [ "mw-htmlform-field-$fieldType",
582  $this->mClass, $this->mVFormClass, $errorClass ];
583 
584  $wrapperAttributes = [
585  'class' => $divCssClasses,
586  ];
587  if ( $this->mHideIf ) {
588  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
589  $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
590  }
591  $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
592  $html .= $helptext;
593 
594  return $html;
595  }
596 
606  public function getOOUI( $value ) {
607  $inputField = $this->getInputOOUI( $value );
608 
609  if ( !$inputField ) {
610  // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
611  // generate the whole field, label and errors and all, then wrap it in a Widget.
612  // It might look weird, but it'll work OK.
613  return $this->getFieldLayoutOOUI(
614  new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
615  [ 'align' => 'top' ]
616  );
617  }
618 
619  $infusable = true;
620  if ( is_string( $inputField ) ) {
621  // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
622  // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
623  // JavaScript doesn't know how to rebuilt the contents.
624  $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
625  $infusable = false;
626  }
627 
628  $fieldType = $this->getClassName();
629  $help = $this->getHelpText();
630  $errors = $this->getErrorsRaw( $value );
631  foreach ( $errors as &$error ) {
632  $error = new OOUI\HtmlSnippet( $error );
633  }
634 
635  $config = [
636  'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
637  'align' => $this->getLabelAlignOOUI(),
638  'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
639  'errors' => $errors,
640  'infusable' => $infusable,
641  'helpInline' => $this->isHelpInline(),
642  ];
643 
644  $preloadModules = false;
645 
646  if ( $infusable && $this->shouldInfuseOOUI() ) {
647  $preloadModules = true;
648  $config['classes'][] = 'mw-htmlform-autoinfuse';
649  }
650 
651  // the element could specify, that the label doesn't need to be added
652  $label = $this->getLabel();
653  if ( $label && $label !== "\u{00A0}" && $label !== '&#160;' ) {
654  $config['label'] = new OOUI\HtmlSnippet( $label );
655  }
656 
657  if ( $this->mHideIf ) {
658  $preloadModules = true;
659  $config['hideIf'] = $this->mHideIf;
660  }
661 
662  $config['modules'] = $this->getOOUIModules();
663 
664  if ( $preloadModules ) {
665  $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
666  $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
667  }
668 
669  return $this->getFieldLayoutOOUI( $inputField, $config );
670  }
671 
679  protected function getClassName() {
680  $name = explode( '\\', static::class );
681  return end( $name );
682  }
683 
689  protected function getLabelAlignOOUI() {
690  return 'top';
691  }
692 
700  protected function getFieldLayoutOOUI( $inputField, $config ) {
701  if ( isset( $this->mClassWithButton ) ) {
702  $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
703  return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
704  }
705  return new HTMLFormFieldLayout( $inputField, $config );
706  }
707 
716  protected function shouldInfuseOOUI() {
717  // Always infuse fields with popup help text, since the interface for it is nicer with JS
718  return $this->getHelpText() !== null && !$this->isHelpInline();
719  }
720 
728  protected function getOOUIModules() {
729  return [];
730  }
731 
742  public function getRaw( $value ) {
743  list( $errors, ) = $this->getErrorsAndErrorClass( $value );
744  $inputHtml = $this->getInputHTML( $value );
745  $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
746  $cellAttributes = [];
747  $label = $this->getLabelHtml( $cellAttributes );
748 
749  $html = "\n$errors";
750  $html .= $label;
751  $html .= $inputHtml;
752  $html .= $helptext;
753 
754  return $html;
755  }
756 
766  public function getVForm( $value ) {
767  // Ewwww
768  $this->mVFormClass = ' mw-ui-vform-field';
769  return $this->getDiv( $value );
770  }
771 
779  public function getInline( $value ) {
780  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
781  $inputHtml = $this->getInputHTML( $value );
782  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
783  $cellAttributes = [];
784  $label = $this->getLabelHtml( $cellAttributes );
785 
786  $html = "\n" . $errors .
787  $label . "\u{00A0}" .
788  $inputHtml .
789  $helptext;
790 
791  return $html;
792  }
793 
801  public function getHelpTextHtmlTable( $helptext ) {
802  if ( $helptext === null ) {
803  return '';
804  }
805 
806  $rowAttributes = [];
807  if ( $this->mHideIf ) {
808  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
809  $rowAttributes['class'] = 'mw-htmlform-hide-if';
810  }
811 
812  $tdClasses = [ 'htmlform-tip' ];
813  if ( $this->mHelpClass !== false ) {
814  $tdClasses[] = $this->mHelpClass;
815  }
816  $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
817  $row = Html::rawElement( 'tr', $rowAttributes, $row );
818 
819  return $row;
820  }
821 
830  public function getHelpTextHtmlDiv( $helptext ) {
831  if ( $helptext === null ) {
832  return '';
833  }
834 
835  $wrapperAttributes = [
836  'class' => 'htmlform-tip',
837  ];
838  if ( $this->mHelpClass !== false ) {
839  $wrapperAttributes['class'] .= " {$this->mHelpClass}";
840  }
841  if ( $this->mHideIf ) {
842  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
843  $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
844  }
845  $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
846 
847  return $div;
848  }
849 
857  public function getHelpTextHtmlRaw( $helptext ) {
858  return $this->getHelpTextHtmlDiv( $helptext );
859  }
860 
867  public function getHelpText() {
868  $helptext = null;
869 
870  if ( isset( $this->mParams['help-message'] ) ) {
871  $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
872  }
873 
874  if ( isset( $this->mParams['help-messages'] ) ) {
875  foreach ( $this->mParams['help-messages'] as $msg ) {
876  $msg = $this->getMessage( $msg );
877 
878  if ( $msg->exists() ) {
879  if ( $helptext === null ) {
880  $helptext = '';
881  } else {
882  $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
883  }
884  $helptext .= $msg->parse(); // Append message
885  }
886  }
887  } elseif ( isset( $this->mParams['help'] ) ) {
888  $helptext = $this->mParams['help'];
889  }
890 
891  return $helptext;
892  }
893 
902  public function isHelpInline() {
903  return $this->mParams['help-inline'] ?? true;
904  }
905 
918  public function getErrorsAndErrorClass( $value ) {
919  $errors = $this->validate( $value, $this->mParent->mFieldData );
920 
921  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
922  $errors = '';
923  $errorClass = '';
924  } else {
925  $errors = self::formatErrors( $errors );
926  $errorClass = 'mw-htmlform-invalid-input';
927  }
928 
929  return [ $errors, $errorClass ];
930  }
931 
939  public function getErrorsRaw( $value ) {
940  $errors = $this->validate( $value, $this->mParent->mFieldData );
941 
942  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
943  $errors = [];
944  }
945 
946  if ( !is_array( $errors ) ) {
947  $errors = [ $errors ];
948  }
949  foreach ( $errors as &$error ) {
950  if ( $error instanceof Message ) {
951  $error = $error->parse();
952  }
953  }
954 
955  return $errors;
956  }
957 
962  public function getLabel() {
963  return $this->mLabel ?? '';
964  }
965 
972  public function getLabelHtml( $cellAttributes = [] ) {
973  # Don't output a for= attribute for labels with no associated input.
974  # Kind of hacky here, possibly we don't want these to be <label>s at all.
975  $for = [];
976 
977  if ( $this->needsLabel() ) {
978  $for['for'] = $this->mID;
979  }
980 
981  $labelValue = trim( $this->getLabel() );
982  $hasLabel = false;
983  if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
984  $hasLabel = true;
985  }
986 
987  $displayFormat = $this->mParent->getDisplayFormat();
988  $html = '';
989  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
990 
991  if ( $displayFormat === 'table' ) {
992  $html =
993  Html::rawElement( 'td',
994  [ 'class' => 'mw-label' ] + $cellAttributes,
995  Html::rawElement( 'label', $for, $labelValue ) );
996  } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
997  if ( $displayFormat === 'div' && !$horizontalLabel ) {
998  $html =
999  Html::rawElement( 'div',
1000  [ 'class' => 'mw-label' ] + $cellAttributes,
1001  Html::rawElement( 'label', $for, $labelValue ) );
1002  } else {
1003  $html = Html::rawElement( 'label', $for, $labelValue );
1004  }
1005  }
1006 
1007  return $html;
1008  }
1009 
1014  public function getDefault() {
1015  return $this->mDefault ?? null;
1016  }
1017 
1023  public function getTooltipAndAccessKey() {
1024  if ( empty( $this->mParams['tooltip'] ) ) {
1025  return [];
1026  }
1027 
1028  return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1029  }
1030 
1036  public function getTooltipAndAccessKeyOOUI() {
1037  if ( empty( $this->mParams['tooltip'] ) ) {
1038  return [];
1039  }
1040 
1041  return [
1042  'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1043  'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1044  ];
1045  }
1046 
1054  public function getAttributes( array $list ) {
1055  static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1056 
1057  $ret = [];
1058  foreach ( $list as $key ) {
1059  if ( in_array( $key, $boolAttribs ) ) {
1060  if ( !empty( $this->mParams[$key] ) ) {
1061  $ret[$key] = '';
1062  }
1063  } elseif ( isset( $this->mParams[$key] ) ) {
1064  $ret[$key] = $this->mParams[$key];
1065  }
1066  }
1067 
1068  return $ret;
1069  }
1070 
1080  private function lookupOptionsKeys( $options, $needsParse ) {
1081  $ret = [];
1082  foreach ( $options as $key => $value ) {
1083  $msg = $this->msg( $key );
1084  $key = $needsParse ? $msg->parse() : $msg->plain();
1085  $ret[$key] = is_array( $value )
1086  ? $this->lookupOptionsKeys( $value, $needsParse )
1087  : strval( $value );
1088  }
1089  return $ret;
1090  }
1091 
1099  public static function forceToStringRecursive( $array ) {
1100  if ( is_array( $array ) ) {
1101  return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1102  } else {
1103  return strval( $array );
1104  }
1105  }
1106 
1113  public function getOptions() {
1114  if ( $this->mOptions === false ) {
1115  if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1116  $needsParse = $this->mParams['options-messages-parse'] ?? false;
1117  if ( $needsParse ) {
1118  $this->mOptionsLabelsNotFromMessage = true;
1119  }
1120  $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'], $needsParse );
1121  } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1122  $this->mOptionsLabelsNotFromMessage = true;
1123  $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1124  } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1125  $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1126  $this->mOptions = Xml::listDropDownOptions( $message );
1127  } else {
1128  $this->mOptions = null;
1129  }
1130  }
1131 
1132  return $this->mOptions;
1133  }
1134 
1140  public function getOptionsOOUI() {
1141  $oldoptions = $this->getOptions();
1142 
1143  if ( $oldoptions === null ) {
1144  return null;
1145  }
1146 
1147  return Xml::listDropDownOptionsOoui( $oldoptions );
1148  }
1149 
1157  public static function flattenOptions( $options ) {
1158  $flatOpts = [];
1159 
1160  foreach ( $options as $value ) {
1161  if ( is_array( $value ) ) {
1162  $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1163  } else {
1164  $flatOpts[] = $value;
1165  }
1166  }
1167 
1168  return $flatOpts;
1169  }
1170 
1184  protected static function formatErrors( $errors ) {
1185  if ( is_array( $errors ) && count( $errors ) === 1 ) {
1186  $errors = array_shift( $errors );
1187  }
1188 
1189  if ( is_array( $errors ) ) {
1190  $lines = [];
1191  foreach ( $errors as $error ) {
1192  if ( $error instanceof Message ) {
1193  $lines[] = Html::rawElement( 'li', [], $error->parse() );
1194  } else {
1195  $lines[] = Html::rawElement( 'li', [], $error );
1196  }
1197  }
1198 
1199  $errors = Html::rawElement( 'ul', [], implode( "\n", $lines ) );
1200  } else {
1201  if ( $errors instanceof Message ) {
1202  $errors = $errors->parse();
1203  }
1204  }
1205 
1206  return Html::rawElement( 'div', [ 'class' => 'errorbox' ], $errors );
1207  }
1208 
1215  protected function getMessage( $value ) {
1216  $message = Message::newFromSpecifier( $value );
1217 
1218  if ( $this->mParent ) {
1219  $message->setContext( $this->mParent );
1220  }
1221 
1222  return $message;
1223  }
1224 
1232  public function skipLoadData( $request ) {
1233  return !empty( $this->mParams['nodata'] );
1234  }
1235 
1243  public function needsJSForHtml5FormValidation() {
1244  if ( $this->mHideIf ) {
1245  // This is probably more restrictive than it needs to be, but better safe than sorry
1246  return true;
1247  }
1248  return false;
1249  }
1250 }
HTMLFormField\getOptions
getOptions()
Fetch the array of options from the field's parameters.
Definition: HTMLFormField.php:1113
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:406
HTMLFormField\__construct
__construct( $params)
Initialise the object.
Definition: HTMLFormField.php:410
HTMLFormField\$mHelpClass
$mHelpClass
Definition: HTMLFormField.php:23
HTMLFormField\getTooltipAndAccessKeyOOUI
getTooltipAndAccessKeyOOUI()
Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
Definition: HTMLFormField.php:1036
HTMLFormField\getClassName
getClassName()
Gets the non namespaced class name.
Definition: HTMLFormField.php:679
HTMLFormField\$mLabel
$mLabel
Definition: HTMLFormField.php:19
HTMLFormField\isHiddenRecurse
isHiddenRecurse(array $alldata, array $params)
Helper function for isHidden to handle recursive data structures.
Definition: HTMLFormField.php:169
Xml\listDropDownOptionsOoui
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:594
HTMLFormField\setShowEmptyLabel
setShowEmptyLabel( $show)
Tell the field whether to generate a separate label element if its label is blank.
Definition: HTMLFormField.php:366
HTMLFormField\getErrorsAndErrorClass
getErrorsAndErrorClass( $value)
Determine form errors to display and their classes.
Definition: HTMLFormField.php:918
HTMLFormField\validate
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.
Definition: HTMLFormField.php:311
HTMLFormActionFieldLayout
Definition: HTMLFormActionFieldLayout.php:6
HTMLFormField\formatErrors
static formatErrors( $errors)
Formats one or more errors as accepted by field validation-callback.
Definition: HTMLFormField.php:1184
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1182
HTMLFormField\hasVisibleOutput
hasVisibleOutput()
If this field has a user-visible output or not.
Definition: HTMLFormField.php:103
HTMLFormField\getMessage
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
Definition: HTMLFormField.php:1215
HTMLFormField\getNearestFieldByName
getNearestFieldByName( $alldata, $name)
Fetch a field value from $alldata for the closest field matching a given name.
Definition: HTMLFormField.php:120
HTMLFormField\$mClass
$mClass
Definition: HTMLFormField.php:21
HTMLFormField\shouldInfuseOOUI
shouldInfuseOOUI()
Whether the field should be automatically infused.
Definition: HTMLFormField.php:716
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:353
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2457
HTMLFormField\$mDir
$mDir
Definition: HTMLFormField.php:18
HTMLFormField\skipLoadData
skipLoadData( $request)
Skip this field when collecting data.
Definition: HTMLFormField.php:1232
HTMLFormField\$mOptions
array bool null $mOptions
Definition: HTMLFormField.php:28
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:1080
HTMLFormField\getTableRow
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:497
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:295
HTMLFormField\getLabelHtml
getLabelHtml( $cellAttributes=[])
Definition: HTMLFormField.php:972
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:73
HTMLFormField\getHelpTextHtmlTable
getHelpTextHtmlTable( $helptext)
Generate help text HTML in table format.
Definition: HTMLFormField.php:801
HTMLFormField\$mParent
HTMLForm null $mParent
Definition: HTMLFormField.php:41
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:867
MWException
MediaWiki exception.
Definition: MWException.php:29
HTMLFormField\$mName
$mName
Definition: HTMLFormField.php:17
HTMLFormField\isHelpInline
isHelpInline()
Determine if the help text should be displayed inline.
Definition: HTMLFormField.php:902
HTMLFormField\getLabelAlignOOUI
getLabelAlignOOUI()
Get label alignment when generating field for OOUI.
Definition: HTMLFormField.php:689
HTMLFormField
The parent class to generate form fields.
Definition: HTMLFormField.php:11
HTMLFormField\$mDefault
$mDefault
Definition: HTMLFormField.php:24
HTMLFormField\needsJSForHtml5FormValidation
needsJSForHtml5FormValidation()
Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5 form ...
Definition: HTMLFormField.php:1243
HTMLFormField\filter
filter( $value, $alldata)
Definition: HTMLFormField.php:338
HTMLFormField\$mID
$mID
Definition: HTMLFormField.php:20
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:655
HTMLFormField\getOOUI
getOOUI( $value)
Get the OOUI version of the div.
Definition: HTMLFormField.php:606
MediaWiki\Session\CsrfTokenSet
Definition: CsrfTokenSet.php:31
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:276
HTMLFormField\$mValidationCallback
$mValidationCallback
Definition: HTMLFormField.php:15
HTMLFormField\getDefault
getDefault()
Definition: HTMLFormField.php:1014
HTMLFormFieldLayout
Definition: HTMLFormFieldLayout.php:6
HTMLFormField\$mFilterCallback
$mFilterCallback
Definition: HTMLFormField.php:16
HTMLFormField\getFieldLayoutOOUI
getFieldLayoutOOUI( $inputField, $config)
Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
Definition: HTMLFormField.php:700
HTMLFormField\getLabel
getLabel()
Definition: HTMLFormField.php:962
HTMLFormField\getHelpTextHtmlRaw
getHelpTextHtmlRaw( $helptext)
Generate help text HTML formatted for raw output.
Definition: HTMLFormField.php:857
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:2278
$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:42
HTMLFormField\getOOUIModules
getOOUIModules()
Get the list of extra ResourceLoader modules which must be loaded client-side before it's possible to...
Definition: HTMLFormField.php:728
HTMLFormField\getInputOOUI
getInputOOUI( $value)
Same as getInputHTML, but returns an OOUI object.
Definition: HTMLFormField.php:63
HTMLFormField\$mShowEmptyLabels
bool $mShowEmptyLabels
If true will generate an empty div element with no label.
Definition: HTMLFormField.php:36
HTMLFormField\getDiv
getDiv( $value)
Get the complete div for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:556
HTMLFormField\getVForm
getVForm( $value)
Get the complete field for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:766
HTMLFormField\$mParams
array array[] $mParams
Definition: HTMLFormField.php:13
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:210
HTMLFormField\$mOptionsLabelsNotFromMessage
$mOptionsLabelsNotFromMessage
Definition: HTMLFormField.php:29
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:138
HTMLFormField\getRaw
getRaw( $value)
Get the complete raw fields for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:742
$keys
$keys
Definition: testCompression.php:72
HTMLFormField\getErrorsRaw
getErrorsRaw( $value)
Determine form errors to display, returning them in an array.
Definition: HTMLFormField.php:939
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:1099
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:380
$help
$help
Definition: mcc.php:32
HTMLFormField\$mHideIf
$mHideIf
Definition: HTMLFormField.php:30
HTMLFormField\getTooltipAndAccessKey
getTooltipAndAccessKey()
Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
Definition: HTMLFormField.php:1023
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:1157
HTMLFormField\msg
msg( $key,... $params)
Get a translated interface message.
Definition: HTMLFormField.php:89
HTMLFormField\$mVFormClass
$mVFormClass
Definition: HTMLFormField.php:22
HTMLFormField\getHelpTextHtmlDiv
getHelpTextHtmlDiv( $helptext)
Generate help text HTML in div format.
Definition: HTMLFormField.php:830
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2326
HTMLFormField\getInline
getInline( $value)
Get the complete field as an inline element.
Definition: HTMLFormField.php:779
HTMLFormField\getOptionsOOUI
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
Definition: HTMLFormField.php:1140
Xml\listDropDownOptions
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:545
HTMLFormField\getAttributes
getAttributes(array $list)
Returns the given attributes from the parameters.
Definition: HTMLFormField.php:1054
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:144
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:393