ba44003dcda1c4091af34d7f7438826363c78394
[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, strval($value) );
605
606 // If one of the options' 'name' is int(0), it is automatically selected.
607 // because PHP sucks and things int(0) == 'some string'.
608 // Working around this by forcing all of them to strings.
609 $options = array_map( 'strval', $this->mParams['options'] );
610
611 if (!empty($this->mParams['disabled'])) {
612 $select->setAttribute( 'disabled', 'disabled' );
613 }
614
615 $select->addOptions( $options );
616
617 return $select->getHTML();
618 }
619 }
620
621 class HTMLSelectOrOtherField extends HTMLTextField {
622 static $jsAdded = false;
623
624 function __construct( $params ) {
625 if (! array_key_exists('other', $params['options']) ) {
626 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
627 }
628
629 parent::__construct( $params );
630 }
631
632 function getInputHTML( $value ) {
633 $valInSelect = false;
634
635 if ($value !== false)
636 $valInSelect = in_array( $value,
637 HTMLFormField::flattenOptions($this->mParams['options']) );
638
639 $selected = $valInSelect ? $value : 'other';
640
641 $select = new XmlSelect( $this->mName, $this->mID, $selected );
642 $select->addOptions( $this->mParams['options'] );
643
644 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
645
646 $tbAttribs = array( 'id' => $this->mID.'-other' );
647 if (!empty($this->mParams['disabled'])) {
648 $select->setAttribute( 'disabled', 'disabled' );
649 $tbAttribs['disabled'] = 'disabled';
650 }
651
652 $select = $select->getHTML();
653
654 if ( isset($this->mParams['maxlength']) ) {
655 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
656 }
657
658 $textbox = Xml::input( $this->mName.'-other',
659 $this->getSize(),
660 $valInSelect ? '' : $value,
661 $tbAttribs );
662
663 return "$select<br/>\n$textbox";
664 }
665
666 function loadDataFromRequest( $request ) {
667 if ($request->getCheck( $this->mName ) ) {
668 $val = $request->getText( $this->mName );
669
670 if ($val == 'other') {
671 $val = $request->getText( $this->mName.'-other' );
672 }
673
674 return $val;
675 } else {
676 return $this->getDefault();
677 }
678 }
679 }
680
681 class HTMLMultiSelectField extends HTMLFormField {
682 function validate( $value, $alldata ) {
683 $p = parent::validate( $value, $alldata );
684 if ($p !== true) return $p;
685
686 if (!is_array($value)) return false;
687
688 // If all options are valid, array_intersect of the valid options and the provided
689 // options will return the provided options.
690 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
691
692 $validValues = array_intersect( $value, $validOptions );
693 if ( count( $validValues ) == count($value) )
694 return true;
695 else
696 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
697 }
698
699 function getInputHTML( $value ) {
700 $html = $this->formatOptions( $this->mParams['options'], $value );
701
702 return $html;
703 }
704
705 function formatOptions( $options, $value ) {
706 $html = '';
707
708 $attribs = array();
709 if ( !empty( $this->mParams['disabled'] ) ) {
710 $attribs['disabled'] = 'disabled';
711 }
712
713 foreach( $options as $label => $info ) {
714 if (is_array($info)) {
715 $html .= Xml::tags( 'h1', null, $label ) . "\n";
716 $html .= $this->formatOptions( $info, $value );
717 } else {
718 $thisAttribs = array( 'id' => $this->mID."-$info", 'value' => $info );
719
720 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
721 $attribs + $thisAttribs );
722 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
723
724 $html .= $checkbox . '<br />';
725 }
726 }
727
728 return $html;
729 }
730
731 function loadDataFromRequest( $request ) {
732 // won't work with getCheck
733 if ($request->getCheck( 'wpEditToken' ) ) {
734 $arr = $request->getArray( $this->mName );
735
736 if (!$arr)
737 $arr = array();
738
739 return $arr;
740 } else {
741 return $this->getDefault();
742 }
743 }
744
745 function getDefault() {
746 if ( isset( $this->mDefault ) ) {
747 return $this->mDefault;
748 } else {
749 return array();
750 }
751 }
752 }
753
754 class HTMLRadioField extends HTMLFormField {
755 function validate( $value, $alldata ) {
756 $p = parent::validate( $value, $alldata );
757 if ($p !== true) return $p;
758
759 if (!is_string($value) && !is_int($value))
760 return false;
761
762 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
763
764 if ( in_array( $value, $validOptions ) )
765 return true;
766 else
767 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
768 }
769
770 function getInputHTML( $value ) {
771 $html = $this->formatOptions( $this->mParams['options'], $value );
772
773 return $html;
774 }
775
776 function formatOptions( $options, $value ) {
777 $html = '';
778
779 $attribs = array();
780 if ( !empty( $this->mParams['disabled'] ) ) {
781 $attribs['disabled'] = 'disabled';
782 }
783
784 foreach( $options as $label => $info ) {
785 if (is_array($info)) {
786 $html .= Xml::tags( 'h1', null, $label ) . "\n";
787 $html .= $this->formatOptions( $info, $value );
788 } else {
789 $html .= Xml::radio( $this->mName, $info, $info == $value,
790 $attribs + array( 'id' => $this->mID."-$info" ) );
791 $html .= '&nbsp;' .
792 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
793
794 $html .= "<br/>\n";
795 }
796 }
797
798 return $html;
799 }
800 }
801
802 class HTMLInfoField extends HTMLFormField {
803 function __construct( $info ) {
804 $info['nodata'] = true;
805
806 parent::__construct($info);
807 }
808
809 function getInputHTML( $value ) {
810 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
811 }
812
813 function getTableRow( $value ) {
814 if ( !empty($this->mParams['rawrow']) ) {
815 return $value;
816 }
817
818 return parent::getTableRow( $value );
819 }
820 }