Implement quickbar settings
[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 if ( !empty( $this->mParams['invert'] ) )
529 $value = !$value;
530
531 return Xml::check( $this->mName, $value, array( 'id' => $this->mID ) ) . '&nbsp;' .
532 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
533 }
534
535 function getLabel( ) {
536 return '&nbsp;'; // In the right-hand column.
537 }
538
539 function loadDataFromRequest( $request ) {
540 $invert = false;
541 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
542 $invert = true;
543 }
544
545 // GetCheck won't work like we want for checks.
546 if ($request->getCheck( 'wpEditToken' ) ) {
547 // XOR has the following truth table, which is what we want
548 // INVERT VALUE | OUTPUT
549 // true true | false
550 // false true | true
551 // false false | false
552 // true false | true
553 return $request->getBool( $this->mName ) xor $invert;
554 } else {
555 return $this->getDefault();
556 }
557 }
558 }
559
560 class HTMLSelectField extends HTMLFormField {
561
562 function validate( $value, $alldata ) {
563 $p = parent::validate( $value, $alldata );
564 if ($p !== true) return $p;
565
566 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
567 if ( in_array( $value, $validOptions ) )
568 return true;
569 else
570 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
571 }
572
573 function getInputHTML( $value ) {
574 $select = new XmlSelect( $this->mName, $this->mID, $value );
575
576 $select->addOptions( $this->mParams['options'] );
577
578 return $select->getHTML();
579 }
580 }
581
582 class HTMLSelectOrOtherField extends HTMLTextField {
583 static $jsAdded = false;
584
585 function __construct( $params ) {
586 if (! array_key_exists('other', $params['options']) ) {
587 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
588 }
589
590 parent::__construct( $params );
591 }
592
593 function getInputHTML( $value ) {
594
595 $valInSelect = false;
596 if ($value !== false)
597 $valInSelect = in_array( $value,
598 HTMLFormField::flattenOptions($this->mParams['options']) );
599
600 $selected = $valInSelect ? $value : 'other';
601
602 $select = new XmlSelect( $this->mName, $this->mID, $selected );
603 $select->addOptions( $this->mParams['options'] );
604
605 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
606
607 $select = $select->getHTML();
608
609 $tbAttribs = array( 'id' => $this->mID.'-other' );
610
611 if ( isset($this->mParams['maxlength']) ) {
612 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
613 }
614
615 $textbox = Xml::input( $this->mName.'-other',
616 $this->getSize(),
617 $valInSelect ? '' : $value,
618 $tbAttribs );
619
620 return "$select<br/>\n$textbox";
621 }
622
623 function loadDataFromRequest( $request ) {
624 if ($request->getCheck( $this->mName ) ) {
625 $val = $request->getText( $this->mName );
626
627 if ($val == 'other') {
628 $val = $request->getText( $this->mName.'-other' );
629 }
630
631 return $val;
632 } else {
633 return $this->getDefault();
634 }
635 }
636 }
637
638 class HTMLMultiSelectField extends HTMLFormField {
639 function validate( $value, $alldata ) {
640 $p = parent::validate( $value, $alldata );
641 if ($p !== true) return $p;
642
643 if (!is_array($value)) return false;
644
645 // If all options are valid, array_intersect of the valid options and the provided
646 // options will return the provided options.
647 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
648
649 $validValues = array_intersect( $value, $validOptions );
650 if ( count( $validValues ) == count($value) )
651 return true;
652 else
653 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
654 }
655
656 function getInputHTML( $value ) {
657 $html = $this->formatOptions( $this->mParams['options'], $value );
658
659 return $html;
660 }
661
662 function formatOptions( $options, $value ) {
663 $html = '';
664 foreach( $options as $label => $info ) {
665 if (is_array($info)) {
666 $html .= Xml::tags( 'h1', null, $label ) . "\n";
667 $html .= $this->formatOptions( $info, $value );
668 } else {
669 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
670 array( 'id' => $this->mID."-$info", 'value' => $info ) );
671 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
672
673 $html .= Xml::tags( 'p', null, $checkbox );
674 }
675 }
676
677 return $html;
678 }
679
680 function loadDataFromRequest( $request ) {
681 // won't work with getCheck
682 if ($request->getCheck( 'wpEditToken' ) ) {
683 $arr = $request->getArray( $this->mName );
684
685 if (!$arr)
686 $arr = array();
687
688 return $arr;
689 } else {
690 return $this->getDefault();
691 }
692 }
693
694 function getDefault() {
695 if ( isset( $this->mDefault ) ) {
696 return $this->mDefault;
697 } else {
698 return array();
699 }
700 }
701 }
702
703 class HTMLRadioField extends HTMLFormField {
704 function validate( $value, $alldata ) {
705 $p = parent::validate( $value, $alldata );
706 if ($p !== true) return $p;
707
708 if (!is_string($value) && !is_int($value))
709 return false;
710
711 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
712
713 if ( in_array( $value, $validOptions ) )
714 return true;
715 else
716 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
717 }
718
719 function getInputHTML( $value ) {
720 $html = $this->formatOptions( $this->mParams['options'], $value );
721
722 return $html;
723 }
724
725 function formatOptions( $options, $value ) {
726 $html = '';
727 foreach( $options as $label => $info ) {
728 if (is_array($info)) {
729 $html .= Xml::tags( 'h1', null, $label ) . "\n";
730 $html .= $this->formatOptions( $info, $value );
731 } else {
732 $html .= Xml::radio( $this->mName, $info, $info == $value,
733 array( 'id' => $this->mID."-$info" ) );
734 $html .= '&nbsp;' .
735 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
736
737 $html .= "<br/>\n";
738 }
739 }
740
741 return $html;
742 }
743 }
744
745 class HTMLInfoField extends HTMLFormField {
746 function __construct( $info ) {
747 $info['nodata'] = true;
748
749 parent::__construct($info);
750 }
751
752 function getInputHTML( $value ) {
753 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
754 }
755
756 function getTableRow( $value ) {
757 if ( !empty($this->mParams['rawrow']) ) {
758 return $value;
759 }
760
761 return parent::getTableRow( $value );
762 }
763 }