abb50d09183c726f8a198ca46a0dda117a66b4a8
[lhc/web/wiklou.git] / includes / htmlform / fields / HTMLFormFieldCloner.php
1 <?php
2
3 /**
4 * A container for HTMLFormFields that allows for multiple copies of the set of
5 * fields to be displayed to and entered by the user.
6 *
7 * Recognized parameters, besides the general ones, include:
8 * fields - HTMLFormField descriptors for the subfields this cloner manages.
9 * The format is just like for the HTMLForm. A field with key 'delete' is
10 * special: it must have type = submit and will serve to delete the group
11 * of fields.
12 * required - If specified, at least one group of fields must be submitted.
13 * format - HTMLForm display format to use when displaying the subfields:
14 * 'table', 'div', or 'raw'.
15 * row-legend - If non-empty, each group of subfields will be enclosed in a
16 * fieldset. The value is the name of a message key to use as the legend.
17 * create-button-message - Message to use as the text of the button to
18 * add an additional group of fields.
19 * delete-button-message - Message to use as the text of automatically-
20 * generated 'delete' button. Ignored if 'delete' is included in 'fields'.
21 *
22 * In the generated HTML, the subfields will be named along the lines of
23 * "clonerName[index][fieldname]", with ids "clonerId--index--fieldid". 'index'
24 * may be a number or an arbitrary string, and may likely change when the page
25 * is resubmitted. Cloners may be nested, resulting in field names along the
26 * lines of "cloner1Name[index1][cloner2Name][index2][fieldname]" and
27 * corresponding ids.
28 *
29 * Use of cloner may result in submissions of the page that are not submissions
30 * of the HTMLForm, when non-JavaScript clients use the create or remove buttons.
31 *
32 * The result is an array, with values being arrays mapping subfield names to
33 * their values. On non-HTMLForm-submission page loads, there may also be
34 * additional (string) keys present with other types of values.
35 *
36 * @since 1.23
37 */
38 class HTMLFormFieldCloner extends HTMLFormField {
39 private static $counter = 0;
40
41 /**
42 * @var string String uniquely identifying this cloner instance and
43 * unlikely to exist otherwise in the generated HTML, while still being
44 * valid as part of an HTML id.
45 */
46 protected $uniqueId;
47
48 public function __construct( $params ) {
49 $this->uniqueId = get_class( $this ) . ++self::$counter . 'x';
50 parent::__construct( $params );
51
52 if ( empty( $this->mParams['fields'] ) || !is_array( $this->mParams['fields'] ) ) {
53 throw new MWException( 'HTMLFormFieldCloner called without any fields' );
54 }
55
56 // Make sure the delete button, if explicitly specified, is sane
57 if ( isset( $this->mParams['fields']['delete'] ) ) {
58 $class = 'mw-htmlform-cloner-delete-button';
59 $info = $this->mParams['fields']['delete'] + [
60 'cssclass' => $class
61 ];
62 unset( $info['name'], $info['class'] );
63
64 if ( !isset( $info['type'] ) || $info['type'] !== 'submit' ) {
65 throw new MWException(
66 'HTMLFormFieldCloner delete field, if specified, must be of type "submit"'
67 );
68 }
69
70 if ( !in_array( $class, explode( ' ', $info['cssclass'] ) ) ) {
71 $info['cssclass'] .= " $class";
72 }
73
74 $this->mParams['fields']['delete'] = $info;
75 }
76 }
77
78 /**
79 * Create the HTMLFormFields that go inside this element, using the
80 * specified key.
81 *
82 * @param string $key Array key under which these fields should be named
83 * @return HTMLFormField[]
84 */
85 protected function createFieldsForKey( $key ) {
86 $fields = [];
87 foreach ( $this->mParams['fields'] as $fieldname => $info ) {
88 $name = "{$this->mName}[$key][$fieldname]";
89 if ( isset( $info['name'] ) ) {
90 $info['name'] = "{$this->mName}[$key][{$info['name']}]";
91 } else {
92 $info['name'] = $name;
93 }
94 if ( isset( $info['id'] ) ) {
95 $info['id'] = Sanitizer::escapeId( "{$this->mID}--$key--{$info['id']}" );
96 } else {
97 $info['id'] = Sanitizer::escapeId( "{$this->mID}--$key--$fieldname" );
98 }
99 // Copy the hide-if rules to "child" fields, so that the JavaScript code handling them
100 // (resources/src/mediawiki/htmlform/hide-if.js) doesn't have to handle nested fields.
101 if ( $this->mHideIf ) {
102 if ( isset( $info['hide-if'] ) ) {
103 // Hide child field if either its rules say it's hidden, or parent's rules say it's hidden
104 $info['hide-if'] = [ 'OR', $info['hide-if'], $this->mHideIf ];
105 } else {
106 // Hide child field if parent's rules say it's hidden
107 $info['hide-if'] = $this->mHideIf;
108 }
109 }
110 $field = HTMLForm::loadInputFromParameters( $name, $info, $this->mParent );
111 $fields[$fieldname] = $field;
112 }
113 return $fields;
114 }
115
116 /**
117 * Re-key the specified values array to match the names applied by
118 * createFieldsForKey().
119 *
120 * @param string $key Array key under which these fields should be named
121 * @param array $values Values array from the request
122 * @return array
123 */
124 protected function rekeyValuesArray( $key, $values ) {
125 $data = [];
126 foreach ( $values as $fieldname => $value ) {
127 $name = "{$this->mName}[$key][$fieldname]";
128 $data[$name] = $value;
129 }
130 return $data;
131 }
132
133 protected function needsLabel() {
134 return false;
135 }
136
137 public function loadDataFromRequest( $request ) {
138 // It's possible that this might be posted with no fields. Detect that
139 // by looking for an edit token.
140 if ( !$request->getCheck( 'wpEditToken' ) && $request->getArray( $this->mName ) === null ) {
141 return $this->getDefault();
142 }
143
144 $values = $request->getArray( $this->mName );
145 if ( $values === null ) {
146 $values = [];
147 }
148
149 $ret = [];
150 foreach ( $values as $key => $value ) {
151 if ( $key === 'create' || isset( $value['delete'] ) ) {
152 $ret['nonjs'] = 1;
153 continue;
154 }
155
156 // Add back in $request->getValues() so things that look for e.g.
157 // wpEditToken don't fail.
158 $data = $this->rekeyValuesArray( $key, $value ) + $request->getValues();
159
160 $fields = $this->createFieldsForKey( $key );
161 $subrequest = new DerivativeRequest( $request, $data, $request->wasPosted() );
162 $row = [];
163 foreach ( $fields as $fieldname => $field ) {
164 if ( $field->skipLoadData( $subrequest ) ) {
165 continue;
166 } elseif ( !empty( $field->mParams['disabled'] ) ) {
167 $row[$fieldname] = $field->getDefault();
168 } else {
169 $row[$fieldname] = $field->loadDataFromRequest( $subrequest );
170 }
171 }
172 $ret[] = $row;
173 }
174
175 if ( isset( $values['create'] ) ) {
176 // Non-JS client clicked the "create" button.
177 $fields = $this->createFieldsForKey( $this->uniqueId );
178 $row = [];
179 foreach ( $fields as $fieldname => $field ) {
180 if ( !empty( $field->mParams['nodata'] ) ) {
181 continue;
182 } else {
183 $row[$fieldname] = $field->getDefault();
184 }
185 }
186 $ret[] = $row;
187 }
188
189 return $ret;
190 }
191
192 public function getDefault() {
193 $ret = parent::getDefault();
194
195 // The default default is one entry with all subfields at their
196 // defaults.
197 if ( $ret === null ) {
198 $fields = $this->createFieldsForKey( $this->uniqueId );
199 $row = [];
200 foreach ( $fields as $fieldname => $field ) {
201 if ( !empty( $field->mParams['nodata'] ) ) {
202 continue;
203 } else {
204 $row[$fieldname] = $field->getDefault();
205 }
206 }
207 $ret = [ $row ];
208 }
209
210 return $ret;
211 }
212
213 public function cancelSubmit( $values, $alldata ) {
214 if ( isset( $values['nonjs'] ) ) {
215 return true;
216 }
217
218 foreach ( $values as $key => $value ) {
219 $fields = $this->createFieldsForKey( $key );
220 foreach ( $fields as $fieldname => $field ) {
221 if ( !array_key_exists( $fieldname, $value ) ) {
222 continue;
223 }
224 if ( $field->cancelSubmit( $value[$fieldname], $alldata ) ) {
225 return true;
226 }
227 }
228 }
229
230 return parent::cancelSubmit( $values, $alldata );
231 }
232
233 public function validate( $values, $alldata ) {
234 if ( isset( $this->mParams['required'] )
235 && $this->mParams['required'] !== false
236 && !$values
237 ) {
238 return $this->msg( 'htmlform-cloner-required' );
239 }
240
241 if ( isset( $values['nonjs'] ) ) {
242 // The submission was a non-JS create/delete click, so fail
243 // validation in case cancelSubmit() somehow didn't already handle
244 // it.
245 return false;
246 }
247
248 foreach ( $values as $key => $value ) {
249 $fields = $this->createFieldsForKey( $key );
250 foreach ( $fields as $fieldname => $field ) {
251 if ( !array_key_exists( $fieldname, $value ) ) {
252 continue;
253 }
254 if ( $field->isHidden( $alldata ) ) {
255 continue;
256 }
257 $ok = $field->validate( $value[$fieldname], $alldata );
258 if ( $ok !== true ) {
259 return false;
260 }
261 }
262 }
263
264 return parent::validate( $values, $alldata );
265 }
266
267 /**
268 * Get the input HTML for the specified key.
269 *
270 * @param string $key Array key under which the fields should be named
271 * @param array $values
272 * @return string
273 */
274 protected function getInputHTMLForKey( $key, array $values ) {
275 $displayFormat = isset( $this->mParams['format'] )
276 ? $this->mParams['format']
277 : $this->mParent->getDisplayFormat();
278
279 // Conveniently, PHP method names are case-insensitive.
280 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
281
282 $html = '';
283 $hidden = '';
284 $hasLabel = false;
285
286 $fields = $this->createFieldsForKey( $key );
287 foreach ( $fields as $fieldname => $field ) {
288 $v = array_key_exists( $fieldname, $values )
289 ? $values[$fieldname]
290 : $field->getDefault();
291
292 if ( $field instanceof HTMLHiddenField ) {
293 // HTMLHiddenField doesn't generate its own HTML
294 list( $name, $value, $params ) = $field->getHiddenFieldData( $v );
295 $hidden .= Html::hidden( $name, $value, $params ) . "\n";
296 } else {
297 $html .= $field->$getFieldHtmlMethod( $v );
298
299 $labelValue = trim( $field->getLabel() );
300 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
301 $hasLabel = true;
302 }
303 }
304 }
305
306 if ( !isset( $fields['delete'] ) ) {
307 $name = "{$this->mName}[$key][delete]";
308 $label = isset( $this->mParams['delete-button-message'] )
309 ? $this->mParams['delete-button-message']
310 : 'htmlform-cloner-delete';
311 $field = HTMLForm::loadInputFromParameters( $name, [
312 'type' => 'submit',
313 'name' => $name,
314 'id' => Sanitizer::escapeId( "{$this->mID}--$key--delete" ),
315 'cssclass' => 'mw-htmlform-cloner-delete-button',
316 'default' => $this->getMessage( $label )->text(),
317 ], $this->mParent );
318 $v = $field->getDefault();
319
320 if ( $displayFormat === 'table' ) {
321 $html .= $field->$getFieldHtmlMethod( $v );
322 } else {
323 $html .= $field->getInputHTML( $v );
324 }
325 }
326
327 if ( $displayFormat !== 'raw' ) {
328 $classes = [
329 'mw-htmlform-cloner-row',
330 ];
331
332 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
333 $classes[] = 'mw-htmlform-nolabel';
334 }
335
336 $attribs = [
337 'class' => implode( ' ', $classes ),
338 ];
339
340 if ( $displayFormat === 'table' ) {
341 $html = Html::rawElement( 'table',
342 $attribs,
343 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
344 } else {
345 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
346 }
347 }
348
349 $html .= $hidden;
350
351 if ( !empty( $this->mParams['row-legend'] ) ) {
352 $legend = $this->msg( $this->mParams['row-legend'] )->text();
353 $html = Xml::fieldset( $legend, $html );
354 }
355
356 return $html;
357 }
358
359 public function getInputHTML( $values ) {
360 $html = '';
361
362 foreach ( (array)$values as $key => $value ) {
363 if ( $key === 'nonjs' ) {
364 continue;
365 }
366 $html .= Html::rawElement( 'li', [ 'class' => 'mw-htmlform-cloner-li' ],
367 $this->getInputHTMLForKey( $key, $value )
368 );
369 }
370
371 $template = $this->getInputHTMLForKey( $this->uniqueId, [] );
372 $html = Html::rawElement( 'ul', [
373 'id' => "mw-htmlform-cloner-list-{$this->mID}",
374 'class' => 'mw-htmlform-cloner-ul',
375 'data-template' => $template,
376 'data-unique-id' => $this->uniqueId,
377 ], $html );
378
379 $name = "{$this->mName}[create]";
380 $label = isset( $this->mParams['create-button-message'] )
381 ? $this->mParams['create-button-message']
382 : 'htmlform-cloner-create';
383 $field = HTMLForm::loadInputFromParameters( $name, [
384 'type' => 'submit',
385 'name' => $name,
386 'id' => Sanitizer::escapeId( "{$this->mID}--create" ),
387 'cssclass' => 'mw-htmlform-cloner-create-button',
388 'default' => $this->getMessage( $label )->text(),
389 ], $this->mParent );
390 $html .= $field->getInputHTML( $field->getDefault() );
391
392 return $html;
393 }
394 }