HTMLFormField.php 31 KB

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