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