Misc EOL w/s and spaces-instead-of-tabs fixes. One day I'll get around to nagging...
[lhc/web/wiklou.git] / includes / HTMLForm.php
index 5a0fbae..ec038c9 100644 (file)
@@ -101,6 +101,8 @@ class HTMLForm {
        protected $mSubmitName;
        protected $mSubmitText;
        protected $mSubmitTooltip;
+
+       protected $mContext; // <! RequestContext
        protected $mTitle;
        protected $mMethod = 'post';
 
@@ -113,10 +115,22 @@ class HTMLForm {
        /**
         * Build a new HTMLForm from an array of field attributes
         * @param $descriptor Array of Field constructs, as described above
+        * @param $context RequestContext available since 1.18, will become compulsory in 1.19.
+        *     Obviates the need to call $form->setTitle()
         * @param $messagePrefix String a prefix to go in front of default messages
         */
-       public function __construct( $descriptor, $messagePrefix = '' ) {
-               $this->mMessagePrefix = $messagePrefix;
+       public function __construct( $descriptor, /*RequestContext*/ $context = null, $messagePrefix = '' ) {
+               if( $context instanceof RequestContext ){
+                       $this->mContext = $context;
+                       $this->mTitle = false; // We don't need them to set a title
+                       $this->mMessagePrefix = $messagePrefix;
+               } else {
+                       // B/C since 1.18
+                       if( is_string( $context ) && $messagePrefix === '' ){
+                               // it's actually $messagePrefix
+                               $this->mMessagePrefix = $context;
+                       }
+               }
 
                // Expand out into a tree.
                $loadedDescriptor = array();
@@ -159,7 +173,7 @@ class HTMLForm {
        /**
         * Add the HTMLForm-specific JavaScript, if it hasn't been
         * done already.
-        * @deprecated @since 1.18 load modules with ResourceLoader instead
+        * @deprecated since 1.18 load modules with ResourceLoader instead
         */
        static function addJS() { }
 
@@ -174,6 +188,8 @@ class HTMLForm {
                } elseif ( isset( $descriptor['type'] ) ) {
                        $class = self::$typeMappings[$descriptor['type']];
                        $descriptor['class'] = $class;
+               } else {
+                       $class = null;
                }
 
                if ( !$class ) {
@@ -192,7 +208,7 @@ class HTMLForm {
         */
        function prepareForm() {
                # Check if we have the info we need
-               if ( ! $this->mTitle ) {
+               if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
                        throw new MWException( "You must call setTitle() on an HTMLForm" );
                }
 
@@ -205,11 +221,10 @@ class HTMLForm {
         * @return Status|boolean
         */
        function tryAuthorizedSubmit() {
-               global $wgUser, $wgRequest;
-               $editToken = $wgRequest->getVal( 'wpEditToken' );
+               $editToken = $this->getRequest()->getVal( 'wpEditToken' );
 
                $result = false;
-               if ( $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
+               if ( $this->getMethod() != 'post' || $this->getUser()->matchEditToken( $editToken ) ) {
                        $result = $this->trySubmit();
                }
                return $result;
@@ -303,9 +318,9 @@ class HTMLForm {
         * Add header text, inside the form.
         * @param $msg String complete text of message to display
         */
-       function addHeaderText( $msg, $section = null ) { 
+       function addHeaderText( $msg, $section = null ) {
                if ( is_null( $section ) ) {
-                       $this->mHeader .= $msg; 
+                       $this->mHeader .= $msg;
                } else {
                        if ( !isset( $this->mSectionHeaders[$section] ) ) {
                                $this->mSectionHeaders[$section] = '';
@@ -318,14 +333,14 @@ class HTMLForm {
         * Add footer text, inside the form.
         * @param $msg String complete text of message to display
         */
-       function addFooterText( $msg, $section = null ) { 
+       function addFooterText( $msg, $section = null ) {
                if ( is_null( $section ) ) {
-                       $this->mFooter .= $msg; 
+                       $this->mFooter .= $msg;
                } else {
                        if ( !isset( $this->mSectionFooters[$section] ) ) {
                                $this->mSectionFooters[$section] = '';
                        }
-                       $this->mSectionFooters[$section] .= $msg;                       
+                       $this->mSectionFooters[$section] .= $msg;
                }
        }
 
@@ -356,11 +371,9 @@ class HTMLForm {
         * @param $submitResult Mixed output from HTMLForm::trySubmit()
         */
        function displayForm( $submitResult ) {
-               global $wgOut;
-
                # For good measure (it is the default)
-               $wgOut->preventClickjacking();
-               $wgOut->addModules( 'mediawiki.htmlform' );
+               $this->getOutput()->preventClickjacking();
+               $this->getOutput()->addModules( 'mediawiki.htmlform' );
 
                $html = ''
                        . $this->getErrors( $submitResult )
@@ -373,7 +386,7 @@ class HTMLForm {
 
                $html = $this->wrapForm( $html );
 
-               $wgOut->addHTML( ''
+               $this->getOutput()->addHTML( ''
                        . $this->mPre
                        . $html
                        . $this->mPost
@@ -414,11 +427,9 @@ class HTMLForm {
         * @return String HTML.
         */
        function getHiddenFields() {
-               global $wgUser;
-
                $html = '';
                if( $this->getMethod() == 'post' ){
-                       $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
+                       $html .= Html::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
                        $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
                }
 
@@ -447,8 +458,7 @@ class HTMLForm {
                }
 
                if ( isset( $this->mSubmitTooltip ) ) {
-                       global $wgUser;
-                       $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
+                       $attribs += Linker::tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
                }
 
                $attribs['class'] = 'mw-htmlform-submit';
@@ -495,16 +505,15 @@ class HTMLForm {
 
        /**
         * Format and display an error message stack.
-        * @param $errors Mixed String or Array of message keys
+        * @param $errors String|Array|Status
         * @return String
         */
        function getErrors( $errors ) {
                if ( $errors instanceof Status ) {
-                       global $wgOut;
                        if ( $errors->isOK() ) {
                                $errorstr = '';
                        } else {
-                               $errorstr = $wgOut->parse( $errors->getWikiText() );
+                               $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
                        }
                } elseif ( is_array( $errors ) ) {
                        $errorstr = $this->formatErrors( $errors );
@@ -522,7 +531,7 @@ class HTMLForm {
         * @param $errors Array of message keys/values
         * @return String HTML, a <ul> list of errors
         */
-       static function formatErrors( $errors ) {
+       public static function formatErrors( $errors ) {
                $errorstr = '';
 
                foreach ( $errors as $error ) {
@@ -535,7 +544,7 @@ class HTMLForm {
 
                        $errorstr .= Html::rawElement(
                                'li',
-                               null,
+                               array(),
                                wfMsgExt( $msg, array( 'parseinline' ), $error )
                        );
                }
@@ -573,7 +582,8 @@ class HTMLForm {
 
        /**
         * Set the id for the submit button.
-        * @param $t String.  FIXME: Integrity is *not* validated
+        * @param $t String.
+        * @todo FIXME: Integrity of $t is *not* validated
         */
        function setSubmitID( $t ) {
                $this->mSubmitID = $t;
@@ -613,7 +623,39 @@ class HTMLForm {
         * @return Title
         */
        function getTitle() {
-               return $this->mTitle;
+               return $this->mTitle === false
+                       ? $this->getContext()->title
+                       : $this->mTitle;
+       }
+
+       /**
+        * @return RequestContext
+        */
+       public function getContext(){
+               return $this->mContext instanceof RequestContext
+                       ? $this->mContext
+                       : RequestContext::getMain();
+       }
+
+       /**
+        * @return OutputPage
+        */
+       public function getOutput(){
+               return $this->getContext()->output;
+       }
+
+       /**
+        * @return WebRequest
+        */
+       public function getRequest(){
+               return $this->getContext()->request;
+       }
+
+       /**
+        * @return User
+        */
+       public function getUser(){
+               return $this->getContext()->user;
        }
 
        /**
@@ -648,14 +690,14 @@ class HTMLForm {
                                        $hasLeftColumn = true;
                        } elseif ( is_array( $value ) ) {
                                $section = $this->displaySection( $value, $key );
-                               $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
+                               $legend = $this->getLegend( $key );
                                if ( isset( $this->mSectionHeaders[$key] ) ) {
                                        $section = $this->mSectionHeaders[$key] . $section;
-                               } 
+                               }
                                if ( isset( $this->mSectionFooters[$key] ) ) {
                                        $section .= $this->mSectionFooters[$key];
                                }
-                               $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";                                   
+                               $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
                        }
                }
 
@@ -683,8 +725,6 @@ class HTMLForm {
         * Construct the form fields from the Descriptor array
         */
        function loadData() {
-               global $wgRequest;
-
                $fieldData = array();
 
                foreach ( $this->mFlatFields as $fieldname => $field ) {
@@ -693,7 +733,7 @@ class HTMLForm {
                        } elseif ( !empty( $field->mParams['disabled'] ) ) {
                                $fieldData[$fieldname] = $field->getDefault();
                        } else {
-                               $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
+                               $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
                        }
                }
 
@@ -725,6 +765,16 @@ class HTMLForm {
        function filterDataForSubmit( $data ) {
                return $data;
        }
+
+       /**
+        * Get a string to go in the <legend> of a section fieldset.  Override this if you
+        * want something more complicated
+        * @param $key String
+        * @return String
+        */
+       public function getLegend( $key ) {
+               return wfMsg( "{$this->mMessagePrefix}-$key" );
+       }
 }
 
 /**
@@ -741,6 +791,10 @@ abstract class HTMLFormField {
        protected $mID;
        protected $mClass = '';
        protected $mDefault;
+
+       /**
+        * @var HTMLForm
+        */
        public $mParent;
 
        /**
@@ -876,7 +930,6 @@ abstract class HTMLFormField {
         */
        function getTableRow( $value ) {
                # Check for invalid data.
-               global $wgRequest;
 
                $errors = $this->validate( $value, $this->mParent->mFieldData );
 
@@ -888,10 +941,12 @@ abstract class HTMLFormField {
                        $verticalLabel = true;
                }
 
-               if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
+               if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
                        $errors = '';
+                       $errorClass = '';
                } else {
-                       $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
+                       $errors = self::formatErrors( $errors );
+                       $errorClass = 'mw-htmlform-invalid-input';
                }
 
                $label = $this->getLabelHtml( $cellAttributes );
@@ -903,38 +958,35 @@ abstract class HTMLFormField {
 
                $fieldType = get_class( $this );
 
-               if ($verticalLabel) {
+               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}" ),
+                               array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
                                $field );
                } else {
                        $html = Html::rawElement( 'tr',
-                               array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
+                               array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
                                $label . $field );
                }
 
                $helptext = null;
 
                if ( isset( $this->mParams['help-message'] ) ) {
-                       $msg = $this->mParams['help-message'];
-                       $helptext = wfMsgExt( $msg, 'parseinline' );
-                       if ( wfEmptyMsg( $msg, $helptext ) ) {
-                               # Never mind
-                               $helptext = null;
+                       $msg = wfMessage( $this->mParams['help-message'] );
+                       if ( $msg->exists() ) {
+                               $helptext = $msg->parse();
                        }
                } 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;
+                       foreach( $this->mParams['help-messages'] as $name ) {
+                               $msg = wfMessage( $name );
+                               if( $msg->exists() ) {
+                                       $helptext .= $msg->parse(); // append message
                                }
-                               $helptext .= $candidate; // append message
-                       }       
+                       }
                } elseif ( isset( $this->mParams['help'] ) ) {
                        $helptext = $this->mParams['help'];
                }
@@ -983,10 +1035,7 @@ abstract class HTMLFormField {
                if ( empty( $this->mParams['tooltip'] ) ) {
                        return array();
                }
-
-               global $wgUser;
-
-               return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
+               return Linker::tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
        }
 
        /**
@@ -1009,6 +1058,35 @@ abstract class HTMLFormField {
 
                return $flatOpts;
        }
+
+       /**
+        * Formats one or more errors as accepted by field validation-callback.
+        * @param $errors String|Message|Array of strings or Message instances
+        * @return String html
+        * @since 1.18
+        */
+       protected static function formatErrors( $errors ) {
+               if ( is_array( $errors ) && count( $errors ) === 1 ) {
+                       $errors = array_shift( $errors );
+               }
+
+               if ( is_array( $errors ) ) {
+                       $lines = array();
+                       foreach ( $errors as $error ) {
+                               if ( $error instanceof Message ) {
+                                       $lines[] = Html::rawElement( 'li', array(), $error->parse() );
+                               } else {
+                                       $lines[] = Html::rawElement( 'li', array(), $error );
+                               }
+                       }
+                       return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
+               } else {
+                       if ( $errors instanceof Message ) {
+                               $errors = $errors->parse();
+                       }
+                       return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
+               }
+       }
 }
 
 class HTMLTextField extends HTMLFormField {
@@ -1216,6 +1294,10 @@ class HTMLCheckField extends HTMLFormField {
                return '&#160;';
        }
 
+       /**
+        * @param  $request WebRequest
+        * @return String
+        */
        function loadDataFromRequest( $request ) {
                $invert = false;
                if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
@@ -1223,7 +1305,7 @@ class HTMLCheckField extends HTMLFormField {
                }
 
                // GetCheck won't work like we want for checks.
-               if ( $request->getCheck( 'wpEditToken' ) ) {
+               if ( $request->getCheck( 'wpEditToken' ) || $this->mParent->getMethod() != 'post' ) {
                        // XOR has the following truth table, which is what we want
                        // INVERT VALUE | OUTPUT
                        // true   true  | false
@@ -1260,9 +1342,9 @@ class HTMLSelectField extends HTMLFormField {
                $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
 
                # If one of the options' 'name' is int(0), it is automatically selected.
-               # because PHP sucks and things int(0) == 'some string'.
+               # because PHP sucks and thinks int(0) == 'some string'.
                # Working around this by forcing all of them to strings.
-               foreach( $this->mParams['options'] as $key => &$opt ){
+               foreach( $this->mParams['options'] as &$opt ){
                        if( is_int( $opt ) ){
                                $opt = strval( $opt );
                        }
@@ -1343,6 +1425,10 @@ class HTMLSelectOrOtherField extends HTMLTextField {
                return "$select<br />\n$textbox";
        }
 
+       /**
+        * @param  $request WebRequest
+        * @return String
+        */
        function loadDataFromRequest( $request ) {
                if ( $request->getCheck( $this->mName ) ) {
                        $val = $request->getText( $this->mName );
@@ -1362,6 +1448,14 @@ class HTMLSelectOrOtherField extends HTMLTextField {
  * Multi-select field
  */
 class HTMLMultiSelectField extends HTMLFormField {
+
+       public function __construct( $params ){
+               parent::__construct( $params );
+               if( isset( $params['flatlist'] ) ){
+                       $this->mClass .= ' mw-htmlform-multiselect-flatlist';
+               }
+       }
+
        function validate( $value, $alldata ) {
                $p = parent::validate( $value, $alldata );
 
@@ -1413,25 +1507,35 @@ class HTMLMultiSelectField extends HTMLFormField {
                                        $attribs + $thisAttribs );
                                $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
 
-                               $html .= $checkbox . '<br />';
+                               $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
                        }
                }
 
                return $html;
        }
 
+       /**
+        * @param  $request WebRequest
+        * @return String
+        */
        function loadDataFromRequest( $request ) {
-               # won't work with getCheck
-               if ( $request->getCheck( 'wpEditToken' ) ) {
-                       $arr = $request->getArray( $this->mName );
-
-                       if ( !$arr ) {
-                               $arr = array();
+               if ( $this->mParent->getMethod() == 'post' ) {
+                       if( $request->wasPosted() ){
+                               # Checkboxes are just not added to the request arrays if they're not checked,
+                               # so it's perfectly possible for there not to be an entry at all
+                               return $request->getArray( $this->mName, array() );
+                       } else {
+                               # That's ok, the user has not yet submitted the form, so show the defaults
+                               return $this->getDefault();
                        }
-
-                       return $arr;
                } else {
-                       return $this->getDefault();
+                       # This is the impossible case: if we look at $_GET and see no data for our
+                       # field, is it because the user has not yet submitted the form, or that they
+                       # have submitted it with all the options unchecked? We will have to assume the
+                       # latter, which basically means that you can't specify 'positive' defaults
+                       # for GET forms.
+                       # @todo FIXME...
+                       return $request->getArray( $this->mName, array() );
                }
        }
 
@@ -1457,7 +1561,7 @@ class HTMLMultiSelectField extends HTMLFormField {
  * Plus a text field underneath for an additional reason.  The 'value' of the field is
  * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
  * select dropdown.
- * FIXME: If made 'required', only the text field should be compulsory.
+ * @todo FIXME: If made 'required', only the text field should be compulsory.
  */
 class HTMLSelectAndOtherField extends HTMLSelectField {
 
@@ -1521,7 +1625,7 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
                        } else {
                                # groupless reason list
                                $optgroup = false;
-                               $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
+                               $parts = array_map( 'trim', explode( '|', $option, 2 ) );
                                if( count( $parts ) === 1 ){
                                        $parts[1] = $parts[0];
                                }
@@ -1533,8 +1637,7 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
        }
 
        function getInputHTML( $value ) {
-
-               $select = parent::getInputHTML( $value );
+               $select = parent::getInputHTML( $value[1] );
 
                $textAttribs = array(
                        'id' => $this->mID . '-other',
@@ -1549,7 +1652,7 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
 
                $textbox = Html::input(
                        $this->mName . '-other',
-                       '',
+                       $value[2],
                        'text',
                        $textAttribs
                );
@@ -1557,6 +1660,10 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
                return "$select<br />\n$textbox";
        }
 
+       /**
+        * @param  $request WebRequest
+        * @return Array( <overall message>, <select value>, <text field value> )
+        */
        function loadDataFromRequest( $request ) {
                if ( $request->getCheck( $this->mName ) ) {
 
@@ -1564,27 +1671,22 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
                        $text = $request->getText( $this->mName . '-other' );
 
                        if ( $list == 'other' ) {
-                               return $text;
+                               $final = $text;
+                       } elseif( !in_array( $list, $this->mFlatOptions ) ){
+                               # User has spoofed the select form to give an option which wasn't
+                               # in the original offer.  Sulk...
+                               $final = $text;
+                       } elseif( $text == '' ) {
+                               $final = $list;
                        } else {
-                               # Need to get the value from the key
-                               if( in_array( $list, $this->mFlatOptions ) ){
-                                       $list = $this->mFlatOptions[$list];
-                               } else {
-                                       # User has spoofed the select form to give an option which wasn't
-                                       # in the original offer.  Sulk...
-                                       return $text;
-                               }
-                       }
-
-                       if( $text == '' ) {
-                               return $list;
-                       } else {
-                               return $list . wfMsgForContent( 'colon-separator' ) . $text;
+                               $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
                        }
 
                } else {
-                       return $this->getDefault();
+                       $final = $this->getDefault();
+                       $list = $text = '';
                }
+               return array( $final, $list, $text );
        }
 
        function getSize() {
@@ -1592,6 +1694,23 @@ class HTMLSelectAndOtherField extends HTMLSelectField {
                        ? $this->mParams['size']
                        : 45;
        }
+
+       function validate( $value, $alldata ) {
+               # HTMLSelectField forces $value to be one of the options in the select
+               # field, which is not useful here.  But we do want the validation further up
+               # the chain
+               $p = parent::validate( $value[1], $alldata );
+
+               if ( $p !== true ) {
+                       return $p;
+               }
+
+               if( isset( $this->mParams['required'] ) && $value[1] === '' ){
+                       return wfMsgExt( 'htmlform-required', 'parseinline' );
+               }
+
+               return true;
+       }
 }
 
 /**
@@ -1767,8 +1886,8 @@ class HTMLEditTools extends HTMLFormField {
                        }
                }
                $msg->inContentLanguage();
-               
-               
+
+
                return '<tr><td></td><td class="mw-input">'
                        . '<div class="mw-editTools">'
                        . $msg->parseAsBlock()