HTMLForm.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. <?php
  2. /**
  3. * HTML form generation and submission handling.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. /**
  23. * Object handling generic submission, CSRF protection, layout and
  24. * other logic for UI forms in a reusable manner.
  25. *
  26. * In order to generate the form, the HTMLForm object takes an array
  27. * structure detailing the form fields available. Each element of the
  28. * array is a basic property-list, including the type of field, the
  29. * label it is to be given in the form, callbacks for validation and
  30. * 'filtering', and other pertinent information.
  31. *
  32. * Field types are implemented as subclasses of the generic HTMLFormField
  33. * object, and typically implement at least getInputHTML, which generates
  34. * the HTML for the input field to be placed in the table.
  35. *
  36. * You can find extensive documentation on the www.mediawiki.org wiki:
  37. * - https://www.mediawiki.org/wiki/HTMLForm
  38. * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
  39. *
  40. * The constructor input is an associative array of $fieldname => $info,
  41. * where $info is an Associative Array with any of the following:
  42. *
  43. * 'class' -- the subclass of HTMLFormField that will be used
  44. * to create the object. *NOT* the CSS class!
  45. * 'type' -- roughly translates into the <select> type attribute.
  46. * if 'class' is not specified, this is used as a map
  47. * through HTMLForm::$typeMappings to get the class name.
  48. * 'default' -- default value when the form is displayed
  49. * 'nodata' -- if set (to any value, which casts to true), the data
  50. * for this field will not be loaded from the actual request. Instead,
  51. * always the default data is set as the value of this field.
  52. * 'id' -- HTML id attribute
  53. * 'cssclass' -- CSS class
  54. * 'csshelpclass' -- CSS class used to style help text
  55. * 'dir' -- Direction of the element.
  56. * 'options' -- associative array mapping raw text labels to values.
  57. * Some field types support multi-level arrays.
  58. * Overwrites 'options-message'.
  59. * 'options-messages' -- associative array mapping message keys to values.
  60. * Some field types support multi-level arrays.
  61. * Overwrites 'options' and 'options-message'.
  62. * 'options-message' -- message key or object to be parsed to extract the list of
  63. * options (like 'ipbreason-dropdown').
  64. * 'label-message' -- message key or object for a message to use as the label.
  65. * can be an array of msg key and then parameters to
  66. * the message.
  67. * 'label' -- alternatively, a raw text message. Overridden by
  68. * label-message
  69. * 'help' -- message text for a message to use as a help text.
  70. * 'help-message' -- message key or object for a message to use as a help text.
  71. * can be an array of msg key and then parameters to
  72. * the message.
  73. * Overwrites 'help-messages' and 'help'.
  74. * 'help-messages' -- array of message keys/objects. As above, each item can
  75. * be an array of msg key and then parameters.
  76. * Overwrites 'help'.
  77. * 'help-inline' -- Whether help text (defined using options above) will be shown
  78. * inline after the input field, rather than in a popup.
  79. * Defaults to true. Only used by OOUI form fields.
  80. * 'required' -- passed through to the object, indicating that it
  81. * is a required field.
  82. * 'size' -- the length of text fields
  83. * 'filter-callback' -- a function name to give you the chance to
  84. * massage the inputted value before it's processed.
  85. * @see HTMLFormField::filter()
  86. * 'validation-callback' -- a function name to give you the chance
  87. * to impose extra validation on the field input.
  88. * @see HTMLFormField::validate()
  89. * 'name' -- By default, the 'name' attribute of the input field
  90. * is "wp{$fieldname}". If you want a different name
  91. * (eg one without the "wp" prefix), specify it here and
  92. * it will be used without modification.
  93. * 'hide-if' -- expression given as an array stating when the field
  94. * should be hidden. The first array value has to be the
  95. * expression's logic operator. Supported expressions:
  96. * 'NOT'
  97. * [ 'NOT', array $expression ]
  98. * To hide a field if a given expression is not true.
  99. * '==='
  100. * [ '===', string $fieldName, string $value ]
  101. * To hide a field if another field identified by
  102. * $field has the value $value.
  103. * '!=='
  104. * [ '!==', string $fieldName, string $value ]
  105. * Same as [ 'NOT', [ '===', $fieldName, $value ]
  106. * 'OR', 'AND', 'NOR', 'NAND'
  107. * [ 'XXX', array $expression1, ..., array $expressionN ]
  108. * To hide a field if one or more (OR), all (AND),
  109. * neither (NOR) or not all (NAND) given expressions
  110. * are evaluated as true.
  111. * The expressions will be given to a JavaScript frontend
  112. * module which will continually update the field's
  113. * visibility.
  114. *
  115. * Since 1.20, you can chain mutators to ease the form generation:
  116. * @par Example:
  117. * @code
  118. * $form = new HTMLForm( $someFields );
  119. * $form->setMethod( 'get' )
  120. * ->setWrapperLegendMsg( 'message-key' )
  121. * ->prepareForm()
  122. * ->displayForm( '' );
  123. * @endcode
  124. * Note that you will have prepareForm and displayForm at the end. Other
  125. * methods call done after that would simply not be part of the form :(
  126. *
  127. * @todo Document 'section' / 'subsection' stuff
  128. */
  129. class HTMLForm extends ContextSource {
  130. // A mapping of 'type' inputs onto standard HTMLFormField subclasses
  131. public static $typeMappings = [
  132. 'api' => HTMLApiField::class,
  133. 'text' => HTMLTextField::class,
  134. 'textwithbutton' => HTMLTextFieldWithButton::class,
  135. 'textarea' => HTMLTextAreaField::class,
  136. 'select' => HTMLSelectField::class,
  137. 'combobox' => HTMLComboboxField::class,
  138. 'radio' => HTMLRadioField::class,
  139. 'multiselect' => HTMLMultiSelectField::class,
  140. 'limitselect' => HTMLSelectLimitField::class,
  141. 'check' => HTMLCheckField::class,
  142. 'toggle' => HTMLCheckField::class,
  143. 'int' => HTMLIntField::class,
  144. 'float' => HTMLFloatField::class,
  145. 'info' => HTMLInfoField::class,
  146. 'selectorother' => HTMLSelectOrOtherField::class,
  147. 'selectandother' => HTMLSelectAndOtherField::class,
  148. 'namespaceselect' => HTMLSelectNamespace::class,
  149. 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
  150. 'tagfilter' => HTMLTagFilter::class,
  151. 'sizefilter' => HTMLSizeFilterField::class,
  152. 'submit' => HTMLSubmitField::class,
  153. 'hidden' => HTMLHiddenField::class,
  154. 'edittools' => HTMLEditTools::class,
  155. 'checkmatrix' => HTMLCheckMatrix::class,
  156. 'cloner' => HTMLFormFieldCloner::class,
  157. 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
  158. 'language' => HTMLSelectLanguageField::class,
  159. 'date' => HTMLDateTimeField::class,
  160. 'time' => HTMLDateTimeField::class,
  161. 'datetime' => HTMLDateTimeField::class,
  162. 'expiry' => HTMLExpiryField::class,
  163. // HTMLTextField will output the correct type="" attribute automagically.
  164. // There are about four zillion other HTML5 input types, like range, but
  165. // we don't use those at the moment, so no point in adding all of them.
  166. 'email' => HTMLTextField::class,
  167. 'password' => HTMLTextField::class,
  168. 'url' => HTMLTextField::class,
  169. 'title' => HTMLTitleTextField::class,
  170. 'user' => HTMLUserTextField::class,
  171. 'usersmultiselect' => HTMLUsersMultiselectField::class,
  172. 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
  173. 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
  174. ];
  175. public $mFieldData;
  176. protected $mMessagePrefix;
  177. /** @var HTMLFormField[] */
  178. protected $mFlatFields = [];
  179. protected $mFieldTree = [];
  180. protected $mShowReset = false;
  181. protected $mShowSubmit = true;
  182. /** @var string[] */
  183. protected $mSubmitFlags = [ 'primary', 'progressive' ];
  184. protected $mShowCancel = false;
  185. protected $mCancelTarget;
  186. protected $mSubmitCallback;
  187. protected $mValidationErrorMessage;
  188. protected $mPre = '';
  189. protected $mHeader = '';
  190. protected $mFooter = '';
  191. protected $mSectionHeaders = [];
  192. protected $mSectionFooters = [];
  193. protected $mPost = '';
  194. protected $mId;
  195. protected $mName;
  196. protected $mTableId = '';
  197. protected $mSubmitID;
  198. protected $mSubmitName;
  199. protected $mSubmitText;
  200. protected $mSubmitTooltip;
  201. protected $mFormIdentifier;
  202. protected $mTitle;
  203. protected $mMethod = 'post';
  204. protected $mWasSubmitted = false;
  205. /**
  206. * Form action URL. false means we will use the URL to set Title
  207. * @since 1.19
  208. * @var bool|string
  209. */
  210. protected $mAction = false;
  211. /**
  212. * Whether the form can be collapsed
  213. * @since 1.34
  214. * @var bool
  215. */
  216. protected $mCollapsible = false;
  217. /**
  218. * Whether the form is collapsed by default
  219. * @since 1.34
  220. * @var bool
  221. */
  222. protected $mCollapsed = false;
  223. /**
  224. * Form attribute autocomplete. A typical value is "off". null does not set the attribute
  225. * @since 1.27
  226. * @var string|null
  227. */
  228. protected $mAutocomplete = null;
  229. protected $mUseMultipart = false;
  230. protected $mHiddenFields = [];
  231. /**
  232. * @var array[]
  233. * @phan-var array<array{name:string,value:string,label-message?:string,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool}>
  234. */
  235. protected $mButtons = [];
  236. protected $mWrapperLegend = false;
  237. protected $mWrapperAttributes = [];
  238. /**
  239. * Salt for the edit token.
  240. * @var string|array
  241. */
  242. protected $mTokenSalt = '';
  243. /**
  244. * If true, sections that contain both fields and subsections will
  245. * render their subsections before their fields.
  246. *
  247. * Subclasses may set this to false to render subsections after fields
  248. * instead.
  249. */
  250. protected $mSubSectionBeforeFields = true;
  251. /**
  252. * Format in which to display form. For viable options,
  253. * @see $availableDisplayFormats
  254. * @var string
  255. */
  256. protected $displayFormat = 'table';
  257. /**
  258. * Available formats in which to display the form
  259. * @var array
  260. */
  261. protected $availableDisplayFormats = [
  262. 'table',
  263. 'div',
  264. 'raw',
  265. 'inline',
  266. ];
  267. /**
  268. * Available formats in which to display the form
  269. * @var array
  270. */
  271. protected $availableSubclassDisplayFormats = [
  272. 'vform',
  273. 'ooui',
  274. ];
  275. /**
  276. * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
  277. *
  278. * @param string $displayFormat
  279. * @param mixed ...$arguments Additional arguments to pass to the constructor.
  280. * @return HTMLForm
  281. */
  282. public static function factory( $displayFormat, ...$arguments ) {
  283. switch ( $displayFormat ) {
  284. case 'vform':
  285. return new VFormHTMLForm( ...$arguments );
  286. case 'ooui':
  287. return new OOUIHTMLForm( ...$arguments );
  288. default:
  289. $form = new self( ...$arguments );
  290. $form->setDisplayFormat( $displayFormat );
  291. return $form;
  292. }
  293. }
  294. /**
  295. * Build a new HTMLForm from an array of field attributes
  296. *
  297. * @param array $descriptor Array of Field constructs, as described
  298. * in the class documentation
  299. * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
  300. * Obviates the need to call $form->setTitle()
  301. * @param string $messagePrefix A prefix to go in front of default messages
  302. */
  303. public function __construct( $descriptor, /*IContextSource*/ $context = null,
  304. $messagePrefix = ''
  305. ) {
  306. if ( $context instanceof IContextSource ) {
  307. $this->setContext( $context );
  308. $this->mTitle = false; // We don't need them to set a title
  309. $this->mMessagePrefix = $messagePrefix;
  310. } elseif ( $context === null && $messagePrefix !== '' ) {
  311. $this->mMessagePrefix = $messagePrefix;
  312. } elseif ( is_string( $context ) && $messagePrefix === '' ) {
  313. // B/C since 1.18
  314. // it's actually $messagePrefix
  315. $this->mMessagePrefix = $context;
  316. }
  317. // Evil hack for mobile :(
  318. if (
  319. !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
  320. && $this->displayFormat === 'table'
  321. ) {
  322. $this->displayFormat = 'div';
  323. }
  324. $this->addFields( $descriptor );
  325. }
  326. /**
  327. * Add fields to the form
  328. *
  329. * @since 1.34
  330. *
  331. * @param array $descriptor Array of Field constructs, as described
  332. * in the class documentation
  333. * @return HTMLForm
  334. */
  335. public function addFields( $descriptor ) {
  336. $loadedDescriptor = [];
  337. foreach ( $descriptor as $fieldname => $info ) {
  338. $section = $info['section'] ?? '';
  339. if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
  340. $this->mUseMultipart = true;
  341. }
  342. $field = static::loadInputFromParameters( $fieldname, $info, $this );
  343. $setSection =& $loadedDescriptor;
  344. if ( $section ) {
  345. foreach ( explode( '/', $section ) as $newName ) {
  346. if ( !isset( $setSection[$newName] ) ) {
  347. $setSection[$newName] = [];
  348. }
  349. $setSection =& $setSection[$newName];
  350. }
  351. }
  352. $setSection[$fieldname] = $field;
  353. $this->mFlatFields[$fieldname] = $field;
  354. }
  355. $this->mFieldTree = array_merge( $this->mFieldTree, $loadedDescriptor );
  356. return $this;
  357. }
  358. /**
  359. * @param string $fieldname
  360. * @return bool
  361. */
  362. public function hasField( $fieldname ) {
  363. return isset( $this->mFlatFields[$fieldname] );
  364. }
  365. /**
  366. * @param string $fieldname
  367. * @return HTMLFormField
  368. * @throws DomainException on invalid field name
  369. */
  370. public function getField( $fieldname ) {
  371. if ( !$this->hasField( $fieldname ) ) {
  372. throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
  373. }
  374. return $this->mFlatFields[$fieldname];
  375. }
  376. /**
  377. * Set format in which to display the form
  378. *
  379. * @param string $format The name of the format to use, must be one of
  380. * $this->availableDisplayFormats
  381. *
  382. * @throws MWException
  383. * @since 1.20
  384. * @return HTMLForm $this for chaining calls (since 1.20)
  385. */
  386. public function setDisplayFormat( $format ) {
  387. if (
  388. in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
  389. in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
  390. ) {
  391. throw new MWException( 'Cannot change display format after creation, ' .
  392. 'use HTMLForm::factory() instead' );
  393. }
  394. if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
  395. throw new MWException( 'Display format must be one of ' .
  396. print_r(
  397. array_merge(
  398. $this->availableDisplayFormats,
  399. $this->availableSubclassDisplayFormats
  400. ),
  401. true
  402. ) );
  403. }
  404. // Evil hack for mobile :(
  405. if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
  406. $format = 'div';
  407. }
  408. $this->displayFormat = $format;
  409. return $this;
  410. }
  411. /**
  412. * Getter for displayFormat
  413. * @since 1.20
  414. * @return string
  415. */
  416. public function getDisplayFormat() {
  417. return $this->displayFormat;
  418. }
  419. /**
  420. * Get the HTMLFormField subclass for this descriptor.
  421. *
  422. * The descriptor can be passed either 'class' which is the name of
  423. * a HTMLFormField subclass, or a shorter 'type' which is an alias.
  424. * This makes sure the 'class' is always set, and also is returned by
  425. * this function for ease.
  426. *
  427. * @since 1.23
  428. *
  429. * @param string $fieldname Name of the field
  430. * @param array &$descriptor Input Descriptor, as described
  431. * in the class documentation
  432. *
  433. * @throws MWException
  434. * @return string Name of a HTMLFormField subclass
  435. */
  436. public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
  437. if ( isset( $descriptor['class'] ) ) {
  438. $class = $descriptor['class'];
  439. } elseif ( isset( $descriptor['type'] ) ) {
  440. $class = static::$typeMappings[$descriptor['type']];
  441. $descriptor['class'] = $class;
  442. } else {
  443. $class = null;
  444. }
  445. if ( !$class ) {
  446. throw new MWException( "Descriptor with no class for $fieldname: "
  447. . print_r( $descriptor, true ) );
  448. }
  449. return $class;
  450. }
  451. /**
  452. * Initialise a new Object for the field
  453. *
  454. * @param string $fieldname Name of the field
  455. * @param array $descriptor Input Descriptor, as described
  456. * in the class documentation
  457. * @param HTMLForm|null $parent Parent instance of HTMLForm
  458. *
  459. * @throws MWException
  460. * @return HTMLFormField Instance of a subclass of HTMLFormField
  461. */
  462. public static function loadInputFromParameters( $fieldname, $descriptor,
  463. HTMLForm $parent = null
  464. ) {
  465. $class = static::getClassFromDescriptor( $fieldname, $descriptor );
  466. $descriptor['fieldname'] = $fieldname;
  467. if ( $parent ) {
  468. $descriptor['parent'] = $parent;
  469. }
  470. # @todo This will throw a fatal error whenever someone try to use
  471. # 'class' to feed a CSS class instead of 'cssclass'. Would be
  472. # great to avoid the fatal error and show a nice error.
  473. return new $class( $descriptor );
  474. }
  475. /**
  476. * Prepare form for submission.
  477. *
  478. * @warning When doing method chaining, that should be the very last
  479. * method call before displayForm().
  480. *
  481. * @throws MWException
  482. * @return HTMLForm $this for chaining calls (since 1.20)
  483. */
  484. public function prepareForm() {
  485. # Check if we have the info we need
  486. if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
  487. throw new MWException( 'You must call setTitle() on an HTMLForm' );
  488. }
  489. # Load data from the request.
  490. if (
  491. $this->mFormIdentifier === null ||
  492. $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
  493. ) {
  494. $this->loadData();
  495. } else {
  496. $this->mFieldData = [];
  497. }
  498. return $this;
  499. }
  500. /**
  501. * Try submitting, with edit token check first
  502. * @return Status|bool
  503. */
  504. public function tryAuthorizedSubmit() {
  505. $result = false;
  506. if ( $this->mFormIdentifier === null ) {
  507. $identOkay = true;
  508. } else {
  509. $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
  510. }
  511. $tokenOkay = false;
  512. if ( $this->getMethod() !== 'post' ) {
  513. $tokenOkay = true; // no session check needed
  514. } elseif ( $this->getRequest()->wasPosted() ) {
  515. $editToken = $this->getRequest()->getVal( 'wpEditToken' );
  516. if ( $this->getUser()->isLoggedIn() || $editToken !== null ) {
  517. // Session tokens for logged-out users have no security value.
  518. // However, if the user gave one, check it in order to give a nice
  519. // "session expired" error instead of "permission denied" or such.
  520. $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
  521. } else {
  522. $tokenOkay = true;
  523. }
  524. }
  525. if ( $tokenOkay && $identOkay ) {
  526. $this->mWasSubmitted = true;
  527. $result = $this->trySubmit();
  528. }
  529. return $result;
  530. }
  531. /**
  532. * The here's-one-I-made-earlier option: do the submission if
  533. * posted, or display the form with or without funky validation
  534. * errors
  535. * @return bool|Status Whether submission was successful.
  536. */
  537. public function show() {
  538. $this->prepareForm();
  539. $result = $this->tryAuthorizedSubmit();
  540. if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
  541. return $result;
  542. }
  543. $this->displayForm( $result );
  544. return false;
  545. }
  546. /**
  547. * Same as self::show with the difference, that the form will be
  548. * added to the output, no matter, if the validation was good or not.
  549. * @return bool|Status Whether submission was successful.
  550. */
  551. public function showAlways() {
  552. $this->prepareForm();
  553. $result = $this->tryAuthorizedSubmit();
  554. $this->displayForm( $result );
  555. return $result;
  556. }
  557. /**
  558. * Validate all the fields, and call the submission callback
  559. * function if everything is kosher.
  560. * @throws MWException
  561. * @return bool|string|array|Status
  562. * - Bool true or a good Status object indicates success,
  563. * - Bool false indicates no submission was attempted,
  564. * - Anything else indicates failure. The value may be a fatal Status
  565. * object, an HTML string, or an array of arrays (message keys and
  566. * params) or strings (message keys)
  567. */
  568. public function trySubmit() {
  569. $valid = true;
  570. $hoistedErrors = Status::newGood();
  571. if ( $this->mValidationErrorMessage ) {
  572. foreach ( $this->mValidationErrorMessage as $error ) {
  573. $hoistedErrors->fatal( ...$error );
  574. }
  575. } else {
  576. $hoistedErrors->fatal( 'htmlform-invalid-input' );
  577. }
  578. $this->mWasSubmitted = true;
  579. # Check for cancelled submission
  580. foreach ( $this->mFlatFields as $fieldname => $field ) {
  581. if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
  582. continue;
  583. }
  584. if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
  585. $this->mWasSubmitted = false;
  586. return false;
  587. }
  588. }
  589. # Check for validation
  590. foreach ( $this->mFlatFields as $fieldname => $field ) {
  591. if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
  592. continue;
  593. }
  594. if ( $field->isHidden( $this->mFieldData ) ) {
  595. continue;
  596. }
  597. $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
  598. if ( $res !== true ) {
  599. $valid = false;
  600. if ( $res !== false && !$field->canDisplayErrors() ) {
  601. if ( is_string( $res ) ) {
  602. $hoistedErrors->fatal( 'rawmessage', $res );
  603. } else {
  604. $hoistedErrors->fatal( $res );
  605. }
  606. }
  607. }
  608. }
  609. if ( !$valid ) {
  610. return $hoistedErrors;
  611. }
  612. $callback = $this->mSubmitCallback;
  613. if ( !is_callable( $callback ) ) {
  614. throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
  615. 'setSubmitCallback() to set one.' );
  616. }
  617. $data = $this->filterDataForSubmit( $this->mFieldData );
  618. $res = call_user_func( $callback, $data, $this );
  619. if ( $res === false ) {
  620. $this->mWasSubmitted = false;
  621. }
  622. return $res;
  623. }
  624. /**
  625. * Test whether the form was considered to have been submitted or not, i.e.
  626. * whether the last call to tryAuthorizedSubmit or trySubmit returned
  627. * non-false.
  628. *
  629. * This will return false until HTMLForm::tryAuthorizedSubmit or
  630. * HTMLForm::trySubmit is called.
  631. *
  632. * @since 1.23
  633. * @return bool
  634. */
  635. public function wasSubmitted() {
  636. return $this->mWasSubmitted;
  637. }
  638. /**
  639. * Set a callback to a function to do something with the form
  640. * once it's been successfully validated.
  641. *
  642. * @param callable $cb The function will be passed the output from
  643. * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
  644. * return as documented for HTMLForm::trySubmit
  645. *
  646. * @return HTMLForm $this for chaining calls (since 1.20)
  647. */
  648. public function setSubmitCallback( $cb ) {
  649. $this->mSubmitCallback = $cb;
  650. return $this;
  651. }
  652. /**
  653. * Set a message to display on a validation error.
  654. *
  655. * @param array $msg Array of valid inputs to wfMessage()
  656. * (so each entry must itself be an array of arguments)
  657. *
  658. * @return HTMLForm $this for chaining calls (since 1.20)
  659. */
  660. public function setValidationErrorMessage( $msg ) {
  661. $this->mValidationErrorMessage = $msg;
  662. return $this;
  663. }
  664. /**
  665. * Set the introductory message, overwriting any existing message.
  666. *
  667. * @param string $msg Complete text of message to display
  668. *
  669. * @return HTMLForm $this for chaining calls (since 1.20)
  670. */
  671. public function setIntro( $msg ) {
  672. $this->setPreText( $msg );
  673. return $this;
  674. }
  675. /**
  676. * Set the introductory message HTML, overwriting any existing message.
  677. * @since 1.19
  678. *
  679. * @param string $msg Complete HTML of message to display
  680. *
  681. * @return HTMLForm $this for chaining calls (since 1.20)
  682. */
  683. public function setPreText( $msg ) {
  684. $this->mPre = $msg;
  685. return $this;
  686. }
  687. /**
  688. * Add HTML to introductory message.
  689. *
  690. * @param string $msg Complete HTML of message to display
  691. *
  692. * @return HTMLForm $this for chaining calls (since 1.20)
  693. */
  694. public function addPreText( $msg ) {
  695. $this->mPre .= $msg;
  696. return $this;
  697. }
  698. /**
  699. * Get the introductory message HTML.
  700. *
  701. * @since 1.32
  702. *
  703. * @return string
  704. */
  705. public function getPreText() {
  706. return $this->mPre;
  707. }
  708. /**
  709. * Add HTML to the header, inside the form.
  710. *
  711. * @param string $msg Additional HTML to display in header
  712. * @param string|null $section The section to add the header to
  713. *
  714. * @return HTMLForm $this for chaining calls (since 1.20)
  715. */
  716. public function addHeaderText( $msg, $section = null ) {
  717. if ( $section === null ) {
  718. $this->mHeader .= $msg;
  719. } else {
  720. if ( !isset( $this->mSectionHeaders[$section] ) ) {
  721. $this->mSectionHeaders[$section] = '';
  722. }
  723. $this->mSectionHeaders[$section] .= $msg;
  724. }
  725. return $this;
  726. }
  727. /**
  728. * Set header text, inside the form.
  729. * @since 1.19
  730. *
  731. * @param string $msg Complete HTML of header to display
  732. * @param string|null $section The section to add the header to
  733. *
  734. * @return HTMLForm $this for chaining calls (since 1.20)
  735. */
  736. public function setHeaderText( $msg, $section = null ) {
  737. if ( $section === null ) {
  738. $this->mHeader = $msg;
  739. } else {
  740. $this->mSectionHeaders[$section] = $msg;
  741. }
  742. return $this;
  743. }
  744. /**
  745. * Get header text.
  746. *
  747. * @param string|null $section The section to get the header text for
  748. * @since 1.26
  749. * @return string HTML
  750. */
  751. public function getHeaderText( $section = null ) {
  752. if ( $section === null ) {
  753. return $this->mHeader;
  754. } else {
  755. return $this->mSectionHeaders[$section] ?? '';
  756. }
  757. }
  758. /**
  759. * Add footer text, inside the form.
  760. *
  761. * @param string $msg Complete text of message to display
  762. * @param string|null $section The section to add the footer text to
  763. *
  764. * @return HTMLForm $this for chaining calls (since 1.20)
  765. */
  766. public function addFooterText( $msg, $section = null ) {
  767. if ( $section === null ) {
  768. $this->mFooter .= $msg;
  769. } else {
  770. if ( !isset( $this->mSectionFooters[$section] ) ) {
  771. $this->mSectionFooters[$section] = '';
  772. }
  773. $this->mSectionFooters[$section] .= $msg;
  774. }
  775. return $this;
  776. }
  777. /**
  778. * Set footer text, inside the form.
  779. * @since 1.19
  780. *
  781. * @param string $msg Complete text of message to display
  782. * @param string|null $section The section to add the footer text to
  783. *
  784. * @return HTMLForm $this for chaining calls (since 1.20)
  785. */
  786. public function setFooterText( $msg, $section = null ) {
  787. if ( $section === null ) {
  788. $this->mFooter = $msg;
  789. } else {
  790. $this->mSectionFooters[$section] = $msg;
  791. }
  792. return $this;
  793. }
  794. /**
  795. * Get footer text.
  796. *
  797. * @param string|null $section The section to get the footer text for
  798. * @since 1.26
  799. * @return string
  800. */
  801. public function getFooterText( $section = null ) {
  802. if ( $section === null ) {
  803. return $this->mFooter;
  804. } else {
  805. return $this->mSectionFooters[$section] ?? '';
  806. }
  807. }
  808. /**
  809. * Add text to the end of the display.
  810. *
  811. * @param string $msg Complete text of message to display
  812. *
  813. * @return HTMLForm $this for chaining calls (since 1.20)
  814. */
  815. public function addPostText( $msg ) {
  816. $this->mPost .= $msg;
  817. return $this;
  818. }
  819. /**
  820. * Set text at the end of the display.
  821. *
  822. * @param string $msg Complete text of message to display
  823. *
  824. * @return HTMLForm $this for chaining calls (since 1.20)
  825. */
  826. public function setPostText( $msg ) {
  827. $this->mPost = $msg;
  828. return $this;
  829. }
  830. /**
  831. * Add a hidden field to the output
  832. *
  833. * @param string $name Field name. This will be used exactly as entered
  834. * @param string $value Field value
  835. * @param array $attribs
  836. *
  837. * @return HTMLForm $this for chaining calls (since 1.20)
  838. */
  839. public function addHiddenField( $name, $value, array $attribs = [] ) {
  840. $attribs += [ 'name' => $name ];
  841. $this->mHiddenFields[] = [ $value, $attribs ];
  842. return $this;
  843. }
  844. /**
  845. * Add an array of hidden fields to the output
  846. *
  847. * @since 1.22
  848. *
  849. * @param array $fields Associative array of fields to add;
  850. * mapping names to their values
  851. *
  852. * @return HTMLForm $this for chaining calls
  853. */
  854. public function addHiddenFields( array $fields ) {
  855. foreach ( $fields as $name => $value ) {
  856. $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
  857. }
  858. return $this;
  859. }
  860. /**
  861. * Add a button to the form
  862. *
  863. * @since 1.27 takes an array as shown. Earlier versions accepted
  864. * 'name', 'value', 'id', and 'attribs' as separate parameters in that
  865. * order.
  866. * @note Custom labels ('label', 'label-message', 'label-raw') are not
  867. * supported for IE6 and IE7 due to bugs in those browsers. If detected,
  868. * they will be served buttons using 'value' as the button label.
  869. * @param array $data Data to define the button:
  870. * - name: (string) Button name.
  871. * - value: (string) Button value.
  872. * - label-message: (string, optional) Button label message key to use
  873. * instead of 'value'. Overrides 'label' and 'label-raw'.
  874. * - label: (string, optional) Button label text to use instead of
  875. * 'value'. Overrides 'label-raw'.
  876. * - label-raw: (string, optional) Button label HTML to use instead of
  877. * 'value'.
  878. * - id: (string, optional) DOM id for the button.
  879. * - attribs: (array, optional) Additional HTML attributes.
  880. * - flags: (string|string[], optional) OOUI flags.
  881. * - framed: (boolean=true, optional) OOUI framed attribute.
  882. * @codingStandardsIgnoreStart
  883. * @phan-param array{name:string,value:string,label-message?:string,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool} $data
  884. * @codingStandardsIgnoreEnd
  885. * @return HTMLForm $this for chaining calls (since 1.20)
  886. */
  887. public function addButton( $data ) {
  888. if ( !is_array( $data ) ) {
  889. $args = func_get_args();
  890. if ( count( $args ) < 2 || count( $args ) > 4 ) {
  891. throw new InvalidArgumentException(
  892. 'Incorrect number of arguments for deprecated calling style'
  893. );
  894. }
  895. $data = [
  896. 'name' => $args[0],
  897. 'value' => $args[1],
  898. 'id' => $args[2] ?? null,
  899. 'attribs' => $args[3] ?? null,
  900. ];
  901. } else {
  902. if ( !isset( $data['name'] ) ) {
  903. throw new InvalidArgumentException( 'A name is required' );
  904. }
  905. if ( !isset( $data['value'] ) ) {
  906. throw new InvalidArgumentException( 'A value is required' );
  907. }
  908. }
  909. $this->mButtons[] = $data + [
  910. 'id' => null,
  911. 'attribs' => null,
  912. 'flags' => null,
  913. 'framed' => true,
  914. ];
  915. return $this;
  916. }
  917. /**
  918. * Set the salt for the edit token.
  919. *
  920. * Only useful when the method is "post".
  921. *
  922. * @since 1.24
  923. * @param string|array $salt Salt to use
  924. * @return HTMLForm $this For chaining calls
  925. */
  926. public function setTokenSalt( $salt ) {
  927. $this->mTokenSalt = $salt;
  928. return $this;
  929. }
  930. /**
  931. * Display the form (sending to the context's OutputPage object), with an
  932. * appropriate error message or stack of messages, and any validation errors, etc.
  933. *
  934. * @warning You should call prepareForm() before calling this function.
  935. * Moreover, when doing method chaining this should be the very last method
  936. * call just after prepareForm().
  937. *
  938. * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
  939. *
  940. * @return void Nothing, should be last call
  941. */
  942. public function displayForm( $submitResult ) {
  943. $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
  944. }
  945. /**
  946. * Returns the raw HTML generated by the form
  947. *
  948. * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
  949. *
  950. * @return string HTML
  951. * @return-taint escaped
  952. */
  953. public function getHTML( $submitResult ) {
  954. # For good measure (it is the default)
  955. $this->getOutput()->preventClickjacking();
  956. $this->getOutput()->addModules( 'mediawiki.htmlform' );
  957. $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
  958. $html = ''
  959. . $this->getErrorsOrWarnings( $submitResult, 'error' )
  960. . $this->getErrorsOrWarnings( $submitResult, 'warning' )
  961. . $this->getHeaderText()
  962. . $this->getBody()
  963. . $this->getHiddenFields()
  964. . $this->getButtons()
  965. . $this->getFooterText();
  966. $html = $this->wrapForm( $html );
  967. return '' . $this->mPre . $html . $this->mPost;
  968. }
  969. /**
  970. * Enable collapsible mode, and set whether the form is collapsed by default.
  971. *
  972. * @since 1.34
  973. * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
  974. * @return HTMLForm $this for chaining calls
  975. */
  976. public function setCollapsibleOptions( $collapsedByDefault = false ) {
  977. $this->mCollapsible = true;
  978. $this->mCollapsed = $collapsedByDefault;
  979. return $this;
  980. }
  981. /**
  982. * Get HTML attributes for the `<form>` tag.
  983. * @return array
  984. */
  985. protected function getFormAttributes() {
  986. # Use multipart/form-data
  987. $encType = $this->mUseMultipart
  988. ? 'multipart/form-data'
  989. : 'application/x-www-form-urlencoded';
  990. # Attributes
  991. $attribs = [
  992. 'class' => 'mw-htmlform',
  993. 'action' => $this->getAction(),
  994. 'method' => $this->getMethod(),
  995. 'enctype' => $encType,
  996. ];
  997. if ( $this->mId ) {
  998. $attribs['id'] = $this->mId;
  999. }
  1000. if ( is_string( $this->mAutocomplete ) ) {
  1001. $attribs['autocomplete'] = $this->mAutocomplete;
  1002. }
  1003. if ( $this->mName ) {
  1004. $attribs['name'] = $this->mName;
  1005. }
  1006. if ( $this->needsJSForHtml5FormValidation() ) {
  1007. $attribs['novalidate'] = true;
  1008. }
  1009. return $attribs;
  1010. }
  1011. /**
  1012. * Wrap the form innards in an actual "<form>" element
  1013. *
  1014. * @param string $html HTML contents to wrap.
  1015. *
  1016. * @return string Wrapped HTML.
  1017. */
  1018. public function wrapForm( $html ) {
  1019. # Include a <fieldset> wrapper for style, if requested.
  1020. if ( $this->mWrapperLegend !== false ) {
  1021. $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
  1022. $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
  1023. }
  1024. return Html::rawElement(
  1025. 'form',
  1026. $this->getFormAttributes(),
  1027. $html
  1028. );
  1029. }
  1030. /**
  1031. * Get the hidden fields that should go inside the form.
  1032. * @return string HTML.
  1033. */
  1034. public function getHiddenFields() {
  1035. $html = '';
  1036. if ( $this->mFormIdentifier !== null ) {
  1037. $html .= Html::hidden(
  1038. 'wpFormIdentifier',
  1039. $this->mFormIdentifier
  1040. ) . "\n";
  1041. }
  1042. if ( $this->getMethod() === 'post' ) {
  1043. $html .= Html::hidden(
  1044. 'wpEditToken',
  1045. $this->getUser()->getEditToken( $this->mTokenSalt ),
  1046. [ 'id' => 'wpEditToken' ]
  1047. ) . "\n";
  1048. $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
  1049. }
  1050. $articlePath = $this->getConfig()->get( 'ArticlePath' );
  1051. if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
  1052. $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
  1053. }
  1054. foreach ( $this->mHiddenFields as $data ) {
  1055. list( $value, $attribs ) = $data;
  1056. $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
  1057. }
  1058. return $html;
  1059. }
  1060. /**
  1061. * Get the submit and (potentially) reset buttons.
  1062. * @return string HTML.
  1063. */
  1064. public function getButtons() {
  1065. $buttons = '';
  1066. $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
  1067. if ( $this->mShowSubmit ) {
  1068. $attribs = [];
  1069. if ( isset( $this->mSubmitID ) ) {
  1070. $attribs['id'] = $this->mSubmitID;
  1071. }
  1072. if ( isset( $this->mSubmitName ) ) {
  1073. $attribs['name'] = $this->mSubmitName;
  1074. }
  1075. if ( isset( $this->mSubmitTooltip ) ) {
  1076. $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
  1077. }
  1078. $attribs['class'] = [ 'mw-htmlform-submit' ];
  1079. if ( $useMediaWikiUIEverywhere ) {
  1080. foreach ( $this->mSubmitFlags as $flag ) {
  1081. $attribs['class'][] = 'mw-ui-' . $flag;
  1082. }
  1083. $attribs['class'][] = 'mw-ui-button';
  1084. }
  1085. $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
  1086. }
  1087. if ( $this->mShowReset ) {
  1088. $buttons .= Html::element(
  1089. 'input',
  1090. [
  1091. 'type' => 'reset',
  1092. 'value' => $this->msg( 'htmlform-reset' )->text(),
  1093. 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
  1094. ]
  1095. ) . "\n";
  1096. }
  1097. if ( $this->mShowCancel ) {
  1098. $target = $this->mCancelTarget ?: Title::newMainPage();
  1099. if ( $target instanceof Title ) {
  1100. $target = $target->getLocalURL();
  1101. }
  1102. $buttons .= Html::element(
  1103. 'a',
  1104. [
  1105. 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
  1106. 'href' => $target,
  1107. ],
  1108. $this->msg( 'cancel' )->text()
  1109. ) . "\n";
  1110. }
  1111. // IE<8 has bugs with <button>, so we'll need to avoid them.
  1112. $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
  1113. foreach ( $this->mButtons as $button ) {
  1114. $attrs = [
  1115. 'type' => 'submit',
  1116. 'name' => $button['name'],
  1117. 'value' => $button['value']
  1118. ];
  1119. if ( isset( $button['label-message'] ) ) {
  1120. $label = $this->getMessage( $button['label-message'] )->parse();
  1121. } elseif ( isset( $button['label'] ) ) {
  1122. $label = htmlspecialchars( $button['label'] );
  1123. } elseif ( isset( $button['label-raw'] ) ) {
  1124. $label = $button['label-raw'];
  1125. } else {
  1126. $label = htmlspecialchars( $button['value'] );
  1127. }
  1128. if ( $button['attribs'] ) {
  1129. $attrs += $button['attribs'];
  1130. }
  1131. if ( isset( $button['id'] ) ) {
  1132. $attrs['id'] = $button['id'];
  1133. }
  1134. if ( $useMediaWikiUIEverywhere ) {
  1135. $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
  1136. $attrs['class'][] = 'mw-ui-button';
  1137. }
  1138. if ( $isBadIE ) {
  1139. $buttons .= Html::element( 'input', $attrs ) . "\n";
  1140. } else {
  1141. $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
  1142. }
  1143. }
  1144. if ( !$buttons ) {
  1145. return '';
  1146. }
  1147. return Html::rawElement( 'span',
  1148. [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
  1149. }
  1150. /**
  1151. * Get the whole body of the form.
  1152. * @return string
  1153. */
  1154. public function getBody() {
  1155. return $this->displaySection( $this->mFieldTree, $this->mTableId );
  1156. }
  1157. /**
  1158. * Returns a formatted list of errors or warnings from the given elements.
  1159. *
  1160. * @param string|array|Status $elements The set of errors/warnings to process.
  1161. * @param string $elementsType Should warnings or errors be returned. This is meant
  1162. * for Status objects, all other valid types are always considered as errors.
  1163. * @return string
  1164. */
  1165. public function getErrorsOrWarnings( $elements, $elementsType ) {
  1166. if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
  1167. throw new DomainException( $elementsType . ' is not a valid type.' );
  1168. }
  1169. $elementstr = false;
  1170. if ( $elements instanceof Status ) {
  1171. list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
  1172. $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
  1173. if ( $status->isGood() ) {
  1174. $elementstr = '';
  1175. } else {
  1176. $elementstr = $this->getOutput()->parseAsInterface(
  1177. $status->getWikiText()
  1178. );
  1179. }
  1180. } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
  1181. $elementstr = $this->formatErrors( $elements );
  1182. } elseif ( $elementsType === 'error' ) {
  1183. $elementstr = $elements;
  1184. }
  1185. return $elementstr
  1186. ? Html::rawElement( 'div', [ 'class' => $elementsType . 'box' ], $elementstr )
  1187. : '';
  1188. }
  1189. /**
  1190. * Format a stack of error messages into a single HTML string
  1191. *
  1192. * @param array $errors Array of message keys/values
  1193. *
  1194. * @return string HTML, a "<ul>" list of errors
  1195. */
  1196. public function formatErrors( $errors ) {
  1197. $errorstr = '';
  1198. foreach ( $errors as $error ) {
  1199. $errorstr .= Html::rawElement(
  1200. 'li',
  1201. [],
  1202. $this->getMessage( $error )->parse()
  1203. );
  1204. }
  1205. $errorstr = Html::rawElement( 'ul', [], $errorstr );
  1206. return $errorstr;
  1207. }
  1208. /**
  1209. * Set the text for the submit button
  1210. *
  1211. * @param string $t Plaintext
  1212. *
  1213. * @return HTMLForm $this for chaining calls (since 1.20)
  1214. */
  1215. public function setSubmitText( $t ) {
  1216. $this->mSubmitText = $t;
  1217. return $this;
  1218. }
  1219. /**
  1220. * Identify that the submit button in the form has a destructive action
  1221. * @since 1.24
  1222. *
  1223. * @return HTMLForm $this for chaining calls (since 1.28)
  1224. */
  1225. public function setSubmitDestructive() {
  1226. $this->mSubmitFlags = [ 'destructive', 'primary' ];
  1227. return $this;
  1228. }
  1229. /**
  1230. * Set the text for the submit button to a message
  1231. * @since 1.19
  1232. *
  1233. * @param string|Message $msg Message key or Message object
  1234. *
  1235. * @return HTMLForm $this for chaining calls (since 1.20)
  1236. */
  1237. public function setSubmitTextMsg( $msg ) {
  1238. if ( !$msg instanceof Message ) {
  1239. $msg = $this->msg( $msg );
  1240. }
  1241. $this->setSubmitText( $msg->text() );
  1242. return $this;
  1243. }
  1244. /**
  1245. * Get the text for the submit button, either customised or a default.
  1246. * @return string
  1247. */
  1248. public function getSubmitText() {
  1249. return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
  1250. }
  1251. /**
  1252. * @param string $name Submit button name
  1253. *
  1254. * @return HTMLForm $this for chaining calls (since 1.20)
  1255. */
  1256. public function setSubmitName( $name ) {
  1257. $this->mSubmitName = $name;
  1258. return $this;
  1259. }
  1260. /**
  1261. * @param string $name Tooltip for the submit button
  1262. *
  1263. * @return HTMLForm $this for chaining calls (since 1.20)
  1264. */
  1265. public function setSubmitTooltip( $name ) {
  1266. $this->mSubmitTooltip = $name;
  1267. return $this;
  1268. }
  1269. /**
  1270. * Set the id for the submit button.
  1271. *
  1272. * @param string $t
  1273. *
  1274. * @todo FIXME: Integrity of $t is *not* validated
  1275. * @return HTMLForm $this for chaining calls (since 1.20)
  1276. */
  1277. public function setSubmitID( $t ) {
  1278. $this->mSubmitID = $t;
  1279. return $this;
  1280. }
  1281. /**
  1282. * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
  1283. * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
  1284. * two purposes:
  1285. *
  1286. * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
  1287. * was submitted, and not attempt to validate the other ones.
  1288. * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
  1289. * HTMLForm to distinguish between the initial page view and a form submission with all
  1290. * checkboxes or select options unchecked.
  1291. *
  1292. * @since 1.28
  1293. * @param string $ident
  1294. * @return $this
  1295. */
  1296. public function setFormIdentifier( $ident ) {
  1297. $this->mFormIdentifier = $ident;
  1298. return $this;
  1299. }
  1300. /**
  1301. * Stop a default submit button being shown for this form. This implies that an
  1302. * alternate submit method must be provided manually.
  1303. *
  1304. * @since 1.22
  1305. *
  1306. * @param bool $suppressSubmit Set to false to re-enable the button again
  1307. *
  1308. * @return HTMLForm $this for chaining calls
  1309. */
  1310. public function suppressDefaultSubmit( $suppressSubmit = true ) {
  1311. $this->mShowSubmit = !$suppressSubmit;
  1312. return $this;
  1313. }
  1314. /**
  1315. * Show a cancel button (or prevent it). The button is not shown by default.
  1316. * @param bool $show
  1317. * @return HTMLForm $this for chaining calls
  1318. * @since 1.27
  1319. */
  1320. public function showCancel( $show = true ) {
  1321. $this->mShowCancel = $show;
  1322. return $this;
  1323. }
  1324. /**
  1325. * Sets the target where the user is redirected to after clicking cancel.
  1326. * @param Title|string $target Target as a Title object or an URL
  1327. * @return HTMLForm $this for chaining calls
  1328. * @since 1.27
  1329. */
  1330. public function setCancelTarget( $target ) {
  1331. $this->mCancelTarget = $target;
  1332. return $this;
  1333. }
  1334. /**
  1335. * Set the id of the \<table\> or outermost \<div\> element.
  1336. *
  1337. * @since 1.22
  1338. *
  1339. * @param string $id New value of the id attribute, or "" to remove
  1340. *
  1341. * @return HTMLForm $this for chaining calls
  1342. */
  1343. public function setTableId( $id ) {
  1344. $this->mTableId = $id;
  1345. return $this;
  1346. }
  1347. /**
  1348. * @param string $id DOM id for the form
  1349. *
  1350. * @return HTMLForm $this for chaining calls (since 1.20)
  1351. */
  1352. public function setId( $id ) {
  1353. $this->mId = $id;
  1354. return $this;
  1355. }
  1356. /**
  1357. * @param string $name 'name' attribute for the form
  1358. * @return HTMLForm $this for chaining calls
  1359. */
  1360. public function setName( $name ) {
  1361. $this->mName = $name;
  1362. return $this;
  1363. }
  1364. /**
  1365. * Prompt the whole form to be wrapped in a "<fieldset>", with
  1366. * this text as its "<legend>" element.
  1367. *
  1368. * @param string|bool $legend If false, no wrapper or legend will be displayed.
  1369. * If true, a wrapper will be displayed, but no legend.
  1370. * If a string, a wrapper will be displayed with that string as a legend.
  1371. * The string will be escaped before being output (this doesn't support HTML).
  1372. *
  1373. * @return HTMLForm $this for chaining calls (since 1.20)
  1374. */
  1375. public function setWrapperLegend( $legend ) {
  1376. $this->mWrapperLegend = $legend;
  1377. return $this;
  1378. }
  1379. /**
  1380. * For internal use only. Use is discouraged, and should only be used where
  1381. * support for gadgets/user scripts is warranted.
  1382. * @param array $attributes
  1383. * @internal
  1384. * @return HTMLForm $this for chaining calls
  1385. */
  1386. public function setWrapperAttributes( $attributes ) {
  1387. $this->mWrapperAttributes = $attributes;
  1388. return $this;
  1389. }
  1390. /**
  1391. * Prompt the whole form to be wrapped in a "<fieldset>", with
  1392. * this message as its "<legend>" element.
  1393. * @since 1.19
  1394. *
  1395. * @param string|Message $msg Message key or Message object
  1396. *
  1397. * @return HTMLForm $this for chaining calls (since 1.20)
  1398. */
  1399. public function setWrapperLegendMsg( $msg ) {
  1400. if ( !$msg instanceof Message ) {
  1401. $msg = $this->msg( $msg );
  1402. }
  1403. $this->setWrapperLegend( $msg->text() );
  1404. return $this;
  1405. }
  1406. /**
  1407. * Set the prefix for various default messages
  1408. * @todo Currently only used for the "<fieldset>" legend on forms
  1409. * with multiple sections; should be used elsewhere?
  1410. *
  1411. * @param string $p
  1412. *
  1413. * @return HTMLForm $this for chaining calls (since 1.20)
  1414. */
  1415. public function setMessagePrefix( $p ) {
  1416. $this->mMessagePrefix = $p;
  1417. return $this;
  1418. }
  1419. /**
  1420. * Set the title for form submission
  1421. *
  1422. * @param Title $t Title of page the form is on/should be posted to
  1423. *
  1424. * @return HTMLForm $this for chaining calls (since 1.20)
  1425. */
  1426. public function setTitle( $t ) {
  1427. $this->mTitle = $t;
  1428. return $this;
  1429. }
  1430. /**
  1431. * Get the title
  1432. * @return Title
  1433. */
  1434. public function getTitle() {
  1435. return $this->mTitle === false
  1436. ? $this->getContext()->getTitle()
  1437. : $this->mTitle;
  1438. }
  1439. /**
  1440. * Set the method used to submit the form
  1441. *
  1442. * @param string $method
  1443. *
  1444. * @return HTMLForm $this for chaining calls (since 1.20)
  1445. */
  1446. public function setMethod( $method = 'post' ) {
  1447. $this->mMethod = strtolower( $method );
  1448. return $this;
  1449. }
  1450. /**
  1451. * @return string Always lowercase
  1452. */
  1453. public function getMethod() {
  1454. return $this->mMethod;
  1455. }
  1456. /**
  1457. * Wraps the given $section into an user-visible fieldset.
  1458. *
  1459. * @param string $legend Legend text for the fieldset
  1460. * @param string $section The section content in plain Html
  1461. * @param array $attributes Additional attributes for the fieldset
  1462. * @param bool $isRoot Section is at the root of the tree
  1463. * @return string The fieldset's Html
  1464. */
  1465. protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
  1466. return Xml::fieldset( $legend, $section, $attributes ) . "\n";
  1467. }
  1468. /**
  1469. * @todo Document
  1470. *
  1471. * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
  1472. * objects).
  1473. * @param string $sectionName ID attribute of the "<table>" tag for this
  1474. * section, ignored if empty.
  1475. * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
  1476. * each subsection, ignored if empty.
  1477. * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
  1478. * @throws LogicException When called on uninitialized field data, e.g. When
  1479. * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
  1480. * first.
  1481. *
  1482. * @return string
  1483. */
  1484. public function displaySection( $fields,
  1485. $sectionName = '',
  1486. $fieldsetIDPrefix = '',
  1487. &$hasUserVisibleFields = false
  1488. ) {
  1489. if ( $this->mFieldData === null ) {
  1490. throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
  1491. . 'You probably called displayForm() without calling prepareForm() first.' );
  1492. }
  1493. $displayFormat = $this->getDisplayFormat();
  1494. $html = [];
  1495. $subsectionHtml = '';
  1496. $hasLabel = false;
  1497. // Conveniently, PHP method names are case-insensitive.
  1498. // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
  1499. $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
  1500. foreach ( $fields as $key => $value ) {
  1501. if ( $value instanceof HTMLFormField ) {
  1502. $v = array_key_exists( $key, $this->mFieldData )
  1503. ? $this->mFieldData[$key]
  1504. : $value->getDefault();
  1505. $retval = $value->$getFieldHtmlMethod( $v );
  1506. // check, if the form field should be added to
  1507. // the output.
  1508. if ( $value->hasVisibleOutput() ) {
  1509. $html[] = $retval;
  1510. $labelValue = trim( $value->getLabel() );
  1511. if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
  1512. $hasLabel = true;
  1513. }
  1514. $hasUserVisibleFields = true;
  1515. }
  1516. } elseif ( is_array( $value ) ) {
  1517. $subsectionHasVisibleFields = false;
  1518. $section =
  1519. $this->displaySection( $value,
  1520. "mw-htmlform-$key",
  1521. "$fieldsetIDPrefix$key-",
  1522. $subsectionHasVisibleFields );
  1523. $legend = null;
  1524. if ( $subsectionHasVisibleFields === true ) {
  1525. // Display the section with various niceties.
  1526. $hasUserVisibleFields = true;
  1527. $legend = $this->getLegend( $key );
  1528. $section = $this->getHeaderText( $key ) .
  1529. $section .
  1530. $this->getFooterText( $key );
  1531. $attributes = [];
  1532. if ( $fieldsetIDPrefix ) {
  1533. $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
  1534. }
  1535. $subsectionHtml .= $this->wrapFieldSetSection(
  1536. $legend, $section, $attributes, $fields === $this->mFieldTree
  1537. );
  1538. } else {
  1539. // Just return the inputs, nothing fancy.
  1540. $subsectionHtml .= $section;
  1541. }
  1542. }
  1543. }
  1544. $html = $this->formatSection( $html, $sectionName, $hasLabel );
  1545. if ( $subsectionHtml ) {
  1546. if ( $this->mSubSectionBeforeFields ) {
  1547. return $subsectionHtml . "\n" . $html;
  1548. } else {
  1549. return $html . "\n" . $subsectionHtml;
  1550. }
  1551. } else {
  1552. return $html;
  1553. }
  1554. }
  1555. /**
  1556. * Put a form section together from the individual fields' HTML, merging it and wrapping.
  1557. * @param array $fieldsHtml
  1558. * @param string $sectionName
  1559. * @param bool $anyFieldHasLabel
  1560. * @return string HTML
  1561. */
  1562. protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
  1563. if ( !$fieldsHtml ) {
  1564. // Do not generate any wrappers for empty sections. Sections may be empty if they only have
  1565. // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
  1566. return '';
  1567. }
  1568. $displayFormat = $this->getDisplayFormat();
  1569. $html = implode( '', $fieldsHtml );
  1570. if ( $displayFormat === 'raw' ) {
  1571. return $html;
  1572. }
  1573. $classes = [];
  1574. if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
  1575. $classes[] = 'mw-htmlform-nolabel';
  1576. }
  1577. $attribs = [
  1578. 'class' => implode( ' ', $classes ),
  1579. ];
  1580. if ( $sectionName ) {
  1581. $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
  1582. }
  1583. if ( $displayFormat === 'table' ) {
  1584. return Html::rawElement( 'table',
  1585. $attribs,
  1586. Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
  1587. } elseif ( $displayFormat === 'inline' ) {
  1588. return Html::rawElement( 'span', $attribs, "\n$html\n" );
  1589. } else {
  1590. return Html::rawElement( 'div', $attribs, "\n$html\n" );
  1591. }
  1592. }
  1593. /**
  1594. * Construct the form fields from the Descriptor array
  1595. */
  1596. public function loadData() {
  1597. $fieldData = [];
  1598. foreach ( $this->mFlatFields as $fieldname => $field ) {
  1599. $request = $this->getRequest();
  1600. if ( $field->skipLoadData( $request ) ) {
  1601. continue;
  1602. } elseif ( !empty( $field->mParams['disabled'] ) ) {
  1603. $fieldData[$fieldname] = $field->getDefault();
  1604. } else {
  1605. $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
  1606. }
  1607. }
  1608. # Filter data.
  1609. foreach ( $fieldData as $name => &$value ) {
  1610. $field = $this->mFlatFields[$name];
  1611. $value = $field->filter( $value, $this->mFlatFields );
  1612. }
  1613. $this->mFieldData = $fieldData;
  1614. }
  1615. /**
  1616. * Stop a reset button being shown for this form
  1617. *
  1618. * @param bool $suppressReset Set to false to re-enable the button again
  1619. *
  1620. * @return HTMLForm $this for chaining calls (since 1.20)
  1621. */
  1622. public function suppressReset( $suppressReset = true ) {
  1623. $this->mShowReset = !$suppressReset;
  1624. return $this;
  1625. }
  1626. /**
  1627. * Overload this if you want to apply special filtration routines
  1628. * to the form as a whole, after it's submitted but before it's
  1629. * processed.
  1630. *
  1631. * @param array $data
  1632. *
  1633. * @return array
  1634. */
  1635. public function filterDataForSubmit( $data ) {
  1636. return $data;
  1637. }
  1638. /**
  1639. * Get a string to go in the "<legend>" of a section fieldset.
  1640. * Override this if you want something more complicated.
  1641. *
  1642. * @param string $key
  1643. *
  1644. * @return string Plain text (not HTML-escaped)
  1645. */
  1646. public function getLegend( $key ) {
  1647. return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
  1648. }
  1649. /**
  1650. * Set the value for the action attribute of the form.
  1651. * When set to false (which is the default state), the set title is used.
  1652. *
  1653. * @since 1.19
  1654. *
  1655. * @param string|bool $action
  1656. *
  1657. * @return HTMLForm $this for chaining calls (since 1.20)
  1658. */
  1659. public function setAction( $action ) {
  1660. $this->mAction = $action;
  1661. return $this;
  1662. }
  1663. /**
  1664. * Get the value for the action attribute of the form.
  1665. *
  1666. * @since 1.22
  1667. *
  1668. * @return string
  1669. */
  1670. public function getAction() {
  1671. // If an action is alredy provided, return it
  1672. if ( $this->mAction !== false ) {
  1673. return $this->mAction;
  1674. }
  1675. $articlePath = $this->getConfig()->get( 'ArticlePath' );
  1676. // Check whether we are in GET mode and the ArticlePath contains a "?"
  1677. // meaning that getLocalURL() would return something like "index.php?title=...".
  1678. // As browser remove the query string before submitting GET forms,
  1679. // it means that the title would be lost. In such case use wfScript() instead
  1680. // and put title in an hidden field (see getHiddenFields()).
  1681. if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
  1682. return wfScript();
  1683. }
  1684. return $this->getTitle()->getLocalURL();
  1685. }
  1686. /**
  1687. * Set the value for the autocomplete attribute of the form. A typical value is "off".
  1688. * When set to null (which is the default state), the attribute get not set.
  1689. *
  1690. * @since 1.27
  1691. *
  1692. * @param string|null $autocomplete
  1693. *
  1694. * @return HTMLForm $this for chaining calls
  1695. */
  1696. public function setAutocomplete( $autocomplete ) {
  1697. $this->mAutocomplete = $autocomplete;
  1698. return $this;
  1699. }
  1700. /**
  1701. * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
  1702. * name + parameters array) into a Message.
  1703. * @param mixed $value
  1704. * @return Message
  1705. */
  1706. protected function getMessage( $value ) {
  1707. return Message::newFromSpecifier( $value )->setContext( $this );
  1708. }
  1709. /**
  1710. * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
  1711. * for the client-side HTML5 form validation to work correctly. If this function returns true, a
  1712. * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
  1713. * agent has JavaScript support, in htmlform.js.
  1714. *
  1715. * @return bool
  1716. * @since 1.29
  1717. */
  1718. public function needsJSForHtml5FormValidation() {
  1719. foreach ( $this->mFlatFields as $fieldname => $field ) {
  1720. if ( $field->needsJSForHtml5FormValidation() ) {
  1721. return true;
  1722. }
  1723. }
  1724. return false;
  1725. }
  1726. }