Update HTMLSelectOrOtherField to correctly work, since the code changes of having...
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2
3 class HTMLForm {
4
5 static $jsAdded = false;
6
7 /* The descriptor is an array of arrays.
8 i.e. array(
9 'fieldname' => array( 'section' => 'section/subsection',
10 properties... ),
11 ...
12 )
13 */
14
15 static $typeMappings = array(
16 'text' => 'HTMLTextField',
17 'select' => 'HTMLSelectField',
18 'radio' => 'HTMLRadioField',
19 'multiselect' => 'HTMLMultiSelectField',
20 'check' => 'HTMLCheckField',
21 'toggle' => 'HTMLCheckField',
22 'int' => 'HTMLIntField',
23 'info' => 'HTMLInfoField',
24 'selectorother' => 'HTMLSelectOrOtherField',
25 );
26
27 function __construct( $descriptor, $messagePrefix ) {
28 $this->mMessagePrefix = $messagePrefix;
29
30 // Expand out into a tree.
31 $loadedDescriptor = array();
32 $this->mFlatFields = array();
33
34 foreach( $descriptor as $fieldname => $info ) {
35 $section = '';
36 if ( isset( $info['section'] ) )
37 $section = $info['section'];
38
39 $info['name'] = $fieldname;
40
41 $field = $this->loadInputFromParameters( $info );
42 $field->mParent = $this;
43
44 $setSection =& $loadedDescriptor;
45 if ($section) {
46 $sectionParts = explode( '/', $section );
47
48 while( count($sectionParts) ) {
49 $newName = array_shift( $sectionParts );
50
51 if ( !isset($setSection[$newName]) ) {
52 $setSection[$newName] = array();
53 }
54
55 $setSection =& $setSection[$newName];
56 }
57 }
58
59 $setSection[$fieldname] = $field;
60 $this->mFlatFields[$fieldname] = $field;
61 }
62
63 $this->mFieldTree = $loadedDescriptor;
64
65 $this->mShowReset = true;
66 }
67
68 static function addJS() {
69 if (self::$jsAdded) return;
70
71 global $wgOut, $wgStylePath;
72
73 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
74 }
75
76 static function loadInputFromParameters( $descriptor ) {
77 if ( isset( $descriptor['class'] ) ) {
78 $class = $descriptor['class'];
79 } elseif ( isset( $descriptor['type'] ) ) {
80 $class = self::$typeMappings[$descriptor['type']];
81 $descriptor['class'] = $class;
82 }
83
84 if (!$class) {
85 throw new MWException( "Descriptor with no class: ".print_r( $descriptor, true ) );
86 }
87
88 $obj = new $class( $descriptor );
89
90 return $obj;
91 }
92
93 function show() {
94 $html = '';
95
96 self::addJS();
97
98 // Load data from the request.
99 $this->loadData();
100
101 // Try a submission
102 global $wgUser, $wgRequest;
103 $editToken = $wgRequest->getVal( 'wpEditToken' );
104
105 $result = false;
106 if ( $wgUser->matchEditToken( $editToken ) )
107 $result = $this->trySubmit();
108
109 if ($result === true)
110 return $result;
111
112 // Display form.
113 $this->displayForm( $result );
114 }
115
116 /** Return values:
117 * TRUE == Successful submission
118 * FALSE == No submission attempted
119 * Anything else == Error to display.
120 */
121 function trySubmit() {
122 // Check for validation
123 foreach( $this->mFlatFields as $fieldname => $field ) {
124 if ( !empty($field->mParams['nodata']) ) continue;
125 if ( $field->validate( $this->mFieldData[$fieldname],
126 $this->mFieldData ) !== true ) {
127 return isset($this->mValidationErrorMessage) ?
128 $this->mValidationErrorMessage : array( 'htmlform-invalid-input' );
129 }
130 }
131
132 $callback = $this->mSubmitCallback;
133
134 $data = $this->filterDataForSubmit( $this->mFieldData );
135
136 $res = call_user_func( $callback, $data );
137
138 return $res;
139 }
140
141 function setSubmitCallback( $cb ) {
142 $this->mSubmitCallback = $cb;
143 }
144
145 function setValidationErrorMessage( $msg ) {
146 $this->mValidationErrorMessage = $msg;
147 }
148
149 function displayForm( $submitResult ) {
150 global $wgOut;
151
152 if ( $submitResult !== false ) {
153 $this->displayErrors( $submitResult );
154 }
155
156 $html = $this->getBody();
157
158 // Hidden fields
159 $html .= $this->getHiddenFields();
160
161 // Buttons
162 $html .= $this->getButtons();
163
164 $html = $this->wrapForm( $html );
165
166 $wgOut->addHTML( $html );
167 }
168
169 function wrapForm( $html ) {
170 return Xml::tags( 'form',
171 array(
172 'action' => $this->getTitle()->getFullURL(),
173 'method' => 'post',
174 ),
175 $html );
176 }
177
178 function getHiddenFields() {
179 global $wgUser;
180 $html = '';
181
182 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
183 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
184
185 return $html;
186 }
187
188 function getButtons() {
189 $html = '';
190
191 $attribs = array();
192
193 if ( isset($this->mSubmitID) )
194 $attribs['id'] = $this->mSubmitID;
195
196 $attribs['class'] = 'mw-htmlform-submit';
197
198 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
199
200 if ($this->mShowReset) {
201 $html .= Xml::element( 'input',
202 array( 'type' => 'reset',
203 'value' => wfMsg('htmlform-reset')
204 ) ) . "\n";
205 }
206
207 return $html;
208 }
209
210 function getBody() {
211 return $this->displaySection( $this->mFieldTree );
212 }
213
214 function displayErrors( $errors ) {
215 if ( is_array( $errors ) ) {
216 $errorstr = $this->formatErrors( $errors );
217 } else {
218 $errorstr = $errors;
219 }
220
221 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
222
223 global $wgOut;
224 $wgOut->addHTML( $errorstr );
225 }
226
227 static function formatErrors( $errors ) {
228 $errorstr = '';
229 foreach ( $errors as $error ) {
230 if (is_array($error)) {
231 $msg = array_shift($error);
232 } else {
233 $msg = $error;
234 $error = array();
235 }
236 $errorstr .= Xml::tags( 'li',
237 null,
238 wfMsgExt( $msg, array( 'parseinline' ), $error )
239 );
240 }
241
242 $errorstr = Xml::tags( 'ul', null, $errorstr );
243
244 return $errorstr;
245 }
246
247 function setSubmitText( $t ) {
248 $this->mSubmitText = $t;
249 }
250
251 function getSubmitText() {
252 return isset($this->mSubmitText) ? $this->mSubmitText : wfMsg('htmlform-submit');
253 }
254
255 function setSubmitID( $t ) {
256 $this->mSubmitID = $t;
257 }
258
259 function setMessagePrefix( $p ) {
260 $this->mMessagePrefix = $p;
261 }
262
263 function setTitle( $t ) {
264 $this->mTitle = $t;
265 }
266
267 function getTitle() {
268 return $this->mTitle;
269 }
270
271 function displaySection( $fields ) {
272 $tableHtml = '';
273 $subsectionHtml = '';
274
275 foreach( $fields as $key => $value ) {
276 if ( is_object( $value ) ) {
277 $v = empty($value->mParams['nodata'])
278 ? $this->mFieldData[$key]
279 : $value->getDefault();
280 $tableHtml .= $value->getTableRow( $v );
281 } elseif ( is_array( $value ) ) {
282 $section = $this->displaySection( $value );
283 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
284 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
285 }
286 }
287
288 $tableHtml = "<table><tbody>\n$tableHtml\n</tbody></table>\n";
289
290 return $subsectionHtml . "\n" . $tableHtml;
291 }
292
293 function loadData() {
294 global $wgRequest;
295
296 $fieldData = array();
297
298 foreach( $this->mFlatFields as $fieldname => $field ) {
299 if ( !empty($field->mParams['nodata']) ) continue;
300 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
301 }
302
303 // Filter data.
304 foreach( $fieldData as $name => &$value ) {
305 $field = $this->mFlatFields[$name];
306 $value = $field->filter( $value, $this->mFlatFields );
307 }
308
309 $this->mFieldData = $fieldData;
310 }
311
312 function importData( $fieldData ) {
313 // Filter data.
314 foreach( $fieldData as $name => &$value ) {
315 $field = $this->mFlatFields[$name];
316 $value = $field->filter( $value, $this->mFlatFields );
317 }
318
319 foreach( $this->mFlatFields as $fieldname => $field ) {
320 if ( !isset($fieldData[$fieldname]) )
321 $fieldData[$fieldname] = $field->getDefault();
322 }
323
324 $this->mFieldData = $fieldData;
325 }
326
327 function suppressReset( $suppressReset = true ) {
328 $this->mShowReset = !$suppressReset;
329 }
330
331 function filterDataForSubmit( $data ) {
332 return $data;
333 }
334 }
335
336 abstract class HTMLFormField {
337 abstract function getInputHTML( $value );
338
339 function validate( $value, $alldata ) {
340 if ( isset($this->mValidationCallback) ) {
341 return call_user_func( $this->mValidationCallback, $value, $alldata );
342 }
343
344 return true;
345 }
346
347 function filter( $value, $alldata ) {
348 if( isset( $this->mFilterCallback ) ) {
349 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
350 }
351
352 return $value;
353 }
354
355 function loadDataFromRequest( $request ) {
356 if ($request->getCheck( $this->mName ) ) {
357 return $request->getText( $this->mName );
358 } else {
359 return $this->getDefault();
360 }
361 }
362
363 function __construct( $params ) {
364 $this->mParams = $params;
365
366 if (isset( $params['label-message'] ) ) {
367 $msgInfo = $params['label-message'];
368
369 if ( is_array( $msgInfo ) ) {
370 $msg = array_shift( $msgInfo );
371 } else {
372 $msg = $msgInfo;
373 $msgInfo = array();
374 }
375
376 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
377 } elseif ( isset($params['label']) ) {
378 $this->mLabel = $params['label'];
379 }
380
381 if ( isset( $params['name'] ) ) {
382 $this->mName = 'wp'.$params['name'];
383 $this->mID = 'mw-input-'.$params['name'];
384 }
385
386 if ( isset( $params['default'] ) ) {
387 $this->mDefault = $params['default'];
388 }
389
390 if ( isset( $params['id'] ) ) {
391 $this->mID = $params['id'];
392 }
393
394 if ( isset( $params['validation-callback'] ) ) {
395 $this->mValidationCallback = $params['validation-callback'];
396 }
397
398 if ( isset( $params['filter-callback'] ) ) {
399 $this->mFilterCallback = $params['filter-callback'];
400 }
401 }
402
403 function getTableRow( $value ) {
404 // Check for invalid data.
405 global $wgRequest;
406
407 $errors = $this->validate( $value, $this->mParent->mFieldData );
408 if ( $errors === true || !$wgRequest->wasPosted() ) {
409 $errors = '';
410 } else {
411 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
412 }
413
414 $html = '';
415
416 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
417 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
418 );
419 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
420 $this->getInputHTML( $value ) ."\n$errors" );
421
422 $fieldType = get_class($this);
423
424 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
425 $html ) . "\n";
426
427 // Help text
428 if ( isset($this->mParams['help-message']) ) {
429 $msg = $this->mParams['help-message'];
430
431 $text = wfMsgExt( $msg, 'parseinline' );
432
433 if (!wfEmptyMsg( $msg, $text ) ) {
434 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
435 $text );
436
437 $row = Xml::tags( 'tr', null, $row );
438
439 $html .= "$row\n";
440 }
441 }
442
443 return $html;
444 }
445
446 function getLabel() {
447 return $this->mLabel;
448 }
449
450 function getDefault() {
451 if ( isset( $this->mDefault ) ) {
452 return $this->mDefault;
453 } else {
454 return null;
455 }
456 }
457
458 static function flattenOptions( $options ) {
459 $flatOpts = array();
460
461 foreach( $options as $key => $value ) {
462 if ( is_array( $value ) ) {
463 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
464 } else {
465 $flatOpts[] = $value;
466 }
467 }
468
469 return $flatOpts;
470 }
471 }
472
473 class HTMLTextField extends HTMLFormField {
474
475 function getSize() {
476 return isset($this->mParams['size']) ? $this->mParams['size'] : 45;
477 }
478
479 function getInputHTML( $value ) {
480 $attribs = array( 'id' => $this->mID );
481
482 if ( isset($this->mParams['maxlength']) ) {
483 $attribs['maxlength'] = $this->mParams['maxlength'];
484 }
485
486 return Xml::input( $this->mName,
487 $this->getSize(),
488 $value,
489 $attribs );
490 }
491
492 }
493
494 class HTMLIntField extends HTMLTextField {
495 function getSize() {
496 return isset($this->mParams['size']) ? $this->mParams['size'] : 20;
497 }
498
499 function validate( $value, $alldata ) {
500 $p = parent::validate($value, $alldata);
501
502 if ($p !== true) return $p;
503
504 if ( intval($value) != $value ) {
505 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
506 }
507
508 $in_range = true;
509
510 if ( isset($this->mParams['min']) ) {
511 $min = $this->mParams['min'];
512 if ( $min > $value )
513 return wfMsgExt( 'htmlform-int-toolow', 'parse', array($min) );
514 }
515
516 if ( isset($this->mParams['max']) ) {
517 $max = $this->mParams['max'];
518 if ($max < $value)
519 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array($max) );
520 }
521
522 return true;
523 }
524 }
525
526 class HTMLCheckField extends HTMLFormField {
527 function getInputHTML( $value ) {
528 return Xml::check( $this->mName, $value, array( 'id' => $this->mID ) ) . '&nbsp;' .
529 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
530 }
531
532 function getLabel( ) {
533 return '&nbsp;'; // In the right-hand column.
534 }
535
536 function loadDataFromRequest( $request ) {
537 $invert = false;
538 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
539 $invert = true;
540 }
541
542 // GetCheck won't work like we want for checks.
543 if ($request->getCheck( 'wpEditToken' ) ) {
544 // XOR has the following truth table, which is what we want
545 // INVERT VALUE | OUTPUT
546 // true true | false
547 // false true | true
548 // false false | false
549 // true false | true
550 return $request->getBool( $this->mName ) xor $invert;
551 } else {
552 return $this->getDefault();
553 }
554 }
555 }
556
557 class HTMLSelectField extends HTMLFormField {
558
559 function validate( $value, $alldata ) {
560 $p = parent::validate( $value, $alldata );
561 if ($p !== true) return $p;
562
563 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
564 if ( in_array( $value, $validOptions ) )
565 return true;
566 else
567 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
568 }
569
570 function getInputHTML( $value ) {
571 $select = new XmlSelect( $this->mName, $this->mID, $value );
572
573 $select->addOptions( $this->mParams['options'] );
574
575 return $select->getHTML();
576 }
577 }
578
579 class HTMLSelectOrOtherField extends HTMLTextField {
580 static $jsAdded = false;
581
582 function __construct( $params ) {
583 if (! array_key_exists('other', $params['options']) ) {
584 $params['options']['other'] = wfMsg( 'htmlform-selectorother-other' );
585 }
586
587 parent::__construct( $params );
588 }
589
590 function getInputHTML( $value ) {
591
592 $valInSelect = false;
593 if ($value !== false)
594 $valInSelect = in_array( $value,
595 HTMLFormField::flattenOptions($this->mParams['options']) );
596
597 $selected = $valInSelect ? $value : 'other';
598
599 $select = new XmlSelect( $this->mName, $this->mID, $selected );
600 $select->addOptions( $this->mParams['options'] );
601
602 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
603
604 $select = $select->getHTML();
605
606 $tbAttribs = array( 'id' => $this->mID.'-other' );
607
608 if ( isset($this->mParams['maxlength']) ) {
609 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
610 }
611
612 $textbox = Xml::input( $this->mName.'-other',
613 $this->getSize(),
614 $valInSelect ? '' : $value,
615 $tbAttribs );
616
617 return "$select<br/>\n$textbox";
618 }
619
620 function loadDataFromRequest( $request ) {
621 if ($request->getCheck( $this->mName ) ) {
622 $val = $request->getText( $this->mName );
623
624 if ($val == 'other') {
625 $val = $request->getText( $this->mName.'-other' );
626 }
627
628 return $val;
629 } else {
630 return $this->getDefault();
631 }
632 }
633 }
634
635 class HTMLMultiSelectField extends HTMLFormField {
636 function validate( $value, $alldata ) {
637 $p = parent::validate( $value, $alldata );
638 if ($p !== true) return $p;
639
640 if (!is_array($value)) return false;
641
642 // If all options are valid, array_intersect of the valid options and the provided
643 // options will return the provided options.
644 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
645
646 $validValues = array_intersect( $value, $validOptions );
647 if ( count( $validValues ) == count($value) )
648 return true;
649 else
650 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
651 }
652
653 function getInputHTML( $value ) {
654 $html = $this->formatOptions( $this->mParams['options'], $value );
655
656 return $html;
657 }
658
659 function formatOptions( $options, $value ) {
660 $html = '';
661 foreach( $options as $label => $info ) {
662 if (is_array($info)) {
663 $html .= Xml::tags( 'h1', null, $label ) . "\n";
664 $html .= $this->formatOptions( $info, $value );
665 } else {
666 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
667 array( 'id' => $this->mID, 'value' => $info ) );
668 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID ), $label );
669
670 $html .= Xml::tags( 'p', null, $checkbox );
671 }
672 }
673
674 return $html;
675 }
676
677 function loadDataFromRequest( $request ) {
678 // won't work with getCheck
679 if ($request->getCheck( 'wpEditToken' ) ) {
680 $arr = $request->getArray( $this->mName );
681
682 if (!$arr)
683 $arr = array();
684
685 return $arr;
686 } else {
687 return $this->getDefault();
688 }
689 }
690
691 function getDefault() {
692 if ( isset( $this->mDefault ) ) {
693 return $this->mDefault;
694 } else {
695 return array();
696 }
697 }
698 }
699
700 class HTMLRadioField extends HTMLFormField {
701 function validate( $value, $alldata ) {
702 $p = parent::validate( $value, $alldata );
703 if ($p !== true) return $p;
704
705 if (!is_string($value) && !is_int($value))
706 return false;
707
708 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
709
710 if ( in_array( $value, $validOptions ) )
711 return true;
712 else
713 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
714 }
715
716 function getInputHTML( $value ) {
717 $html = $this->formatOptions( $this->mParams['options'], $value );
718
719 return $html;
720 }
721
722 function formatOptions( $options, $value ) {
723 $html = '';
724 foreach( $options as $label => $info ) {
725 if (is_array($info)) {
726 $html .= Xml::tags( 'h1', null, $label ) . "\n";
727 $html .= $this->formatOptions( $info, $value );
728 } else {
729 $html .= Xml::radio( $this->mName, $info, $info == $value,
730 array( 'id' => $this->mID."-$info" ) );
731 $html .= '&nbsp;' .
732 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
733
734 $html .= "<br/>\n";
735 }
736 }
737
738 return $html;
739 }
740 }
741
742 class HTMLInfoField extends HTMLFormField {
743 function __construct( $info ) {
744 $info['nodata'] = true;
745
746 parent::__construct($info);
747 }
748
749 function getInputHTML( $value ) {
750 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
751 }
752
753 function getTableRow( $value ) {
754 if ( !empty($this->mParams['rawrow']) ) {
755 return $value;
756 }
757
758 return parent::getTableRow( $value );
759 }
760 }