Debian Codegraph @

includes/htmlform/fields/HTMLFormFieldCloner.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\HTMLForm\Field;
4
5 use InvalidArgumentException;
6 use MediaWiki\Html\Html;
7 use MediaWiki\HTMLForm\HTMLForm;
8 use MediaWiki\HTMLForm\HTMLFormField;
9 use MediaWiki\Parser\Sanitizer;
10 use MediaWiki\Request\DerivativeRequest;
11
12 /**
13 * A container for HTMLFormFields that allows for multiple copies of the set of
14 * fields to be displayed to and entered by the user.
15 *
16 * Recognized parameters, besides the general ones, include:
17 * fields - HTMLFormField descriptors for the subfields this cloner manages.
18 * The format is just like for the HTMLForm. A field with key 'delete' is
19 * special: it must have type = submit and will serve to delete the group
20 * of fields.
21 * required - If specified, at least one group of fields must be submitted.
22 * format - HTMLForm display format to use when displaying the subfields:
23 * 'table', 'div', or 'raw'. This is ignored when using OOUI.
24 * row-legend - If non-empty, each group of subfields will be enclosed in a
25 * fieldset. The value is the name of a message key to use as the legend.
26 * create-button-message - Message to use as the text of the button to
27 * add an additional group of fields.
28 * delete-button-message - Message to use as the text of automatically-
29 * generated 'delete' button. Ignored if 'delete' is included in 'fields'.
30 *
31 * In the generated HTML, the subfields will be named along the lines of
32 * "clonerName[index][fieldname]", with ids "clonerId--index--fieldid". 'index'
33 * may be a number or an arbitrary string, and may likely change when the page
34 * is resubmitted. Cloners may be nested, resulting in field names along the
35 * lines of "cloner1Name[index1][cloner2Name][index2][fieldname]" and
36 * corresponding ids.
37 *
38 * Use of cloner may result in submissions of the page that are not submissions
39 * of the HTMLForm, when non-JavaScript clients use the create or remove buttons.
40 *
41 * The result is an array, with values being arrays mapping subfield names to
42 * their values. On non-HTMLForm-submission page loads, there may also be
43 * additional (string) keys present with other types of values.
44 *
45 * @since 1.23
46 * @stable to extend
47 */
48 class HTMLFormFieldCloner extends HTMLFormField {
49 /** @var int */
50 private static $counter = 0;
51
52 /**
53 * @var string String uniquely identifying this cloner instance and
54 * unlikely to exist otherwise in the generated HTML, while still being
55 * valid as part of an HTML id.
56 */
57 protected $uniqueId;
58
59 /** @var array<string, HTMLFormField[]> */
60 protected $mFields = [];
61
62 private bool $nonJsUpdate = false;
63
64 /**
65 * @stable to call
66 * @inheritDoc
67 */
68 public function __construct( $params ) {
69 $this->uniqueId = $this->getClassName() . ++self::$counter . 'x';
70 parent::__construct( $params );
71
72 if ( empty( $this->mParams['fields'] ) || !is_array( $this->mParams['fields'] ) ) {
73 throw new InvalidArgumentException( 'HTMLFormFieldCloner called without any fields' );
74 }
75
76 // Make sure the delete button, if explicitly specified, is sensible
77 if ( isset( $this->mParams['fields']['delete'] ) ) {
78 $class = 'mw-htmlform-cloner-delete-button';
79 $info = $this->mParams['fields']['delete'] + [
80 'formnovalidate' => true,
81 'cssclass' => $class
82 ];
83 unset( $info['name'], $info['class'] );
84
85 if ( !isset( $info['type'] ) || $info['type'] !== 'submit' ) {
86 throw new InvalidArgumentException(
87 'HTMLFormFieldCloner delete field, if specified, must be of type "submit"'
88 );
89 }
90
91 if ( !in_array( $class, explode( ' ', $info['cssclass'] ) ) ) {
92 $info['cssclass'] .= " $class";
93 }
94
95 $this->mParams['fields']['delete'] = $info;
96 }
97 }
98
99 /**
100 * @param string $key Array key under which these fields should be named
101 * @return HTMLFormField[]
102 */
103 protected function getFieldsForKey( $key ) {
104 if ( !isset( $this->mFields[$key] ) ) {
105 $this->mFields[$key] = $this->createFieldsForKey( $key );
106 }
107 return $this->mFields[$key];
108 }
109
110 /**
111 * Create the HTMLFormFields that go inside this element, using the
112 * specified key.
113 *
114 * @param string $key Array key under which these fields should be named
115 * @return HTMLFormField[]
116 */
117 protected function createFieldsForKey( $key ) {
118 $fields = [];
119 foreach ( $this->mParams['fields'] as $fieldname => $info ) {
120 $name = "{$this->mName}[$key][$fieldname]";
121 if ( isset( $info['name'] ) ) {
122 $info['name'] = "{$this->mName}[$key][{$info['name']}]";
123 } else {
124 $info['name'] = $name;
125 }
126 if ( isset( $info['id'] ) ) {
127 $info['id'] = Sanitizer::escapeIdForAttribute( "{$this->mID}--$key--{$info['id']}" );
128 } else {
129 $info['id'] = Sanitizer::escapeIdForAttribute( "{$this->mID}--$key--$fieldname" );
130 }
131 // Copy the hide-if and disable-if rules to "child" fields, so that the JavaScript code handling them
132 // (resources/src/mediawiki.htmlform/cond-state.js) doesn't have to handle nested fields.
133 if ( $this->mCondState ) {
134 foreach ( [ 'hide', 'disable' ] as $type ) {
135 if ( !isset( $this->mCondState[$type] ) ) {
136 continue;
137 }
138 $param = $type . '-if';
139 if ( isset( $info[$param] ) ) {
140 // Hide or disable child field if either its rules say so, or parent's rules say so.
141 $info[$param] = [ 'OR', $info[$param], $this->mCondState[$type] ];
142 } else {
143 // Hide or disable child field if parent's rules say so.
144 $info[$param] = $this->mCondState[$type];
145 }
146 }
147 }
148 $cloner = $this;
149 $info['cloner'] = &$cloner;
150 $info['cloner-key'] = $key;
151 $field = HTMLForm::loadInputFromParameters( $fieldname, $info, $this->mParent );
152 $fields[$fieldname] = $field;
153 }
154 return $fields;
155 }
156
157 /**
158 * Re-key the specified values array to match the names applied by
159 * createFieldsForKey().
160 *
161 * @param string $key Array key under which these fields should be named
162 * @param array $values Values array from the request
163 * @return array
164 */
165 protected function rekeyValuesArray( $key, $values ) {
166 $data = [];
167 foreach ( $values as $fieldname => $value ) {
168 $name = "{$this->mName}[$key][$fieldname]";
169 $data[$name] = $value;
170 }
171 return $data;
172 }
173
174 /**
175 * @param string $name
176 * @return string[]
177 */
178 protected function parseFieldPath( $name ) {
179 $fieldKeys = [];
180 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $name, $m ) ) {
181 array_unshift( $fieldKeys, $m[2] );
182 $name = $m[1];
183 }
184 array_unshift( $fieldKeys, $name );
185 return $fieldKeys;
186 }
187
188 /**
189 * Find the nearest field to a field in this cloner matched the given name,
190 * walk through the chain of cloners.
191 *
192 * @param HTMLFormField $field
193 * @param string $find
194 * @return HTMLFormField|null
195 */
196 public function findNearestField( $field, $find ) {
197 $findPath = $this->parseFieldPath( $find );
198 // Access to fields as child or in other group is not allowed.
199 // Further support for a more complicated path may conduct here.
200 if ( count( $findPath ) > 1 ) {
201 return null;
202 }
203 if ( !isset( $this->mParams['fields'][$find] ) ) {
204 $cloner = $this->mParams['cloner'] ?? null;
205 if ( $cloner instanceof self ) {
206 return $cloner->findNearestField( $this, $find );
207 }
208 return null;
209 }
210 $fields = $this->getFieldsForKey( $field->mParams['cloner-key'] );
211 return $fields[$find];
212 }
213
214 /**
215 * @param HTMLFormField $field
216 * @return string[]
217 */
218 protected function getFieldPath( $field ) {
219 $path = [ $this->mParams['fieldname'], $field->mParams['cloner-key'] ];
220 $cloner = $this->mParams['cloner'] ?? null;
221 if ( $cloner instanceof self ) {
222 $path = array_merge( $cloner->getFieldPath( $this ), $path );
223 }
224 return $path;
225 }
226
227 /**
228 * Extract field data for a given field that belongs to this cloner.
229 *
230 * @param HTMLFormField $field
231 * @param mixed[] $alldata
232 * @return mixed
233 */
234 public function extractFieldData( $field, $alldata ) {
235 if (
236 // Is an empty array when first rendering a form with a formIdentifier.
237 count( $alldata ) === 0 ||
238 // This field is either part of the cloner template or is newly created
239 // for non-JS users, which is not tracked in the form's field data (T391882).
240 $field->mParams['cloner-key'] === $this->uniqueId
241 ) {
242 return $field->getDefault();
243 }
244
245 foreach ( $this->getFieldPath( $field ) as $key ) {
246 $alldata = $alldata[$key];
247 }
248 return $alldata[$field->mParams['fieldname']];
249 }
250
251 protected function needsLabel() {
252 return false;
253 }
254
255 public function loadDataFromRequest( $request ) {
256 // It's possible that this might be posted with no fields. Detect that
257 // by looking for an edit token.
258 if ( !$request->getCheck( 'wpEditToken' ) && $request->getArray( $this->mName ) === null ) {
259 return $this->getDefault();
260 }
261
262 $values = $request->getArray( $this->mName ) ?? [];
263
264 $ret = [];
265 foreach ( $values as $key => $value ) {
266 if ( $key === 'create' || isset( $value['delete'] ) ) {
267 $this->nonJsUpdate = true;
268 continue;
269 }
270
271 // Add back in $request->getValues() so things that look for e.g.
272 // wpEditToken don't fail.
273 $data = $this->rekeyValuesArray( $key, $value ) + $request->getValues();
274
275 $fields = $this->getFieldsForKey( $key );
276 $subrequest = new DerivativeRequest( $request, $data, $request->wasPosted() );
277 $row = [];
278 foreach ( $fields as $fieldname => $field ) {
279 if ( $field->skipLoadData( $subrequest ) ) {
280 continue;
281 }
282 if ( !empty( $field->mParams['disabled'] ) ) {
283 $row[$fieldname] = $field->getDefault();
284 } else {
285 $row[$fieldname] = $field->loadDataFromRequest( $subrequest );
286 }
287 }
288 $ret[] = $row;
289 }
290
291 if ( isset( $values['create'] ) ) {
292 // Non-JS client clicked the "create" button.
293 $fields = $this->getFieldsForKey( $this->uniqueId );
294 $row = [];
295 foreach ( $fields as $fieldname => $field ) {
296 if ( !empty( $field->mParams['nodata'] ) ) {
297 continue;
298 }
299 $row[$fieldname] = $field->getDefault();
300 }
301 $ret[] = $row;
302 }
303
304 return $ret;
305 }
306
307 /** @inheritDoc */
308 public function filter( $values, $alldata ) {
309 // Mimic the later stage of HTMLForm::loadFieldData() as if for normal fields.
310 foreach ( $values as $key => &$fieldsValue ) {
311 $fields = $this->getFieldsForKey( $key );
312 foreach ( $fieldsValue as $fieldname => &$value ) {
313 // Reset to default for fields that are supposed to be disabled.
314 if ( $fields[$fieldname]->isDisabled( $alldata ) ) {
315 $value = $fields[$fieldname]->getDefault();
316 }
317
318 // Apply field-specific filters.
319 $value = $fields[$fieldname]->filter( $value, $alldata );
320 }
321 }
322
323 // Apply the filter defined by the 'filter-callback' option at the end.
324 return parent::filter( $values, $alldata );
325 }
326
327 /** @inheritDoc */
328 public function getDefault() {
329 $ret = parent::getDefault();
330
331 // Some existing use cases in SecurePoll use an empty string as the default value.
332 // TODO: Throw an exception in future versions.
333 if ( $ret !== null && !is_array( $ret ) ) {
334 $type = gettype( $ret );
335 wfDeprecated( __CLASS__ . " with non-array default ($type given)", '1.46' );
336 }
337
338 // The default is one entry with all subfields at their defaults.
339 if ( $ret === null || !is_array( $ret ) ) {
340 $fields = $this->getFieldsForKey( $this->uniqueId );
341 $row = [];
342 foreach ( $fields as $fieldname => $field ) {
343 if ( !empty( $field->mParams['nodata'] ) ) {
344 continue;
345 }
346 $row[$fieldname] = $field->getDefault();
347 }
348 $ret = [ $row ];
349 }
350
351 return $ret;
352 }
353
354 /**
355 * @inheritDoc
356 * @phan-param array[] $values
357 */
358 public function cancelSubmit( $values, $alldata ) {
359 if ( $this->nonJsUpdate ) {
360 return true;
361 }
362
363 foreach ( $values as $key => $value ) {
364 $fields = $this->getFieldsForKey( $key );
365 foreach ( $fields as $fieldname => $field ) {
366 if ( !array_key_exists( $fieldname, $value ) ) {
367 continue;
368 }
369 if ( $field->cancelSubmit( $value[$fieldname], $alldata ) ) {
370 return true;
371 }
372 }
373 }
374
375 return parent::cancelSubmit( $values, $alldata );
376 }
377
378 /**
379 * @inheritDoc
380 * @phan-param array[] $values
381 */
382 public function validate( $values, $alldata ) {
383 if ( isset( $this->mParams['required'] )
384 && $this->mParams['required'] !== false
385 && !$values
386 ) {
387 return $this->msg( 'htmlform-cloner-required' );
388 }
389
390 if ( $this->nonJsUpdate ) {
391 // The submission was a non-JS create/delete click, so fail
392 // validation in case cancelSubmit() somehow didn't already handle
393 // it.
394 return false;
395 }
396
397 foreach ( $values as $key => $value ) {
398 $fields = $this->getFieldsForKey( $key );
399 foreach ( $fields as $fieldname => $field ) {
400 if ( !array_key_exists( $fieldname, $value ) || $field->isHidden( $alldata ) ) {
401 continue;
402 }
403 $ok = $field->validate( $value[$fieldname], $alldata );
404 if ( $ok !== true ) {
405 return false;
406 }
407 }
408 }
409
410 return parent::validate( $values, $alldata );
411 }
412
413 /**
414 * Get the input HTML for the specified key.
415 *
416 * @param string $key Array key under which the fields should be named
417 * @param array $values
418 * @return string
419 */
420 protected function getInputHTMLForKey( $key, array $values ) {
421 $displayFormat = $this->mParams['format'] ?? $this->mParent->getDisplayFormat();
422
423 // Conveniently, PHP method names are case-insensitive.
424 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
425
426 $html = '';
427 $hidden = '';
428 $hasLabel = false;
429
430 $fields = $this->getFieldsForKey( $key );
431 foreach ( $fields as $fieldname => $field ) {
432 $v = array_key_exists( $fieldname, $values )
433 ? $values[$fieldname]
434 : $field->getDefault();
435
436 if ( $field instanceof HTMLHiddenField ) {
437 // HTMLHiddenField doesn't generate its own HTML
438 [ $name, $value, $params ] = $field->getHiddenFieldData( $v );
439 $hidden .= Html::hidden( $name, $value, $params ) . "\n";
440 } else {
441 $html .= $field->$getFieldHtmlMethod( $v );
442
443 $labelValue = trim( $field->getLabel() );
444 if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
445 $hasLabel = true;
446 }
447 }
448 }
449
450 if ( !isset( $fields['delete'] ) ) {
451 $field = $this->getDeleteButtonHtml( $key );
452
453 if ( $displayFormat === 'table' ) {
454 $html .= $field->$getFieldHtmlMethod( $field->getDefault() );
455 } else {
456 $html .= $field->getInputHTML( $field->getDefault() );
457 }
458 }
459
460 if ( $displayFormat !== 'raw' ) {
461 $classes = [ 'mw-htmlform-cloner-row' ];
462
463 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
464 $classes[] = 'mw-htmlform-nolabel';
465 }
466
467 $attribs = [ 'class' => $classes ];
468
469 if ( $displayFormat === 'table' ) {
470 $html = Html::rawElement( 'table',
471 $attribs,
472 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
473 } else {
474 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
475 }
476 }
477
478 $html .= $hidden;
479
480 if ( !empty( $this->mParams['row-legend'] ) ) {
481 $legend = $this->msg( $this->mParams['row-legend'] )->text();
482 $legend = $legend ? Html::element( 'legend', [], $legend ) : '';
483 $html = Html::rawElement(
484 'fieldset',
485 [],
486 $legend . $html
487 );
488 }
489
490 return $html;
491 }
492
493 /**
494 * @param string $key Array key indicating to which field the delete button belongs
495 * @return HTMLFormField
496 */
497 protected function getDeleteButtonHtml( $key ): HTMLFormField {
498 $name = "{$this->mName}[$key][delete]";
499 $label = $this->mParams['delete-button-message'] ?? 'htmlform-cloner-delete';
500 $field = HTMLForm::loadInputFromParameters( $name, [
501 'type' => 'submit',
502 'formnovalidate' => true,
503 'name' => $name,
504 'id' => Sanitizer::escapeIdForAttribute( "{$this->mID}--$key--delete" ),
505 'cssclass' => 'mw-htmlform-cloner-delete-button',
506 'default' => $this->getMessage( $label )->text(),
507 'disabled' => $this->mParams['disabled'] ?? false,
508 ], $this->mParent );
509 return $field;
510 }
511
512 protected function getCreateButtonHtml(): HTMLFormField {
513 $name = "{$this->mName}[create]";
514 $label = $this->mParams['create-button-message'] ?? 'htmlform-cloner-create';
515 return HTMLForm::loadInputFromParameters( $name, [
516 'type' => 'submit',
517 'formnovalidate' => true,
518 'name' => $name,
519 'id' => Sanitizer::escapeIdForAttribute( "{$this->mID}--create" ),
520 'cssclass' => 'mw-htmlform-cloner-create-button',
521 'default' => $this->getMessage( $label )->text(),
522 'disabled' => $this->mParams['disabled'] ?? false,
523 ], $this->mParent );
524 }
525
526 public function getInputHTML( $values ) {
527 $html = '';
528
529 foreach ( (array)$values as $key => $value ) {
530 $html .= Html::rawElement( 'li', [ 'class' => 'mw-htmlform-cloner-li' ],
531 $this->getInputHTMLForKey( $key, $value )
532 );
533 }
534
535 $template = $this->getInputHTMLForKey( $this->uniqueId, [] );
536 $html = Html::rawElement( 'ul', [
537 'id' => "mw-htmlform-cloner-list-{$this->mID}",
538 'class' => 'mw-htmlform-cloner-ul',
539 'data-template' => $template,
540 'data-unique-id' => $this->uniqueId,
541 ], $html );
542
543 $field = $this->getCreateButtonHtml();
544 $html .= $field->getInputHTML( $field->getDefault() );
545
546 return $html;
547 }
548
549 /**
550 * Get the input OOUI HTML for the specified key.
551 *
552 * @param string $key Array key under which the fields should be named
553 * @param array $values
554 * @return string
555 */
556 protected function getInputOOUIForKey( $key, array $values ) {
557 $html = '';
558 $hidden = '';
559
560 $fields = $this->getFieldsForKey( $key );
561 foreach ( $fields as $fieldname => $field ) {
562 $v = array_key_exists( $fieldname, $values )
563 ? $values[$fieldname]
564 : $field->getDefault();
565
566 if ( $field instanceof HTMLHiddenField ) {
567 // HTMLHiddenField doesn't generate its own HTML
568 [ $name, $value, $params ] = $field->getHiddenFieldData( $v );
569 $hidden .= Html::hidden( $name, $value, $params ) . "\n";
570 } else {
571 $html .= $field->getOOUI( $v );
572 }
573 }
574
575 if ( !isset( $fields['delete'] ) ) {
576 $field = $this->getDeleteButtonHtml( $key );
577 $fieldHtml = $field->getInputOOUI( $field->getDefault() );
578 $fieldHtml->setInfusable( true );
579
580 $html .= $fieldHtml;
581 }
582
583 $html = Html::rawElement( 'div', [ 'class' => 'mw-htmlform-cloner-row' ], "\n$html\n" );
584
585 $html .= $hidden;
586
587 if ( !empty( $this->mParams['row-legend'] ) ) {
588 $legend = $this->msg( $this->mParams['row-legend'] )->text();
589 $legend = $legend ? Html::element( 'legend', [], $legend ) : '';
590 $html = Html::rawElement(
591 'fieldset',
592 [],
593 $legend . $html
594 );
595 }
596
597 return $html;
598 }
599
600 public function getInputOOUI( $values ) {
601 $html = '';
602
603 foreach ( (array)$values as $key => $value ) {
604 $html .= Html::rawElement( 'li', [ 'class' => 'mw-htmlform-cloner-li' ],
605 $this->getInputOOUIForKey( $key, $value )
606 );
607 }
608
609 $template = $this->getInputOOUIForKey( $this->uniqueId, [] );
610 $html = Html::rawElement( 'ul', [
611 'id' => "mw-htmlform-cloner-list-{$this->mID}",
612 'class' => 'mw-htmlform-cloner-ul',
613 'data-template' => $template,
614 'data-unique-id' => $this->uniqueId,
615 ], $html );
616
617 $field = $this->getCreateButtonHtml();
618 $fieldHtml = $field->getInputOOUI( $field->getDefault() );
619 $fieldHtml->setInfusable( true );
620
621 $html .= $fieldHtml;
622
623 return $html;
624 }
625 }
626
627 /** @deprecated class alias since 1.42 */
628 class_alias( HTMLFormFieldCloner::class, 'HTMLFormFieldCloner' );