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;
28  protected $mHideIf = null;
29 
34  protected $mShowEmptyLabels = true;
35 
39  public $mParent;
40 
51  abstract public function getInputHTML( $value );
52 
61  public function getInputOOUI( $value ) {
62  return false;
63  }
64 
71  public function canDisplayErrors() {
72  return $this->hasVisibleOutput();
73  }
74 
87  public function msg( $key, ...$params ) {
88  if ( $this->mParent ) {
89  return $this->mParent->msg( $key, ...$params );
90  }
91  return wfMessage( $key, ...$params );
92  }
93 
101  public function hasVisibleOutput() {
102  return true;
103  }
104 
118  protected function getNearestFieldByName( $alldata, $name ) {
119  $tmp = $this->mName;
120  $thisKeys = [];
121  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
122  array_unshift( $thisKeys, $m[2] );
123  $tmp = $m[1];
124  }
125  if ( substr( $tmp, 0, 2 ) == 'wp' &&
126  !array_key_exists( $tmp, $alldata ) &&
127  array_key_exists( substr( $tmp, 2 ), $alldata )
128  ) {
129  // Adjust for name mangling.
130  $tmp = substr( $tmp, 2 );
131  }
132  array_unshift( $thisKeys, $tmp );
133 
134  $tmp = $name;
135  $nameKeys = [];
136  while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
137  array_unshift( $nameKeys, $m[2] );
138  $tmp = $m[1];
139  }
140  array_unshift( $nameKeys, $tmp );
141 
142  $testValue = '';
143  for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
144  $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
145  $data = $alldata;
146  foreach ( $keys as $key ) {
147  if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
148  continue 2;
149  }
150  $data = $data[$key];
151  }
152  $testValue = (string)$data;
153  break;
154  }
155 
156  return $testValue;
157  }
158 
167  protected function isHiddenRecurse( array $alldata, array $params ) {
168  $origParams = $params;
169  $op = array_shift( $params );
170 
171  try {
172  switch ( $op ) {
173  case 'AND':
174  foreach ( $params as $i => $p ) {
175  if ( !is_array( $p ) ) {
176  throw new MWException(
177  "Expected array, found " . gettype( $p ) . " at index $i"
178  );
179  }
180  if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
181  return false;
182  }
183  }
184  return true;
185 
186  case 'OR':
187  foreach ( $params as $i => $p ) {
188  if ( !is_array( $p ) ) {
189  throw new MWException(
190  "Expected array, found " . gettype( $p ) . " at index $i"
191  );
192  }
193  if ( $this->isHiddenRecurse( $alldata, $p ) ) {
194  return true;
195  }
196  }
197  return false;
198 
199  case 'NAND':
200  foreach ( $params as $i => $p ) {
201  if ( !is_array( $p ) ) {
202  throw new MWException(
203  "Expected array, found " . gettype( $p ) . " at index $i"
204  );
205  }
206  if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
207  return true;
208  }
209  }
210  return false;
211 
212  case 'NOR':
213  foreach ( $params as $i => $p ) {
214  if ( !is_array( $p ) ) {
215  throw new MWException(
216  "Expected array, found " . gettype( $p ) . " at index $i"
217  );
218  }
219  if ( $this->isHiddenRecurse( $alldata, $p ) ) {
220  return false;
221  }
222  }
223  return true;
224 
225  case 'NOT':
226  if ( count( $params ) !== 1 ) {
227  throw new MWException( "NOT takes exactly one parameter" );
228  }
229  $p = $params[0];
230  if ( !is_array( $p ) ) {
231  throw new MWException(
232  "Expected array, found " . gettype( $p ) . " at index 0"
233  );
234  }
235  return !$this->isHiddenRecurse( $alldata, $p );
236 
237  case '===':
238  case '!==':
239  if ( count( $params ) !== 2 ) {
240  throw new MWException( "$op takes exactly two parameters" );
241  }
242  list( $field, $value ) = $params;
243  if ( !is_string( $field ) || !is_string( $value ) ) {
244  throw new MWException( "Parameters for $op must be strings" );
245  }
246  $testValue = $this->getNearestFieldByName( $alldata, $field );
247  switch ( $op ) {
248  case '===':
249  return ( $value === $testValue );
250  case '!==':
251  return ( $value !== $testValue );
252  }
253 
254  default:
255  throw new MWException( "Unknown operation" );
256  }
257  } catch ( Exception $ex ) {
258  throw new MWException(
259  "Invalid hide-if specification for $this->mName: " .
260  $ex->getMessage() . " in " . var_export( $origParams, true ),
261  0, $ex
262  );
263  }
264  }
265 
274  public function isHidden( $alldata ) {
275  if ( !$this->mHideIf ) {
276  return false;
277  }
278 
279  return $this->isHiddenRecurse( $alldata, $this->mHideIf );
280  }
281 
293  public function cancelSubmit( $value, $alldata ) {
294  return false;
295  }
296 
309  public function validate( $value, $alldata ) {
310  if ( $this->isHidden( $alldata ) ) {
311  return true;
312  }
313 
314  if ( isset( $this->mParams['required'] )
315  && $this->mParams['required'] !== false
316  && $value === ''
317  ) {
318  return $this->msg( 'htmlform-required' );
319  }
320 
321  if ( isset( $this->mValidationCallback ) ) {
322  return ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
323  }
324 
325  return true;
326  }
327 
336  public function filter( $value, $alldata ) {
337  if ( isset( $this->mFilterCallback ) ) {
338  $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
339  }
340 
341  return $value;
342  }
343 
351  protected function needsLabel() {
352  return true;
353  }
354 
364  public function setShowEmptyLabel( $show ) {
365  $this->mShowEmptyLabels = $show;
366  }
367 
378  protected function isSubmitAttempt( WebRequest $request ) {
379  return $request->getCheck( 'wpEditToken' ) || $request->getCheck( 'wpFormIdentifier' );
380  }
381 
390  public function loadDataFromRequest( $request ) {
391  if ( $request->getCheck( $this->mName ) ) {
392  return $request->getText( $this->mName );
393  } else {
394  return $this->getDefault();
395  }
396  }
397 
407  public function __construct( $params ) {
408  $this->mParams = $params;
409 
410  if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
411  $this->mParent = $params['parent'];
412  }
413 
414  # Generate the label from a message, if possible
415  if ( isset( $params['label-message'] ) ) {
416  $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
417  } elseif ( isset( $params['label'] ) ) {
418  if ( $params['label'] === '&#160;' || $params['label'] === "\u{00A0}" ) {
419  // Apparently some things set &nbsp directly and in an odd format
420  $this->mLabel = "\u{00A0}";
421  } else {
422  $this->mLabel = htmlspecialchars( $params['label'] );
423  }
424  } elseif ( isset( $params['label-raw'] ) ) {
425  $this->mLabel = $params['label-raw'];
426  }
427 
428  $this->mName = "wp{$params['fieldname']}";
429  if ( isset( $params['name'] ) ) {
430  $this->mName = $params['name'];
431  }
432 
433  if ( isset( $params['dir'] ) ) {
434  $this->mDir = $params['dir'];
435  }
436 
437  $validName = urlencode( $this->mName );
438  $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
439  if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
440  throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
441  }
442 
443  $this->mID = "mw-input-{$this->mName}";
444 
445  if ( isset( $params['default'] ) ) {
446  $this->mDefault = $params['default'];
447  }
448 
449  if ( isset( $params['id'] ) ) {
450  $id = $params['id'];
451  $validId = urlencode( $id );
452 
453  if ( $id != $validId ) {
454  throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
455  }
456 
457  $this->mID = $id;
458  }
459 
460  if ( isset( $params['cssclass'] ) ) {
461  $this->mClass = $params['cssclass'];
462  }
463 
464  if ( isset( $params['csshelpclass'] ) ) {
465  $this->mHelpClass = $params['csshelpclass'];
466  }
467 
468  if ( isset( $params['validation-callback'] ) ) {
469  $this->mValidationCallback = $params['validation-callback'];
470  }
471 
472  if ( isset( $params['filter-callback'] ) ) {
473  $this->mFilterCallback = $params['filter-callback'];
474  }
475 
476  if ( isset( $params['hidelabel'] ) ) {
477  $this->mShowEmptyLabels = false;
478  }
479 
480  if ( isset( $params['hide-if'] ) ) {
481  $this->mHideIf = $params['hide-if'];
482  }
483  }
484 
494  public function getTableRow( $value ) {
495  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
496  $inputHtml = $this->getInputHTML( $value );
497  $fieldType = static::class;
498  $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
499  $cellAttributes = [];
500  $rowAttributes = [];
501  $rowClasses = '';
502 
503  if ( !empty( $this->mParams['vertical-label'] ) ) {
504  $cellAttributes['colspan'] = 2;
505  $verticalLabel = true;
506  } else {
507  $verticalLabel = false;
508  }
509 
510  $label = $this->getLabelHtml( $cellAttributes );
511 
512  $field = Html::rawElement(
513  'td',
514  [ 'class' => 'mw-input' ] + $cellAttributes,
515  $inputHtml . "\n$errors"
516  );
517 
518  if ( $this->mHideIf ) {
519  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
520  $rowClasses .= ' mw-htmlform-hide-if';
521  }
522 
523  if ( $verticalLabel ) {
524  $html = Html::rawElement( 'tr',
525  $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
526  $html .= Html::rawElement( 'tr',
527  $rowAttributes + [
528  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
529  ],
530  $field );
531  } else {
532  $html =
533  Html::rawElement( 'tr',
534  $rowAttributes + [
535  'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
536  ],
537  $label . $field );
538  }
539 
540  return $html . $helptext;
541  }
542 
553  public function getDiv( $value ) {
554  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
555  $inputHtml = $this->getInputHTML( $value );
556  $fieldType = static::class;
557  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
558  $cellAttributes = [];
559  $label = $this->getLabelHtml( $cellAttributes );
560 
561  $outerDivClass = [
562  'mw-input',
563  'mw-htmlform-nolabel' => ( $label === '' )
564  ];
565 
566  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
567 
568  if ( $horizontalLabel ) {
569  $field = "\u{00A0}" . $inputHtml . "\n$errors";
570  } else {
571  $field = Html::rawElement(
572  'div',
573  // @phan-suppress-next-line PhanUselessBinaryAddRight
574  [ 'class' => $outerDivClass ] + $cellAttributes,
575  $inputHtml . "\n$errors"
576  );
577  }
578  $divCssClasses = [ "mw-htmlform-field-$fieldType",
579  $this->mClass, $this->mVFormClass, $errorClass ];
580 
581  $wrapperAttributes = [
582  'class' => $divCssClasses,
583  ];
584  if ( $this->mHideIf ) {
585  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
586  $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
587  }
588  $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
589  $html .= $helptext;
590 
591  return $html;
592  }
593 
603  public function getOOUI( $value ) {
604  $inputField = $this->getInputOOUI( $value );
605 
606  if ( !$inputField ) {
607  // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
608  // generate the whole field, label and errors and all, then wrap it in a Widget.
609  // It might look weird, but it'll work OK.
610  return $this->getFieldLayoutOOUI(
611  new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
612  [ 'align' => 'top' ]
613  );
614  }
615 
616  $infusable = true;
617  if ( is_string( $inputField ) ) {
618  // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
619  // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
620  // JavaScript doesn't know how to rebuilt the contents.
621  $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
622  $infusable = false;
623  }
624 
625  $fieldType = static::class;
626  $help = $this->getHelpText();
627  $errors = $this->getErrorsRaw( $value );
628  foreach ( $errors as &$error ) {
629  $error = new OOUI\HtmlSnippet( $error );
630  }
631 
632  $config = [
633  'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
634  'align' => $this->getLabelAlignOOUI(),
635  'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
636  'errors' => $errors,
637  'infusable' => $infusable,
638  'helpInline' => $this->isHelpInline(),
639  ];
640 
641  $preloadModules = false;
642 
643  if ( $infusable && $this->shouldInfuseOOUI() ) {
644  $preloadModules = true;
645  $config['classes'][] = 'mw-htmlform-field-autoinfuse';
646  }
647 
648  // the element could specify, that the label doesn't need to be added
649  $label = $this->getLabel();
650  if ( $label && $label !== "\u{00A0}" && $label !== '&#160;' ) {
651  $config['label'] = new OOUI\HtmlSnippet( $label );
652  }
653 
654  if ( $this->mHideIf ) {
655  $preloadModules = true;
656  $config['hideIf'] = $this->mHideIf;
657  }
658 
659  $config['modules'] = $this->getOOUIModules();
660 
661  if ( $preloadModules ) {
662  $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
663  $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
664  }
665 
666  return $this->getFieldLayoutOOUI( $inputField, $config );
667  }
668 
674  protected function getLabelAlignOOUI() {
675  return 'top';
676  }
677 
685  protected function getFieldLayoutOOUI( $inputField, $config ) {
686  if ( isset( $this->mClassWithButton ) ) {
687  $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
688  return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
689  }
690  return new HTMLFormFieldLayout( $inputField, $config );
691  }
692 
701  protected function shouldInfuseOOUI() {
702  // Always infuse fields with popup help text, since the interface for it is nicer with JS
703  return $this->getHelpText() !== null && !$this->isHelpInline();
704  }
705 
713  protected function getOOUIModules() {
714  return [];
715  }
716 
727  public function getRaw( $value ) {
728  list( $errors, ) = $this->getErrorsAndErrorClass( $value );
729  $inputHtml = $this->getInputHTML( $value );
730  $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
731  $cellAttributes = [];
732  $label = $this->getLabelHtml( $cellAttributes );
733 
734  $html = "\n$errors";
735  $html .= $label;
736  $html .= $inputHtml;
737  $html .= $helptext;
738 
739  return $html;
740  }
741 
751  public function getVForm( $value ) {
752  // Ewwww
753  $this->mVFormClass = ' mw-ui-vform-field';
754  return $this->getDiv( $value );
755  }
756 
764  public function getInline( $value ) {
765  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
766  $inputHtml = $this->getInputHTML( $value );
767  $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
768  $cellAttributes = [];
769  $label = $this->getLabelHtml( $cellAttributes );
770 
771  $html = "\n" . $errors .
772  $label . "\u{00A0}" .
773  $inputHtml .
774  $helptext;
775 
776  return $html;
777  }
778 
786  public function getHelpTextHtmlTable( $helptext ) {
787  if ( $helptext === null ) {
788  return '';
789  }
790 
791  $rowAttributes = [];
792  if ( $this->mHideIf ) {
793  $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
794  $rowAttributes['class'] = 'mw-htmlform-hide-if';
795  }
796 
797  $tdClasses = [ 'htmlform-tip' ];
798  if ( $this->mHelpClass !== false ) {
799  $tdClasses[] = $this->mHelpClass;
800  }
801  $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
802  $row = Html::rawElement( 'tr', $rowAttributes, $row );
803 
804  return $row;
805  }
806 
815  public function getHelpTextHtmlDiv( $helptext ) {
816  if ( $helptext === null ) {
817  return '';
818  }
819 
820  $wrapperAttributes = [
821  'class' => 'htmlform-tip',
822  ];
823  if ( $this->mHelpClass !== false ) {
824  $wrapperAttributes['class'] .= " {$this->mHelpClass}";
825  }
826  if ( $this->mHideIf ) {
827  $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
828  $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
829  }
830  $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
831 
832  return $div;
833  }
834 
842  public function getHelpTextHtmlRaw( $helptext ) {
843  return $this->getHelpTextHtmlDiv( $helptext );
844  }
845 
852  public function getHelpText() {
853  $helptext = null;
854 
855  if ( isset( $this->mParams['help-message'] ) ) {
856  $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
857  }
858 
859  if ( isset( $this->mParams['help-messages'] ) ) {
860  foreach ( $this->mParams['help-messages'] as $msg ) {
861  $msg = $this->getMessage( $msg );
862 
863  if ( $msg->exists() ) {
864  if ( $helptext === null ) {
865  $helptext = '';
866  } else {
867  $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
868  }
869  $helptext .= $msg->parse(); // Append message
870  }
871  }
872  } elseif ( isset( $this->mParams['help'] ) ) {
873  $helptext = $this->mParams['help'];
874  }
875 
876  return $helptext;
877  }
878 
887  public function isHelpInline() {
888  return $this->mParams['help-inline'] ?? true;
889  }
890 
903  public function getErrorsAndErrorClass( $value ) {
904  $errors = $this->validate( $value, $this->mParent->mFieldData );
905 
906  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
907  $errors = '';
908  $errorClass = '';
909  } else {
910  $errors = self::formatErrors( $errors );
911  $errorClass = 'mw-htmlform-invalid-input';
912  }
913 
914  return [ $errors, $errorClass ];
915  }
916 
924  public function getErrorsRaw( $value ) {
925  $errors = $this->validate( $value, $this->mParent->mFieldData );
926 
927  if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
928  $errors = [];
929  }
930 
931  if ( !is_array( $errors ) ) {
932  $errors = [ $errors ];
933  }
934  foreach ( $errors as &$error ) {
935  if ( $error instanceof Message ) {
936  $error = $error->parse();
937  }
938  }
939 
940  return $errors;
941  }
942 
947  public function getLabel() {
948  return $this->mLabel ?? '';
949  }
950 
957  public function getLabelHtml( $cellAttributes = [] ) {
958  # Don't output a for= attribute for labels with no associated input.
959  # Kind of hacky here, possibly we don't want these to be <label>s at all.
960  $for = [];
961 
962  if ( $this->needsLabel() ) {
963  $for['for'] = $this->mID;
964  }
965 
966  $labelValue = trim( $this->getLabel() );
967  $hasLabel = false;
968  if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
969  $hasLabel = true;
970  }
971 
972  $displayFormat = $this->mParent->getDisplayFormat();
973  $html = '';
974  $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
975 
976  if ( $displayFormat === 'table' ) {
977  $html =
978  Html::rawElement( 'td',
979  [ 'class' => 'mw-label' ] + $cellAttributes,
980  Html::rawElement( 'label', $for, $labelValue ) );
981  } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
982  if ( $displayFormat === 'div' && !$horizontalLabel ) {
983  $html =
984  Html::rawElement( 'div',
985  [ 'class' => 'mw-label' ] + $cellAttributes,
986  Html::rawElement( 'label', $for, $labelValue ) );
987  } else {
988  $html = Html::rawElement( 'label', $for, $labelValue );
989  }
990  }
991 
992  return $html;
993  }
994 
999  public function getDefault() {
1000  return $this->mDefault ?? null;
1001  }
1002 
1008  public function getTooltipAndAccessKey() {
1009  if ( empty( $this->mParams['tooltip'] ) ) {
1010  return [];
1011  }
1012 
1013  return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1014  }
1015 
1021  public function getTooltipAndAccessKeyOOUI() {
1022  if ( empty( $this->mParams['tooltip'] ) ) {
1023  return [];
1024  }
1025 
1026  return [
1027  'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1028  'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1029  ];
1030  }
1031 
1039  public function getAttributes( array $list ) {
1040  static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1041 
1042  $ret = [];
1043  foreach ( $list as $key ) {
1044  if ( in_array( $key, $boolAttribs ) ) {
1045  if ( !empty( $this->mParams[$key] ) ) {
1046  $ret[$key] = '';
1047  }
1048  } elseif ( isset( $this->mParams[$key] ) ) {
1049  $ret[$key] = $this->mParams[$key];
1050  }
1051  }
1052 
1053  return $ret;
1054  }
1055 
1063  private function lookupOptionsKeys( $options ) {
1064  $ret = [];
1065  foreach ( $options as $key => $value ) {
1066  $key = $this->msg( $key )->plain();
1067  $ret[$key] = is_array( $value )
1068  ? $this->lookupOptionsKeys( $value )
1069  : strval( $value );
1070  }
1071  return $ret;
1072  }
1073 
1081  public static function forceToStringRecursive( $array ) {
1082  if ( is_array( $array ) ) {
1083  return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1084  } else {
1085  return strval( $array );
1086  }
1087  }
1088 
1095  public function getOptions() {
1096  if ( $this->mOptions === false ) {
1097  if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1098  $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
1099  } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1100  $this->mOptionsLabelsNotFromMessage = true;
1101  $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1102  } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1103  $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1104  $this->mOptions = Xml::listDropDownOptions( $message );
1105  } else {
1106  $this->mOptions = null;
1107  }
1108  }
1109 
1110  return $this->mOptions;
1111  }
1112 
1118  public function getOptionsOOUI() {
1119  $oldoptions = $this->getOptions();
1120 
1121  if ( $oldoptions === null ) {
1122  return null;
1123  }
1124 
1125  return Xml::listDropDownOptionsOoui( $oldoptions );
1126  }
1127 
1135  public static function flattenOptions( $options ) {
1136  $flatOpts = [];
1137 
1138  foreach ( $options as $value ) {
1139  if ( is_array( $value ) ) {
1140  $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1141  } else {
1142  $flatOpts[] = $value;
1143  }
1144  }
1145 
1146  return $flatOpts;
1147  }
1148 
1162  protected static function formatErrors( $errors ) {
1163  // Note: If you change the logic in this method, change
1164  // htmlform.Checker.js to match.
1165 
1166  if ( is_array( $errors ) && count( $errors ) === 1 ) {
1167  $errors = array_shift( $errors );
1168  }
1169 
1170  if ( is_array( $errors ) ) {
1171  $lines = [];
1172  foreach ( $errors as $error ) {
1173  if ( $error instanceof Message ) {
1174  $lines[] = Html::rawElement( 'li', [], $error->parse() );
1175  } else {
1176  $lines[] = Html::rawElement( 'li', [], $error );
1177  }
1178  }
1179 
1180  $errors = Html::rawElement( 'ul', [], implode( "\n", $lines ) );
1181  } else {
1182  if ( $errors instanceof Message ) {
1183  $errors = $errors->parse();
1184  }
1185  }
1186 
1187  return Html::rawElement( 'div', [ 'class' => 'errorbox' ], $errors );
1188  }
1189 
1196  protected function getMessage( $value ) {
1197  $message = Message::newFromSpecifier( $value );
1198 
1199  if ( $this->mParent ) {
1200  $message->setContext( $this->mParent );
1201  }
1202 
1203  return $message;
1204  }
1205 
1213  public function skipLoadData( $request ) {
1214  return !empty( $this->mParams['nodata'] );
1215  }
1216 
1224  public function needsJSForHtml5FormValidation() {
1225  if ( $this->mHideIf ) {
1226  // This is probably more restrictive than it needs to be, but better safe than sorry
1227  return true;
1228  }
1229  return false;
1230  }
1231 }
HTMLFormField\getOptions
getOptions()
Fetch the array of options from the field's parameters.
Definition: HTMLFormField.php:1095
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:436
HTMLFormField\__construct
__construct( $params)
Initialise the object.
Definition: HTMLFormField.php:407
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:1021
HTMLFormField\$mLabel
$mLabel
Definition: HTMLFormField.php:17
HTMLFormField\isHiddenRecurse
isHiddenRecurse(array $alldata, array $params)
Helper function for isHidden to handle recursive data structures.
Definition: HTMLFormField.php:167
Xml\listDropDownOptionsOoui
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:585
HTMLFormField\setShowEmptyLabel
setShowEmptyLabel( $show)
Tell the field whether to generate a separate label element if its label is blank.
Definition: HTMLFormField.php:364
HTMLFormField\getErrorsAndErrorClass
getErrorsAndErrorClass( $value)
Determine form errors to display and their classes.
Definition: HTMLFormField.php:903
HTMLFormField\validate
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.
Definition: HTMLFormField.php:309
HTMLFormActionFieldLayout
Definition: HTMLFormActionFieldLayout.php:6
HTMLFormField\formatErrors
static formatErrors( $errors)
Formats one or more errors as accepted by field validation-callback.
Definition: HTMLFormField.php:1162
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1219
HTMLFormField\hasVisibleOutput
hasVisibleOutput()
If this field has a user-visible output or not.
Definition: HTMLFormField.php:101
HTMLFormField\getMessage
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
Definition: HTMLFormField.php:1196
HTMLFormField\getNearestFieldByName
getNearestFieldByName( $alldata, $name)
Fetch a field value from $alldata for the closest field matching a given name.
Definition: HTMLFormField.php:118
HTMLFormField\$mClass
$mClass
Definition: HTMLFormField.php:19
HTMLFormField\shouldInfuseOOUI
shouldInfuseOOUI()
Whether the field should be automatically infused.
Definition: HTMLFormField.php:701
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:351
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2294
HTMLFormField\$mDir
$mDir
Definition: HTMLFormField.php:16
HTMLFormField\skipLoadData
skipLoadData( $request)
Skip this field when collecting data.
Definition: HTMLFormField.php:1213
HTMLFormField\$mOptions
array bool null $mOptions
Definition: HTMLFormField.php:26
HTMLFormField\getTableRow
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:494
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:293
HTMLFormField\getLabelHtml
getLabelHtml( $cellAttributes=[])
Stable to override.
Definition: HTMLFormField.php:957
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:71
HTMLFormField\getHelpTextHtmlTable
getHelpTextHtmlTable( $helptext)
Generate help text HTML in table format.
Definition: HTMLFormField.php:786
HTMLFormField\$mParent
HTMLForm null $mParent
Definition: HTMLFormField.php:39
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 Stable to override.
Definition: HTMLFormField.php:852
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:887
HTMLFormField\getLabelAlignOOUI
getLabelAlignOOUI()
Get label alignment when generating field for OOUI.
Definition: HTMLFormField.php:674
HTMLFormField
The parent class to generate form fields.
Definition: HTMLFormField.php:9
HTMLFormField\lookupOptionsKeys
lookupOptionsKeys( $options)
Given an array of msg-key => value mappings, returns an array with keys being the message texts.
Definition: HTMLFormField.php:1063
HTMLFormField\$mDefault
$mDefault
Definition: HTMLFormField.php:22
HTMLFormField\needsJSForHtml5FormValidation
needsJSForHtml5FormValidation()
Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5 form ...
Definition: HTMLFormField.php:1224
HTMLFormField\filter
filter( $value, $alldata)
Stable to override.
Definition: HTMLFormField.php:336
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:657
HTMLFormField\getOOUI
getOOUI( $value)
Get the OOUI version of the div.
Definition: HTMLFormField.php:603
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:274
HTMLFormField\$mValidationCallback
$mValidationCallback
Definition: HTMLFormField.php:13
HTMLFormField\getDefault
getDefault()
Stable to override.
Definition: HTMLFormField.php:999
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:685
HTMLFormField\getLabel
getLabel()
Stable to override.
Definition: HTMLFormField.php:947
HTMLFormField\getHelpTextHtmlRaw
getHelpTextHtmlRaw( $helptext)
Generate help text HTML formatted for raw output.
Definition: HTMLFormField.php:842
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:2110
$lines
if(!file_exists( $CREDITS)) $lines
Definition: updateCredits.php:49
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:713
HTMLFormField\getInputOOUI
getInputOOUI( $value)
Same as getInputHTML, but returns an OOUI object.
Definition: HTMLFormField.php:61
HTMLFormField\$mShowEmptyLabels
bool $mShowEmptyLabels
If true will generate an empty div element with no label.
Definition: HTMLFormField.php:34
HTMLFormField\getDiv
getDiv( $value)
Get the complete div for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:553
HTMLFormField\getVForm
getVForm( $value)
Get the complete field for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:751
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:209
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:161
HTMLFormField\getRaw
getRaw( $value)
Get the complete raw fields for the input, including help text, labels, and whatever.
Definition: HTMLFormField.php:727
$keys
$keys
Definition: testCompression.php:72
HTMLFormField\getErrorsRaw
getErrorsRaw( $value)
Determine form errors to display, returning them in an array.
Definition: HTMLFormField.php:924
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:1081
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:378
$help
$help
Definition: mcc.php:32
HTMLFormField\$mHideIf
$mHideIf
Definition: HTMLFormField.php:28
HTMLFormField\getTooltipAndAccessKey
getTooltipAndAccessKey()
Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
Definition: HTMLFormField.php:1008
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:1135
HTMLFormField\msg
msg( $key,... $params)
Get a translated interface message.
Definition: HTMLFormField.php:87
HTMLFormField\$mVFormClass
$mVFormClass
Definition: HTMLFormField.php:20
HTMLFormField\getHelpTextHtmlDiv
getHelpTextHtmlDiv( $helptext)
Generate help text HTML in div format.
Definition: HTMLFormField.php:815
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2158
HTMLFormField\getInline
getInline( $value)
Get the complete field as an inline element.
Definition: HTMLFormField.php:764
HTMLFormField\getOptionsOOUI
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
Definition: HTMLFormField.php:1118
Xml\listDropDownOptions
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:543
HTMLFormField\getAttributes
getAttributes(array $list)
Returns the given attributes from the parameters Stable to override.
Definition: HTMLFormField.php:1039
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:135
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:390