04b36daae4ac3b405a2542efe2cb2ce50a83b7bb
[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 setIntro( $msg ) {
150 $this->mIntro = $msg;
151 }
152
153 function displayForm( $submitResult ) {
154 global $wgOut;
155
156 if ( $submitResult !== false ) {
157 $this->displayErrors( $submitResult );
158 }
159
160 if ( isset($this->mIntro) ) {
161 $wgOut->addHTML( $this->mIntro );
162 }
163
164 $html = $this->getBody();
165
166 // Hidden fields
167 $html .= $this->getHiddenFields();
168
169 // Buttons
170 $html .= $this->getButtons();
171
172 $html = $this->wrapForm( $html );
173
174 $wgOut->addHTML( $html );
175 }
176
177 function wrapForm( $html ) {
178 return Xml::tags( 'form',
179 array(
180 'action' => $this->getTitle()->getFullURL(),
181 'method' => 'post',
182 ),
183 $html );
184 }
185
186 function getHiddenFields() {
187 global $wgUser;
188 $html = '';
189
190 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
191 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
192
193 return $html;
194 }
195
196 function getButtons() {
197 $html = '';
198
199 $attribs = array();
200
201 if ( isset($this->mSubmitID) )
202 $attribs['id'] = $this->mSubmitID;
203
204 $attribs['class'] = 'mw-htmlform-submit';
205
206 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
207
208 if ($this->mShowReset) {
209 $html .= Xml::element( 'input',
210 array( 'type' => 'reset',
211 'value' => wfMsg('htmlform-reset')
212 ) ) . "\n";
213 }
214
215 return $html;
216 }
217
218 function getBody() {
219 return $this->displaySection( $this->mFieldTree );
220 }
221
222 function displayErrors( $errors ) {
223 if ( is_array( $errors ) ) {
224 $errorstr = $this->formatErrors( $errors );
225 } else {
226 $errorstr = $errors;
227 }
228
229 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
230
231 global $wgOut;
232 $wgOut->addHTML( $errorstr );
233 }
234
235 static function formatErrors( $errors ) {
236 $errorstr = '';
237 foreach ( $errors as $error ) {
238 if (is_array($error)) {
239 $msg = array_shift($error);
240 } else {
241 $msg = $error;
242 $error = array();
243 }
244 $errorstr .= Xml::tags( 'li',
245 null,
246 wfMsgExt( $msg, array( 'parseinline' ), $error )
247 );
248 }
249
250 $errorstr = Xml::tags( 'ul', null, $errorstr );
251
252 return $errorstr;
253 }
254
255 function setSubmitText( $t ) {
256 $this->mSubmitText = $t;
257 }
258
259 function getSubmitText() {
260 return isset($this->mSubmitText) ? $this->mSubmitText : wfMsg('htmlform-submit');
261 }
262
263 function setSubmitID( $t ) {
264 $this->mSubmitID = $t;
265 }
266
267 function setMessagePrefix( $p ) {
268 $this->mMessagePrefix = $p;
269 }
270
271 function setTitle( $t ) {
272 $this->mTitle = $t;
273 }
274
275 function getTitle() {
276 return $this->mTitle;
277 }
278
279 function displaySection( $fields ) {
280 $tableHtml = '';
281 $subsectionHtml = '';
282 $hasLeftColumn = false;
283
284 foreach( $fields as $key => $value ) {
285 if ( is_object( $value ) ) {
286 $v = empty($value->mParams['nodata'])
287 ? $this->mFieldData[$key]
288 : $value->getDefault();
289 $tableHtml .= $value->getTableRow( $v );
290
291 if ($value->getLabel() != '&nbsp;')
292 $hasLeftColumn = true;
293 } elseif ( is_array( $value ) ) {
294 $section = $this->displaySection( $value );
295 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
296 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
297 }
298 }
299
300 $classes = array();
301 if (!$hasLeftColumn) // Avoid strange spacing when no labels exist
302 $classes[] = 'mw-htmlform-nolabel';
303 $classes = implode( ' ', $classes );
304
305 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
306
307 return $subsectionHtml . "\n" . $tableHtml;
308 }
309
310 function loadData() {
311 global $wgRequest;
312
313 $fieldData = array();
314
315 foreach( $this->mFlatFields as $fieldname => $field ) {
316 if ( !empty($field->mParams['nodata']) ) continue;
317 if ( !empty($field->mParams['disabled']) ) {
318 $fieldData[$fieldname] = $field->getDefault();
319 } else {
320 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
321 }
322 }
323
324 // Filter data.
325 foreach( $fieldData as $name => &$value ) {
326 $field = $this->mFlatFields[$name];
327 $value = $field->filter( $value, $this->mFlatFields );
328 }
329
330 $this->mFieldData = $fieldData;
331 }
332
333 function importData( $fieldData ) {
334 // Filter data.
335 foreach( $fieldData as $name => &$value ) {
336 $field = $this->mFlatFields[$name];
337 $value = $field->filter( $value, $this->mFlatFields );
338 }
339
340 foreach( $this->mFlatFields as $fieldname => $field ) {
341 if ( !isset($fieldData[$fieldname]) )
342 $fieldData[$fieldname] = $field->getDefault();
343 }
344
345 $this->mFieldData = $fieldData;
346 }
347
348 function suppressReset( $suppressReset = true ) {
349 $this->mShowReset = !$suppressReset;
350 }
351
352 function filterDataForSubmit( $data ) {
353 return $data;
354 }
355 }
356
357 abstract class HTMLFormField {
358 abstract function getInputHTML( $value );
359
360 function validate( $value, $alldata ) {
361 if ( isset($this->mValidationCallback) ) {
362 return call_user_func( $this->mValidationCallback, $value, $alldata );
363 }
364
365 return true;
366 }
367
368 function filter( $value, $alldata ) {
369 if( isset( $this->mFilterCallback ) ) {
370 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
371 }
372
373 return $value;
374 }
375
376 function loadDataFromRequest( $request ) {
377 if ($request->getCheck( $this->mName ) ) {
378 return $request->getText( $this->mName );
379 } else {
380 return $this->getDefault();
381 }
382 }
383
384 function __construct( $params ) {
385 $this->mParams = $params;
386
387 if (isset( $params['label-message'] ) ) {
388 $msgInfo = $params['label-message'];
389
390 if ( is_array( $msgInfo ) ) {
391 $msg = array_shift( $msgInfo );
392 } else {
393 $msg = $msgInfo;
394 $msgInfo = array();
395 }
396
397 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
398 } elseif ( isset($params['label']) ) {
399 $this->mLabel = $params['label'];
400 }
401
402 if ( isset( $params['name'] ) ) {
403 $this->mName = 'wp'.$params['name'];
404 $this->mID = 'mw-input-'.$params['name'];
405 }
406
407 if ( isset( $params['default'] ) ) {
408 $this->mDefault = $params['default'];
409 }
410
411 if ( isset( $params['id'] ) ) {
412 $this->mID = $params['id'];
413 }
414
415 if ( isset( $params['validation-callback'] ) ) {
416 $this->mValidationCallback = $params['validation-callback'];
417 }
418
419 if ( isset( $params['filter-callback'] ) ) {
420 $this->mFilterCallback = $params['filter-callback'];
421 }
422 }
423
424 function getTableRow( $value ) {
425 // Check for invalid data.
426 global $wgRequest;
427
428 $errors = $this->validate( $value, $this->mParent->mFieldData );
429 if ( $errors === true || !$wgRequest->wasPosted() ) {
430 $errors = '';
431 } else {
432 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
433 }
434
435 $html = '';
436
437 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
438 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
439 );
440 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
441 $this->getInputHTML( $value ) ."\n$errors" );
442
443 $fieldType = get_class($this);
444
445 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
446 $html ) . "\n";
447
448 // Help text
449 if ( isset($this->mParams['help-message']) ) {
450 $msg = $this->mParams['help-message'];
451
452 $text = wfMsgExt( $msg, 'parseinline' );
453
454 if (!wfEmptyMsg( $msg, $text ) ) {
455 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
456 $text );
457
458 $row = Xml::tags( 'tr', null, $row );
459
460 $html .= "$row\n";
461 }
462 }
463
464 return $html;
465 }
466
467 function getLabel() {
468 return $this->mLabel;
469 }
470
471 function getDefault() {
472 if ( isset( $this->mDefault ) ) {
473 return $this->mDefault;
474 } else {
475 return null;
476 }
477 }
478
479 static function flattenOptions( $options ) {
480 $flatOpts = array();
481
482 foreach( $options as $key => $value ) {
483 if ( is_array( $value ) ) {
484 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
485 } else {
486 $flatOpts[] = $value;
487 }
488 }
489
490 return $flatOpts;
491 }
492 }
493
494 class HTMLTextField extends HTMLFormField {
495
496 function getSize() {
497 return isset($this->mParams['size']) ? $this->mParams['size'] : 45;
498 }
499
500 function getInputHTML( $value ) {
501 $attribs = array( 'id' => $this->mID );
502
503 if ( isset($this->mParams['maxlength']) ) {
504 $attribs['maxlength'] = $this->mParams['maxlength'];
505 }
506
507 if (!empty($this->mParams['disabled'])) {
508 $attribs['disabled'] = 'disabled';
509 }
510
511 return Xml::input( $this->mName,
512 $this->getSize(),
513 $value,
514 $attribs ) ;
515 }
516
517 }
518
519 class HTMLIntField extends HTMLTextField {
520 function getSize() {
521 return isset($this->mParams['size']) ? $this->mParams['size'] : 20;
522 }
523
524 function validate( $value, $alldata ) {
525 $p = parent::validate($value, $alldata);
526
527 if ($p !== true) return $p;
528
529 if ( intval($value) != $value ) {
530 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
531 }
532
533 $in_range = true;
534
535 if ( isset($this->mParams['min']) ) {
536 $min = $this->mParams['min'];
537 if ( $min > $value )
538 return wfMsgExt( 'htmlform-int-toolow', 'parse', array($min) );
539 }
540
541 if ( isset($this->mParams['max']) ) {
542 $max = $this->mParams['max'];
543 if ($max < $value)
544 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array($max) );
545 }
546
547 return true;
548 }
549 }
550
551 class HTMLCheckField extends HTMLFormField {
552 function getInputHTML( $value ) {
553 if ( !empty( $this->mParams['invert'] ) )
554 $value = !$value;
555
556 $attr = array( 'id' => $this->mID );
557 if (!empty($this->mParams['disabled'])) {
558 $attr['disabled'] = 'disabled';
559 }
560
561 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
562 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
563 }
564
565 function getLabel( ) {
566 return '&nbsp;'; // In the right-hand column.
567 }
568
569 function loadDataFromRequest( $request ) {
570 $invert = false;
571 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
572 $invert = true;
573 }
574
575 // GetCheck won't work like we want for checks.
576 if ($request->getCheck( 'wpEditToken' ) ) {
577 // XOR has the following truth table, which is what we want
578 // INVERT VALUE | OUTPUT
579 // true true | false
580 // false true | true
581 // false false | false
582 // true false | true
583 return $request->getBool( $this->mName ) xor $invert;
584 } else {
585 return $this->getDefault();
586 }
587 }
588 }
589
590 class HTMLSelectField extends HTMLFormField {
591
592 function validate( $value, $alldata ) {
593 $p = parent::validate( $value, $alldata );
594 if ($p !== true) return $p;
595
596 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
597 if ( in_array( $value, $validOptions ) )
598 return true;
599 else
600 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
601 }
602
603 function getInputHTML( $value ) {
604 $select = new XmlSelect( $this->mName, $this->mID, $value );
605
606 if (!empty($this->mParams['disabled'])) {
607 $select->setAttribute( 'disabled', 'disabled' );
608 }
609
610 $select->addOptions( $this->mParams['options'] );
611
612 return $select->getHTML();
613 }
614 }
615
616 class HTMLSelectOrOtherField extends HTMLTextField {
617 static $jsAdded = false;
618
619 function __construct( $params ) {
620 if (! array_key_exists('other', $params['options']) ) {
621 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
622 }
623
624 parent::__construct( $params );
625 }
626
627 function getInputHTML( $value ) {
628 $valInSelect = false;
629
630 if ($value !== false)
631 $valInSelect = in_array( $value,
632 HTMLFormField::flattenOptions($this->mParams['options']) );
633
634 $selected = $valInSelect ? $value : 'other';
635
636 $select = new XmlSelect( $this->mName, $this->mID, $selected );
637 $select->addOptions( $this->mParams['options'] );
638
639 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
640
641 $tbAttribs = array( 'id' => $this->mID.'-other' );
642 if (!empty($this->mParams['disabled'])) {
643 $select->setAttribute( 'disabled', 'disabled' );
644 $tbAttribs['disabled'] = 'disabled';
645 }
646
647 $select = $select->getHTML();
648
649 if ( isset($this->mParams['maxlength']) ) {
650 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
651 }
652
653 $textbox = Xml::input( $this->mName.'-other',
654 $this->getSize(),
655 $valInSelect ? '' : $value,
656 $tbAttribs );
657
658 return "$select<br/>\n$textbox";
659 }
660
661 function loadDataFromRequest( $request ) {
662 if ($request->getCheck( $this->mName ) ) {
663 $val = $request->getText( $this->mName );
664
665 if ($val == 'other') {
666 $val = $request->getText( $this->mName.'-other' );
667 }
668
669 return $val;
670 } else {
671 return $this->getDefault();
672 }
673 }
674 }
675
676 class HTMLMultiSelectField extends HTMLFormField {
677 function validate( $value, $alldata ) {
678 $p = parent::validate( $value, $alldata );
679 if ($p !== true) return $p;
680
681 if (!is_array($value)) return false;
682
683 // If all options are valid, array_intersect of the valid options and the provided
684 // options will return the provided options.
685 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
686
687 $validValues = array_intersect( $value, $validOptions );
688 if ( count( $validValues ) == count($value) )
689 return true;
690 else
691 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
692 }
693
694 function getInputHTML( $value ) {
695 $html = $this->formatOptions( $this->mParams['options'], $value );
696
697 return $html;
698 }
699
700 function formatOptions( $options, $value ) {
701 $html = '';
702
703 $attribs = array();
704 if ( !empty( $this->mParams['disabled'] ) ) {
705 $attribs['disabled'] = 'disabled';
706 }
707
708 foreach( $options as $label => $info ) {
709 if (is_array($info)) {
710 $html .= Xml::tags( 'h1', null, $label ) . "\n";
711 $html .= $this->formatOptions( $info, $value );
712 } else {
713 $thisAttribs = array( 'id' => $this->mID."-$info", 'value' => $info );
714
715 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
716 $attribs + $thisAttribs );
717 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
718
719 $html .= $checkbox . '<br />';
720 }
721 }
722
723 return $html;
724 }
725
726 function loadDataFromRequest( $request ) {
727 // won't work with getCheck
728 if ($request->getCheck( 'wpEditToken' ) ) {
729 $arr = $request->getArray( $this->mName );
730
731 if (!$arr)
732 $arr = array();
733
734 return $arr;
735 } else {
736 return $this->getDefault();
737 }
738 }
739
740 function getDefault() {
741 if ( isset( $this->mDefault ) ) {
742 return $this->mDefault;
743 } else {
744 return array();
745 }
746 }
747 }
748
749 class HTMLRadioField extends HTMLFormField {
750 function validate( $value, $alldata ) {
751 $p = parent::validate( $value, $alldata );
752 if ($p !== true) return $p;
753
754 if (!is_string($value) && !is_int($value))
755 return false;
756
757 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
758
759 if ( in_array( $value, $validOptions ) )
760 return true;
761 else
762 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
763 }
764
765 function getInputHTML( $value ) {
766 $html = $this->formatOptions( $this->mParams['options'], $value );
767
768 return $html;
769 }
770
771 function formatOptions( $options, $value ) {
772 $html = '';
773
774 $attribs = array();
775 if ( !empty( $this->mParams['disabled'] ) ) {
776 $attribs['disabled'] = 'disabled';
777 }
778
779 foreach( $options as $label => $info ) {
780 if (is_array($info)) {
781 $html .= Xml::tags( 'h1', null, $label ) . "\n";
782 $html .= $this->formatOptions( $info, $value );
783 } else {
784 $html .= Xml::radio( $this->mName, $info, $info == $value,
785 $attribs + array( 'id' => $this->mID."-$info" ) );
786 $html .= '&nbsp;' .
787 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
788
789 $html .= "<br/>\n";
790 }
791 }
792
793 return $html;
794 }
795 }
796
797 class HTMLInfoField extends HTMLFormField {
798 function __construct( $info ) {
799 $info['nodata'] = true;
800
801 parent::__construct($info);
802 }
803
804 function getInputHTML( $value ) {
805 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
806 }
807
808 function getTableRow( $value ) {
809 if ( !empty($this->mParams['rawrow']) ) {
810 return $value;
811 }
812
813 return parent::getTableRow( $value );
814 }
815 }