MediaWiki  1.28.0
HTMLFormFieldCloner.php
Go to the documentation of this file.
1 <?php
2 
39  private static $counter = 0;
40 
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 
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  $field = HTMLForm::loadInputFromParameters( $name, $info, $this->mParent );
100  $fields[$fieldname] = $field;
101  }
102  return $fields;
103  }
104 
113  protected function rekeyValuesArray( $key, $values ) {
114  $data = [];
115  foreach ( $values as $fieldname => $value ) {
116  $name = "{$this->mName}[$key][$fieldname]";
117  $data[$name] = $value;
118  }
119  return $data;
120  }
121 
122  protected function needsLabel() {
123  return false;
124  }
125 
126  public function loadDataFromRequest( $request ) {
127  // It's possible that this might be posted with no fields. Detect that
128  // by looking for an edit token.
129  if ( !$request->getCheck( 'wpEditToken' ) && $request->getArray( $this->mName ) === null ) {
130  return $this->getDefault();
131  }
132 
133  $values = $request->getArray( $this->mName );
134  if ( $values === null ) {
135  $values = [];
136  }
137 
138  $ret = [];
139  foreach ( $values as $key => $value ) {
140  if ( $key === 'create' || isset( $value['delete'] ) ) {
141  $ret['nonjs'] = 1;
142  continue;
143  }
144 
145  // Add back in $request->getValues() so things that look for e.g.
146  // wpEditToken don't fail.
147  $data = $this->rekeyValuesArray( $key, $value ) + $request->getValues();
148 
149  $fields = $this->createFieldsForKey( $key );
150  $subrequest = new DerivativeRequest( $request, $data, $request->wasPosted() );
151  $row = [];
152  foreach ( $fields as $fieldname => $field ) {
153  if ( $field->skipLoadData( $subrequest ) ) {
154  continue;
155  } elseif ( !empty( $field->mParams['disabled'] ) ) {
156  $row[$fieldname] = $field->getDefault();
157  } else {
158  $row[$fieldname] = $field->loadDataFromRequest( $subrequest );
159  }
160  }
161  $ret[] = $row;
162  }
163 
164  if ( isset( $values['create'] ) ) {
165  // Non-JS client clicked the "create" button.
166  $fields = $this->createFieldsForKey( $this->uniqueId );
167  $row = [];
168  foreach ( $fields as $fieldname => $field ) {
169  if ( !empty( $field->mParams['nodata'] ) ) {
170  continue;
171  } else {
172  $row[$fieldname] = $field->getDefault();
173  }
174  }
175  $ret[] = $row;
176  }
177 
178  return $ret;
179  }
180 
181  public function getDefault() {
182  $ret = parent::getDefault();
183 
184  // The default default is one entry with all subfields at their
185  // defaults.
186  if ( $ret === null ) {
187  $fields = $this->createFieldsForKey( $this->uniqueId );
188  $row = [];
189  foreach ( $fields as $fieldname => $field ) {
190  if ( !empty( $field->mParams['nodata'] ) ) {
191  continue;
192  } else {
193  $row[$fieldname] = $field->getDefault();
194  }
195  }
196  $ret = [ $row ];
197  }
198 
199  return $ret;
200  }
201 
202  public function cancelSubmit( $values, $alldata ) {
203  if ( isset( $values['nonjs'] ) ) {
204  return true;
205  }
206 
207  foreach ( $values as $key => $value ) {
208  $fields = $this->createFieldsForKey( $key );
209  foreach ( $fields as $fieldname => $field ) {
210  if ( !array_key_exists( $fieldname, $value ) ) {
211  continue;
212  }
213  if ( $field->cancelSubmit( $value[$fieldname], $alldata ) ) {
214  return true;
215  }
216  }
217  }
218 
219  return parent::cancelSubmit( $values, $alldata );
220  }
221 
222  public function validate( $values, $alldata ) {
223  if ( isset( $this->mParams['required'] )
224  && $this->mParams['required'] !== false
225  && !$values
226  ) {
227  return $this->msg( 'htmlform-cloner-required' )->parseAsBlock();
228  }
229 
230  if ( isset( $values['nonjs'] ) ) {
231  // The submission was a non-JS create/delete click, so fail
232  // validation in case cancelSubmit() somehow didn't already handle
233  // it.
234  return false;
235  }
236 
237  foreach ( $values as $key => $value ) {
238  $fields = $this->createFieldsForKey( $key );
239  foreach ( $fields as $fieldname => $field ) {
240  if ( !array_key_exists( $fieldname, $value ) ) {
241  continue;
242  }
243  $ok = $field->validate( $value[$fieldname], $alldata );
244  if ( $ok !== true ) {
245  return false;
246  }
247  }
248  }
249 
250  return parent::validate( $values, $alldata );
251  }
252 
260  protected function getInputHTMLForKey( $key, array $values ) {
261  $displayFormat = isset( $this->mParams['format'] )
262  ? $this->mParams['format']
263  : $this->mParent->getDisplayFormat();
264 
265  // Conveniently, PHP method names are case-insensitive.
266  $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
267 
268  $html = '';
269  $hidden = '';
270  $hasLabel = false;
271 
272  $fields = $this->createFieldsForKey( $key );
273  foreach ( $fields as $fieldname => $field ) {
274  $v = array_key_exists( $fieldname, $values )
275  ? $values[$fieldname]
276  : $field->getDefault();
277 
278  if ( $field instanceof HTMLHiddenField ) {
279  // HTMLHiddenField doesn't generate its own HTML
280  list( $name, $value, $params ) = $field->getHiddenFieldData( $v );
281  $hidden .= Html::hidden( $name, $value, $params ) . "\n";
282  } else {
283  $html .= $field->$getFieldHtmlMethod( $v );
284 
285  $labelValue = trim( $field->getLabel() );
286  if ( $labelValue != '&#160;' && $labelValue !== '' ) {
287  $hasLabel = true;
288  }
289  }
290  }
291 
292  if ( !isset( $fields['delete'] ) ) {
293  $name = "{$this->mName}[$key][delete]";
294  $label = isset( $this->mParams['delete-button-message'] )
295  ? $this->mParams['delete-button-message']
296  : 'htmlform-cloner-delete';
298  'type' => 'submit',
299  'name' => $name,
300  'id' => Sanitizer::escapeId( "{$this->mID}--$key--delete" ),
301  'cssclass' => 'mw-htmlform-cloner-delete-button',
302  'default' => $this->getMessage( $label )->text(),
303  ], $this->mParent );
304  $v = $field->getDefault();
305 
306  if ( $displayFormat === 'table' ) {
307  $html .= $field->$getFieldHtmlMethod( $v );
308  } else {
309  $html .= $field->getInputHTML( $v );
310  }
311  }
312 
313  if ( $displayFormat !== 'raw' ) {
314  $classes = [
315  'mw-htmlform-cloner-row',
316  ];
317 
318  if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
319  $classes[] = 'mw-htmlform-nolabel';
320  }
321 
322  $attribs = [
323  'class' => implode( ' ', $classes ),
324  ];
325 
326  if ( $displayFormat === 'table' ) {
327  $html = Html::rawElement( 'table',
328  $attribs,
329  Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
330  } else {
331  $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
332  }
333  }
334 
335  $html .= $hidden;
336 
337  if ( !empty( $this->mParams['row-legend'] ) ) {
338  $legend = $this->msg( $this->mParams['row-legend'] )->text();
339  $html = Xml::fieldset( $legend, $html );
340  }
341 
342  return $html;
343  }
344 
345  public function getInputHTML( $values ) {
346  $html = '';
347 
348  foreach ( (array)$values as $key => $value ) {
349  if ( $key === 'nonjs' ) {
350  continue;
351  }
352  $html .= Html::rawElement( 'li', [ 'class' => 'mw-htmlform-cloner-li' ],
353  $this->getInputHTMLForKey( $key, $value )
354  );
355  }
356 
357  $template = $this->getInputHTMLForKey( $this->uniqueId, [] );
358  $html = Html::rawElement( 'ul', [
359  'id' => "mw-htmlform-cloner-list-{$this->mID}",
360  'class' => 'mw-htmlform-cloner-ul',
361  'data-template' => $template,
362  'data-unique-id' => $this->uniqueId,
363  ], $html );
364 
365  $name = "{$this->mName}[create]";
366  $label = isset( $this->mParams['create-button-message'] )
367  ? $this->mParams['create-button-message']
368  : 'htmlform-cloner-create';
370  'type' => 'submit',
371  'name' => $name,
372  'id' => Sanitizer::escapeId( "{$this->mID}--create" ),
373  'cssclass' => 'mw-htmlform-cloner-create-button',
374  'default' => $this->getMessage( $label )->text(),
375  ], $this->mParent );
376  $html .= $field->getInputHTML( $field->getDefault() );
377 
378  return $html;
379  }
380 }
getInputHTMLForKey($key, array $values)
Get the input HTML for the specified key.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1936
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
cancelSubmit($values, $alldata)
getMessage($value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a name + parameters array) into a Message.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1936
msg()
Get a translated interface message.
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:209
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:758
$value
rekeyValuesArray($key, $values)
Re-key the specified values array to match the names applied by createFieldsForKey().
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping $template
Definition: hooks.txt:802
static fieldset($legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:578
A container for HTMLFormFields that allows for multiple copies of the set of fields to be displayed t...
$params
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1936
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static loadInputFromParameters($fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:478
static escapeId($id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it. ...
Definition: Sanitizer.php:1170
validate($values, $alldata)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
The parent class to generate form fields.
string $uniqueId
String uniquely identifying this cloner instance and unlikely to exist otherwise in the generated HTM...
createFieldsForKey($key)
Create the HTMLFormFields that go inside this element, using the specified key.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300