Fix r80982, re-add accidental removed AND during debugging
[lhc/web/wiklou.git] / includes / HTMLForm.php
index 9e8e82f..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;
+       }
+
+       /**
+        * 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();
 
-               if ( $result === true ) {
+               $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
@@ -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'];
@@ -821,7 +866,7 @@ abstract class HTMLFormField {
                        $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 );
@@ -857,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'];
                }
@@ -908,7 +964,7 @@ abstract class HTMLFormField {
 
                global $wgUser;
 
-               return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
+               return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
        }
 
        /**
@@ -921,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 {
@@ -996,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() {
@@ -1049,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;
-       }
 }
 
 /**
@@ -1081,8 +1109,12 @@ 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' );
                }
 
@@ -1119,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' );
                }
@@ -1203,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();
        }
@@ -1341,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 .= '&#160;' . 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 />';
                        }
@@ -1482,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 ) {
@@ -1530,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 {