Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / HTMLForm.php
index 78c3794..2e7e399 100644 (file)
  * The constructor input is an associative array of $fieldname => $info,
  * where $info is an Associative Array with any of the following:
  *
- *      'class'        -- the subclass of HTMLFormField that will be used
- *                                to create the object.  *NOT* the CSS class!
- *      'type'     -- roughly translates into the <select> type attribute.
- *                                if 'class' is not specified, this is used as a map
- *                                through HTMLForm::$typeMappings to get the class name.
- *      'default'  -- default value when the form is displayed
- *      'id'       -- HTML id attribute
- *   'cssclass' -- CSS class
- *      'options'  -- varies according to the specific object.
- *      'label-message' -- message key for a message to use as the label.
- *                                can be an array of msg key and then parameters to
- *                                the message.
- *      'label'        -- alternatively, a raw text message. Overridden by
- *                                label-message
- *      'help-message'  -- message key for a message to use as a help text.
- *                                can be an array of msg key and then parameters to
- *                                the message.
- *      'required' -- passed through to the object, indicating that it
- *                                is a required field.
- *      'size'     -- the length of text fields
- *      'filter-callback -- a function name to give you the chance to
- *                                massage the inputted value before it's processed.
- *                                @see HTMLForm::filter()
- *      'validation-callback' -- a function name to give you the chance
- *                                to impose extra validation on the field input.
- *                                @see HTMLForm::validate()
+ *     'class'               -- the subclass of HTMLFormField that will be used
+ *                              to create the object.  *NOT* the CSS class!
+ *     'type'                -- roughly translates into the <select> type attribute.
+ *                              if 'class' is not specified, this is used as a map
+ *                              through HTMLForm::$typeMappings to get the class name.
+ *     'default'             -- default value when the form is displayed
+ *     'id'                  -- HTML id attribute
+ *     'cssclass'            -- CSS class
+ *     'options'             -- varies according to the specific object.
+ *     'label-message'       -- message key for a message to use as the label.
+ *                              can be an array of msg key and then parameters to
+ *                              the message.
+ *     'label'               -- alternatively, a raw text message. Overridden by
+ *                              label-message
+ *     'help-message'        -- message key for a message to use as a help text.
+ *                              can be an array of msg key and then parameters to
+ *                              the message.
+ *                           Overwrites 'help-messages'.
+ *  'help-messages'       -- array of message key. As above, each item can
+ *                           be an array of msg key and then parameters.
+ *                           Overwrites 'help-message'.
+ *     'required'            -- passed through to the object, indicating that it
+ *                              is a required field.
+ *     'size'                -- the length of text fields
+ *     'filter-callback      -- a function name to give you the chance to
+ *                              massage the inputted value before it's processed.
+ *                              @see HTMLForm::filter()
+ *     'validation-callback' -- a function name to give you the chance
+ *                              to impose extra validation on the field input.
+ *                              @see HTMLForm::validate()
+ *     'name'                -- By default, the 'name' attribute of the input field
+ *                              is "wp{$fieldname}".  If you want a different name
+ *                              (eg one without the "wp" prefix), specify it here and
+ *                              it will be used without modification.
  *
  * TODO: Document 'section' / 'subsection' stuff
  */
@@ -92,6 +100,7 @@ class HTMLForm {
        protected $mSubmitText;
        protected $mSubmitTooltip;
        protected $mTitle;
+       protected $mMethod = 'post';
 
        protected $mUseMultipart = false;
        protected $mHiddenFields = array();
@@ -116,15 +125,11 @@ class HTMLForm {
                                ? $info['section']
                                : '';
 
-                       $info['name'] = isset( $info['name'] )
-                               ? $info['name']
-                               : $fieldname;
-
                        if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
                                $this->mUseMultipart = true;
                        }
 
-                       $field = self::loadInputFromParameters( $info );
+                       $field = self::loadInputFromParameters( $fieldname, $info );
                        $field->mParent = $this;
 
                        $setSection =& $loadedDescriptor;
@@ -156,9 +161,9 @@ class HTMLForm {
        static function addJS() {
                if ( self::$jsAdded ) return;
 
-               global $wgOut, $wgStylePath;
+               global $wgOut;
 
-               $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
+               $wgOut->addModules( 'mediawiki.legacy.htmlform' );
        }
 
        /**
@@ -166,7 +171,7 @@ class HTMLForm {
         * @param $descriptor input Descriptor, as described above
         * @return HTMLFormField subclass
         */
-       static function loadInputFromParameters( $descriptor ) {
+       static function loadInputFromParameters( $fieldname, $descriptor ) {
                if ( isset( $descriptor['class'] ) ) {
                        $class = $descriptor['class'];
                } elseif ( isset( $descriptor['type'] ) ) {
@@ -177,6 +182,8 @@ class HTMLForm {
                if ( !$class ) {
                        throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
                }
+               
+               $descriptor['fieldname'] = $fieldname;
 
                $obj = new $class( $descriptor );
 
@@ -184,36 +191,50 @@ class HTMLForm {
        }
 
        /**
-        * The here's-one-I-made-earlier option: do the submission if
-        * posted, or display the form with or without funky valiation
-        * errors
-        * @return Bool whether submission was successful.
+        * Prepare form for submission
         */
-       function show() {
-               // Check if we have the info we need
+       function prepareForm() {
+               # Check if we have the info we need
                if ( ! $this->mTitle ) {
                        throw new MWException( "You must call setTitle() on an HTMLForm" );
                }
 
+               // FIXME shouldn't this be closer to displayForm() ?
                self::addJS();
 
                # Load data from the request.
                $this->loadData();
+       }
 
-               # Try a submission
+       /**
+        * Try submitting, with edit token check first
+        * @return Status|boolean 
+        */
+       function tryAuthorizedSubmit() {
                global $wgUser, $wgRequest;
                $editToken = $wgRequest->getVal( 'wpEditToken' );
 
                $result = false;
-               if ( $wgUser->matchEditToken( $editToken ) ) {
+               if ( $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
                        $result = $this->trySubmit();
                }
+               return $result;
+       }
 
-               if ( $result === true ) {
+       /**
+        * The here's-one-I-made-earlier option: do the submission if
+        * posted, or display the form with or without funky valiation
+        * errors
+        * @return Bool or Status whether submission was successful.
+        */
+       function show() {
+               $this->prepareForm();
+
+               $result = $this->tryAuthorizedSubmit();
+               if ( $result === true || ( $result instanceof Status && $result->isGood() ) ){
                        return $result;
                }
 
-               # Display form.
                $this->displayForm( $result );
                return false;
        }
@@ -304,7 +325,7 @@ class HTMLForm {
 
        /**
         * Add a hidden field to the output
-        * @param $name String field name
+        * @param $name String field name.  This will be used exactly as entered
         * @param $value String field value
         * @param $attribs Array
         */
@@ -325,6 +346,9 @@ class HTMLForm {
        function displayForm( $submitResult ) {
                global $wgOut;
 
+               # For good measure (it is the default)
+               $wgOut->preventClickjacking();
+
                $html = ''
                        . $this->getErrors( $submitResult )
                        . $this->mHeader
@@ -361,7 +385,7 @@ class HTMLForm {
                # Attributes
                $attribs = array(
                        'action'  => $this->getTitle()->getFullURL(),
-                       'method'  => 'post',
+                       'method'  => $this->mMethod,
                        'class'   => 'visualClear',
                        'enctype' => $encType,
                );
@@ -380,8 +404,11 @@ class HTMLForm {
                global $wgUser;
 
                $html = '';
-               $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
-               $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
+               
+               if( $this->getMethod() == 'post' ){
+                       $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
+                       $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
+               }
 
                foreach ( $this->mHiddenFields as $data ) {
                        list( $value, $attribs ) = $data;
@@ -460,7 +487,10 @@ class HTMLForm {
         * @return String
         */
        function getErrors( $errors ) {
-               if ( is_array( $errors ) ) {
+               if ( $errors instanceof Status ) {
+                       global $wgOut;
+                       $errorstr = $wgOut->parse( $errors->getWikiText() );
+               } elseif ( is_array( $errors ) ) {
                        $errorstr = $this->formatErrors( $errors );
                } else {
                        $errorstr = $errors;
@@ -525,7 +555,6 @@ class HTMLForm {
                $this->mSubmitTooltip = $name;
        }
 
-
        /**
         * Set the id for the submit button.
         * @param $t String.  FIXME: Integrity is *not* validated
@@ -570,6 +599,18 @@ class HTMLForm {
        function getTitle() {
                return $this->mTitle;
        }
+       
+       /**
+        * Set the method used to submit the form
+        * @param $method String
+        */
+       public function setMethod( $method='post' ){
+               $this->mMethod = $method;
+       }
+       
+       public function getMethod(){
+               return $this->mMethod;
+       }
 
        /**
         * TODO: Document
@@ -587,7 +628,7 @@ class HTMLForm {
                                        : $value->getDefault();
                                $tableHtml .= $value->getTableRow( $v );
 
-                               if ( $value->getLabel() != '&nbsp;' )
+                               if ( $value->getLabel() != '&#160;' )
                                        $hasLeftColumn = true;
                        } elseif ( is_array( $value ) ) {
                                $section = $this->displaySection( $value, $key );
@@ -703,6 +744,10 @@ abstract class HTMLFormField {
                        return call_user_func( $this->mValidationCallback, $value, $alldata );
                }
 
+               if ( isset( $this->mParams['required'] ) && $value === '' ) {
+                       return wfMsgExt( 'htmlform-required', 'parseinline' );
+               }
+
                return true;
        }
 
@@ -761,17 +806,17 @@ abstract class HTMLFormField {
                        $this->mLabel = $params['label'];
                }
 
+               $this->mName = "wp{$params['fieldname']}";
                if ( isset( $params['name'] ) ) {
-                       $name = $params['name'];
-                       $validName = Sanitizer::escapeId( $name );
-
-                       if ( $name != $validName ) {
-                               throw new MWException( "Invalid name '$name' passed to " . __METHOD__ );
-                       }
-
-                       $this->mName = 'wp' . $name;
-                       $this->mID = 'mw-input-' . $name;
+                       $this->mName = $params['name'];
+               }
+               
+               $validName = Sanitizer::escapeId( $this->mName );
+               if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
+                       throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
                }
+               
+               $this->mID = "mw-input-{$this->mName}";
 
                if ( isset( $params['default'] ) ) {
                        $this->mDefault = $params['default'];
@@ -812,27 +857,41 @@ abstract class HTMLFormField {
                global $wgRequest;
 
                $errors = $this->validate( $value, $this->mParent->mFieldData );
+               
+               $cellAttributes = array();
+               $verticalLabel = false;
+               
+               if ( !empty($this->mParams['vertical-label']) ) {
+                       $cellAttributes['colspan'] = 2;
+                       $verticalLabel = true;
+               }
 
-               if ( $errors === true || !$wgRequest->wasPosted() ) {
+               if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
                        $errors = '';
                } else {
                        $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
                }
 
-               $html = $this->getLabelHtml();
-               $html .= Html::rawElement(
+               $label = $this->getLabelHtml( $cellAttributes );
+               $field = Html::rawElement(
                        'td',
-                       array( 'class' => 'mw-input' ),
+                       array( 'class' => 'mw-input' ) + $cellAttributes,
                        $this->getInputHTML( $value ) . "\n$errors"
                );
-
+               
                $fieldType = get_class( $this );
-
-               $html = Html::rawElement(
-                       'tr',
-                       array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
-                       $html
-               ) . "\n";
+               
+               if ($verticalLabel) {
+                       $html = Html::rawElement( 'tr',
+                               array( 'class' => 'mw-htmlform-vertical-label' ), $label );
+                       $html .= Html::rawElement( 'tr',
+                               array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
+                               $field );
+               } else {
+                       $html = Html::rawElement( 'tr',
+                               array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
+                               $label . $field );
+               }
 
                $helptext = null;
 
@@ -843,6 +902,17 @@ abstract class HTMLFormField {
                                # Never mind
                                $helptext = null;
                        }
+               } elseif ( isset( $this->mParams['help-messages'] ) ) {
+                       # help-message can be passed a message key (string) or an array containing
+                       # a message key and additional parameters. This makes it impossible to pass
+                       # an array of message key
+                       foreach( $this->mParams['help-messages'] as $msg ) {
+                               $candidate = wfMsgExt( $msg, 'parseinline' );
+                               if( wfEmptyMsg( $msg ) ) {
+                                       $candidate = null;
+                               }
+                               $helptext .= $candidate; // append message
+                       }       
                } elseif ( isset( $this->mParams['help'] ) ) {
                        $helptext = $this->mParams['help'];
                }
@@ -860,7 +930,7 @@ abstract class HTMLFormField {
        function getLabel() {
                return $this->mLabel;
        }
-       function getLabelHtml() {
+       function getLabelHtml( $cellAttributes = array() ) {
                # Don't output a for= attribute for labels with no associated input.
                # Kind of hacky here, possibly we don't want these to be <label>s at all.
                $for = array();
@@ -869,7 +939,7 @@ abstract class HTMLFormField {
                        $for['for'] = $this->mID;
                }
 
-               return Html::rawElement( 'td', array( 'class' => 'mw-label' ),
+               return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
                        Html::rawElement( 'label', $for, $this->getLabel() )
                );
        }
@@ -894,7 +964,7 @@ abstract class HTMLFormField {
 
                global $wgUser;
 
-               return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
+               return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
        }
 
        /**
@@ -907,7 +977,7 @@ abstract class HTMLFormField {
        public static function flattenOptions( $options ) {
                $flatOpts = array();
 
-               foreach ( $options as $key => $value ) {
+               foreach ( $options as $value ) {
                        if ( is_array( $value ) ) {
                                $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
                        } else {
@@ -982,20 +1052,6 @@ class HTMLTextField extends HTMLFormField {
 
                return Html::element( 'input', $attribs );
        }
-
-       public function validate( $value, $alldata ) {
-               $p = parent::validate( $value, $alldata );
-
-               if ( $p !== true ) {
-                       return $p;
-               }
-
-               if ( isset( $this->mParams['required'] ) && $value === '' ) {
-                       return wfMsgExt( 'htmlform-required', 'parseinline' );
-               }
-
-               return true;
-       }
 }
 class HTMLTextAreaField extends HTMLFormField {
        function getCols() {
@@ -1035,20 +1091,6 @@ class HTMLTextAreaField extends HTMLFormField {
 
                return Html::element( 'textarea', $attribs, $value );
        }
-
-       public function validate( $value, $alldata ) {
-               $p = parent::validate( $value, $alldata );
-
-               if ( $p !== true ) {
-                       return $p;
-               }
-
-               if ( isset( $this->mParams['required'] ) && $value === '' ) {
-                       return wfMsgExt( 'htmlform-required', 'parseinline' );
-               }
-
-               return true;
-       }
 }
 
 /**
@@ -1067,13 +1109,15 @@ class HTMLFloatField extends HTMLTextField {
                if ( $p !== true ) {
                        return $p;
                }
+               
+               $value = trim( $value );
 
-               if ( floatval( $value ) != $value ) {
+               # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
+               # with the addition that a leading '+' sign is ok. 
+               if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
                        return wfMsgExt( 'htmlform-float-invalid', 'parse' );
                }
 
-               $in_range = true;
-
                # The "int" part of these message names is rather confusing.
                # They make equal sense for all numbers.
                if ( isset( $this->mParams['min'] ) ) {
@@ -1107,8 +1151,13 @@ class HTMLIntField extends HTMLFloatField {
                        return $p;
                }
 
-               if ( $value !== ''
-                       && ( !is_numeric( $value ) || round( $value ) != $value )
+               # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
+               # with the addition that a leading '+' sign is ok. Note that leading zeros 
+               # are fine, and will be left in the input, which is useful for things like 
+               # phone numbers when you know that they are integers (the HTML5 type=tel
+               # input does not require its value to be numeric).  If you want a tidier
+               # value to, eg, save in the DB, clean it up with intval().
+               if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
                ) {
                        return wfMsgExt( 'htmlform-int-invalid', 'parse' );
                }
@@ -1133,7 +1182,7 @@ class HTMLCheckField extends HTMLFormField {
                        $attr['disabled'] = 'disabled';
                }
 
-               return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
+               return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
                        Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
        }
 
@@ -1142,7 +1191,7 @@ class HTMLCheckField extends HTMLFormField {
         * added in getInputHTML(), rather than HTMLFormField::getRow()
         */
        function getLabel() {
-               return '&nbsp;';
+               return '&#160;';
        }
 
        function loadDataFromRequest( $request ) {
@@ -1191,13 +1240,18 @@ class HTMLSelectField extends HTMLFormField {
                # If one of the options' 'name' is int(0), it is automatically selected.
                # because PHP sucks and things int(0) == 'some string'.
                # Working around this by forcing all of them to strings.
-               $options = array_map( 'strval', $this->mParams['options'] );
+               foreach( $this->mParams['options'] as $key => &$opt ){
+                       if( is_int( $opt ) ){
+                               $opt = strval( $opt );
+                       }
+               }
+               unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
 
                if ( !empty( $this->mParams['disabled'] ) ) {
                        $select->setAttribute( 'disabled', 'disabled' );
                }
 
-               $select->addOptions( $options );
+               $select->addOptions( $this->mParams['options'] );
 
                return $select->getHTML();
        }
@@ -1329,11 +1383,13 @@ class HTMLMultiSelectField extends HTMLFormField {
                                $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
                                $html .= $this->formatOptions( $info, $value );
                        } else {
-                               $thisAttribs = array( 'id' => $this->mID . "-$info", 'value' => $info );
+                               $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
 
-                               $checkbox = Xml::check( $this->mName . '[]', in_array( $info, $value, true ),
-                                                               $attribs + $thisAttribs );
-                               $checkbox .= '&nbsp;' . Html::rawElement( 'label', array( 'for' => $this->mID . "-$info" ), $label );
+                               $checkbox = Xml::check( 
+                                       $this->mName . '[]', 
+                                       in_array( $info, $value, true ),
+                                       $attribs + $thisAttribs );
+                               $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
 
                                $html .= $checkbox . '<br />';
                        }
@@ -1425,7 +1481,7 @@ class HTMLRadioField extends HTMLFormField {
                                        $info == $value,
                                        $attribs + array( 'id' => $id )
                                );
-                               $html .= '&nbsp;' .
+                               $html .= '&#160;' .
                                                Html::rawElement( 'label', array( 'for' => $id ), $label );
 
                                $html .= "<br />\n";
@@ -1470,9 +1526,10 @@ class HTMLInfoField extends HTMLFormField {
 class HTMLHiddenField extends HTMLFormField {
        public function __construct( $params ) {
                parent::__construct( $params );
-               # forcing the 'wp' prefix on hidden field names
-               # is undesirable
-               $this->mName = substr( $this->mName, 2 );
+               
+               # Per HTML5 spec, hidden fields cannot be 'required'
+               # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
+               unset( $this->mParams['required'] );
        }
 
        public function getTableRow( $value ) {
@@ -1518,6 +1575,13 @@ class HTMLSubmitField extends HTMLFormField {
        protected function needsLabel() {
                return false;
        }
+       
+       /**
+        * Button cannot be invalid
+        */
+       public function validate( $value, $alldata ){
+               return true;
+       }
 }
 
 class HTMLEditTools extends HTMLFormField {