* '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'.
+ * 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
*
* TODO: Document 'section' / 'subsection' stuff
*/
-class HTMLForm {
+class HTMLForm extends ContextSource {
# A mapping of 'type' inputs onto standard HTMLFormField subclasses
static $typeMappings = array(
'submit' => 'HTMLSubmitField',
'hidden' => 'HTMLHiddenField',
'edittools' => 'HTMLEditTools',
+ 'namespaces' => 'HTMLNamespacesField',
+ 'restrictionlevels' => 'HTMLRestrictionLevelsField',
# HTMLTextField will output the correct type="" attribute automagically.
# There are about four zillion other HTML5 input types, like url, but
);
protected $mMessagePrefix;
+
+ /** @var HTMLFormField[] */
protected $mFlatFields;
+
protected $mFieldTree;
protected $mShowReset = false;
public $mFieldData;
protected $mSubmitText;
protected $mSubmitTooltip;
- protected $mContext; // <! RequestContext
protected $mTitle;
protected $mMethod = 'post';
protected $mButtons = array();
protected $mWrapperLegend = false;
+
+ /**
+ * If true, sections that contain both fields and subsections will
+ * render their subsections before their fields.
+ *
+ * Subclasses may set this to false to render subsections after fields
+ * instead.
+ */
+ protected $mSubSectionBeforeFields = true;
/**
* 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.
+ * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
* Obviates the need to call $form->setTitle()
* @param $messagePrefix String a prefix to go in front of default messages
*/
- public function __construct( $descriptor, /*RequestContext*/ $context = null, $messagePrefix = '' ) {
- if( $context instanceof RequestContext ){
- $this->mContext = $context;
+ public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
+ if( $context instanceof IContextSource ){
+ $this->setContext( $context );
$this->mTitle = false; // We don't need them to set a title
$this->mMessagePrefix = $messagePrefix;
} else {
/**
* Initialise a new Object for the field
- * @param $descriptor input Descriptor, as described above
+ * @param $fieldname string
+ * @param $descriptor string input Descriptor, as described above
* @return HTMLFormField subclass
*/
static function loadInputFromParameters( $fieldname, $descriptor ) {
$data = $this->filterDataForSubmit( $this->mFieldData );
- $res = call_user_func( $callback, $data );
+ $res = call_user_func( $callback, $data, $this );
return $res;
}
* Set the introductory message, overwriting any existing message.
* @param $msg String complete text of message to display
*/
- function setIntro( $msg ) { $this->mPre = $msg; }
+ function setIntro( $msg ) {
+ $this->setPreText( $msg );
+ }
+
+ /**
+ * Set the introductory message, overwriting any existing message.
+ * @since 1.19
+ * @param $msg String complete text of message to display
+ */
+ function setPreText( $msg ) { $this->mPre = $msg; }
/**
* Add introductory text.
/**
* Add header text, inside the form.
* @param $msg String complete text of message to display
+ * @param $section The section to add the header to
*/
- 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] = '';
}
}
+ /**
+ * Set header text, inside the form.
+ * @since 1.19
+ * @param $msg String complete text of message to display
+ * @param $section The section to add the header to
+ */
+ function setHeaderText( $msg, $section = null ) {
+ if ( is_null( $section ) ) {
+ $this->mHeader = $msg;
+ } else {
+ $this->mSectionHeaders[$section] = $msg;
+ }
+ }
+
/**
* Add footer text, inside the form.
* @param $msg String complete text of message to display
+ * @param $section string The section to add the footer text to
*/
- 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;
+ }
+ }
+
+ /**
+ * Set footer text, inside the form.
+ * @since 1.19
+ * @param $msg String complete text of message to display
+ * @param $section string The section to add the footer text to
+ */
+ function setFooterText( $msg, $section = null ) {
+ if ( is_null( $section ) ) {
+ $this->mFooter = $msg;
+ } else {
+ $this->mSectionFooters[$section] = $msg;
}
}
*/
function addPostText( $msg ) { $this->mPost .= $msg; }
+ /**
+ * Set text at the end of the display.
+ * @param $msg String complete text of message to display
+ */
+ function setPostText( $msg ) { $this->mPost = $msg; }
+
/**
* Add a hidden field to the output
* @param $name String field name. This will be used exactly as entered
* @param $submitResult Mixed output from HTMLForm::trySubmit()
*/
function displayForm( $submitResult ) {
+ $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
+ }
+
+ /**
+ * Returns the raw HTML generated by the form
+ * @param $submitResult Mixed output from HTMLForm::trySubmit()
+ * @return string
+ */
+ function getHTML( $submitResult ) {
# For good measure (it is the default)
$this->getOutput()->preventClickjacking();
$this->getOutput()->addModules( 'mediawiki.htmlform' );
$html = $this->wrapForm( $html );
- $this->getOutput()->addHTML( ''
- . $this->mPre
- . $html
- . $this->mPost
- );
+ return '' . $this->mPre . $html . $this->mPost;
}
/**
* @return String HTML.
*/
function getHiddenFields() {
+ global $wgUsePathInfo;
+
$html = '';
if( $this->getMethod() == 'post' ){
- $html .= Html::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
+ $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
+ $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
+ }
+
+ if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
$html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
}
}
if ( isset( $this->mSubmitTooltip ) ) {
- $attribs += Linker::tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
+ $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
}
$attribs['class'] = 'mw-htmlform-submit';
/**
* Get the whole body of the form.
+ * @return String
*/
function getBody() {
return $this->displaySection( $this->mFieldTree );
$this->mSubmitText = $t;
}
+ /**
+ * Set the text for the submit button to a message
+ * @since 1.19
+ * @param $msg String message key
+ */
+ public function setSubmitTextMsg( $msg ) {
+ return $this->setSubmitText( $this->msg( $msg )->escaped() );
+ }
+
/**
* Get the text for the submit button, either customised or a default.
* @return unknown_type
/**
* 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;
*/
public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
+ /**
+ * Prompt the whole form to be wrapped in a <fieldset>, with
+ * this message as its <legend> element.
+ * @since 1.19
+ * @param $msg String message key
+ */
+ public function setWrapperLegendMsg( $msg ) {
+ return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
+ }
+
/**
* Set the prefix for various default messages
* TODO: currently only used for the <fieldset> legend on forms
*/
function getTitle() {
return $this->mTitle === false
- ? $this->getContext()->title
+ ? $this->getContext()->getTitle()
: $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;
- }
-
/**
* Set the method used to submit the form
* @param $method String
/**
* TODO: Document
- * @param $fields
+ * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
+ * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
+ * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
+ * @return String
*/
- function displaySection( $fields, $sectionName = '' ) {
+ function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
$tableHtml = '';
$subsectionHtml = '';
$hasLeftColumn = false;
: $value->getDefault();
$tableHtml .= $value->getTableRow( $v );
- if ( $value->getLabel() != ' ' )
+ if ( $value->getLabel() != ' ' ) {
$hasLeftColumn = true;
+ }
} elseif ( is_array( $value ) ) {
$section = $this->displaySection( $value, $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";
+ $attributes = array();
+ if ( $fieldsetIDPrefix ) {
+ $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
+ }
+ $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
}
}
$tableHtml = Html::rawElement( 'table', $attribs,
Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
- return $subsectionHtml . "\n" . $tableHtml;
+ if ( $this->mSubSectionBeforeFields ) {
+ return $subsectionHtml . "\n" . $tableHtml;
+ } else {
+ return $tableHtml . "\n" . $subsectionHtml;
+ }
}
/**
public function getLegend( $key ) {
return wfMsg( "{$this->mMessagePrefix}-$key" );
}
+
+ /**
+ * Returns an array of fields in the form
+ *
+ * @return HTMLFormField[]
+ */
+ public function getFlatFields() {
+ return $this->mFlatFields;
+ }
+
+ /**
+ * Returns a value of a field
+ *
+ * @param $field string Field name
+ * @return mixed
+ */
+ public function getVal( $field ) {
+ return $this->mFieldData[$field];
+ }
}
/**
* @return Mixed Bool true on success, or String error to display.
*/
function validate( $value, $alldata ) {
- if ( isset( $this->mValidationCallback ) ) {
- return call_user_func( $this->mValidationCallback, $value, $alldata );
- }
-
if ( isset( $this->mParams['required'] ) && $value === '' ) {
return wfMsgExt( 'htmlform-required', 'parseinline' );
}
+ if ( isset( $this->mValidationCallback ) ) {
+ return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
+ }
+
return true;
}
function filter( $value, $alldata ) {
if ( isset( $this->mFilterCallback ) ) {
- $value = call_user_func( $this->mFilterCallback, $value, $alldata );
+ $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
}
return $value;
/**
* Initialise the object
- * @param $params Associative Array. See HTMLForm doc for syntax.
+ * @param $params array Associative Array. See HTMLForm doc for syntax.
*/
function __construct( $params ) {
$this->mParams = $params;
$helptext = null;
if ( isset( $this->mParams['help-message'] ) ) {
- $msg = $this->mParams['help-message'];
- $helptext = wfMsgExt( $msg, 'parseinline' );
- if ( wfEmptyMsg( $msg ) ) {
- # 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'];
}
return $html;
}
+ /**
+ * Returns the HTML name of the Field
+ *
+ * @return string
+ */
+ public function getName() {
+ return $this->mName;
+ }
+
function getLabel() {
return $this->mLabel;
}
if ( empty( $this->mParams['tooltip'] ) ) {
return array();
}
- return Linker::tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
+ return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
}
/**
/**
* For a checkbox, the label goes on the right hand side, and is
* added in getInputHTML(), rather than HTMLFormField::getRow()
+ * @return String
*/
function getLabel() {
return ' ';
}
// GetCheck won't work like we want for checks.
- if ( $request->getCheck( 'wpEditToken' ) || $this->mParent->getMethod() != 'post' ) {
+ // Fetch the value in either one of the two following case:
+ // - we have a valid token (form got posted or GET forged by the user)
+ // - checkbox name has a value (false or true), ie is not null
+ if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName )!== null ) {
// XOR has the following truth table, which is what we want
// INVERT VALUE | OUTPUT
// true true | false
# If one of the options' 'name' is int(0), it is automatically selected.
# 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 );
}
function __construct( $params ) {
if ( !in_array( 'other', $params['options'], true ) ) {
- $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
+ $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
+ $params['options'][$msg] = 'other';
}
parent::__construct( $params );
# 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. FIXME...
+ # for GET forms.
+ # @todo FIXME...
return $request->getArray( $this->mName, array() );
}
}
/**
* Double field with a dropdown list constructed from a system message in the format
* * Optgroup header
- * ** <option value>|<option name>
- * ** <option value == option name>
+ * ** <option value>
* * New Optgroup header
* 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 {
function __construct( $params ) {
if ( array_key_exists( 'other', $params ) ) {
} elseif( array_key_exists( 'other-message', $params ) ){
- $params['other'] = wfMsg( $params['other-message'] );
+ $params['other'] = wfMessage( $params['other-message'] )->plain();
} else {
- $params['other'] = wfMsg( 'htmlform-selectorother-other' );
+ $params['other'] = null;
}
if ( array_key_exists( 'options', $params ) ) {
# Options array already specified
} elseif( array_key_exists( 'options-message', $params ) ){
# Generate options array from a system message
- $params['options'] = self::parseMessage( wfMsg( $params['options-message'], $params['other'] ) );
+ $params['options'] = self::parseMessage(
+ wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
+ $params['other']
+ );
} else {
# Sulk
throw new MWException( 'HTMLSelectAndOtherField called without any options' );
*/
public static function parseMessage( $string, $otherName=null ) {
if( $otherName === null ){
- $otherName = wfMsg( 'htmlform-selectorother-other' );
+ $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
}
$optgroup = false;
} elseif ( substr( $value, 0, 2) == '**' ) {
# groupmember
$opt = trim( substr( $value, 2 ) );
- $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
- if( count( $parts ) === 1 ){
- $parts[1] = $parts[0];
- }
if( $optgroup === false ){
- $options[$parts[1]] = $parts[0];
+ $options[$opt] = $opt;
} else {
- $options[$optgroup][$parts[1]] = $parts[0];
+ $options[$optgroup][$opt] = $opt;
}
} else {
# groupless reason list
$optgroup = false;
- $parts = array_map( 'trim', explode( '|', $option, 2 ) );
- if( count( $parts ) === 1 ){
- $parts[1] = $parts[0];
- }
- $options[$parts[1]] = $parts[0];
+ $options[$option] = $option;
}
}
} else {
$final = $this->getDefault();
- $list = $text = '';
+
+ $list = 'other';
+ $text = $final;
+ foreach ( $this->mFlatOptions as $option ) {
+ $match = $option . wfMsgForContent( 'colon-separator' );
+ if( strpos( $text, $match ) === 0 ) {
+ $list = $option;
+ $text = substr( $text, strlen( $match ) );
+ break;
+ }
+ }
}
return array( $final, $list, $text );
}
* Radio checkbox fields.
*/
class HTMLRadioField extends HTMLFormField {
+ function __construct( $params ) {
+ parent::__construct( $params );
+ if ( isset( $params['flatlist'] ) ) {
+ $this->mClass .= ' mw-htmlform-radio-flatlist';
+ }
+ }
+
+
function validate( $value, $alldata ) {
$p = parent::validate( $value, $alldata );
/**
* This returns a block of all the radio options, in one cell.
* @see includes/HTMLFormField#getInputHTML()
+ * @param $value String
+ * @return String
*/
function getInputHTML( $value ) {
$html = $this->formatOptions( $this->mParams['options'], $value );
$html .= $this->formatOptions( $info, $value );
} else {
$id = Sanitizer::escapeId( $this->mID . "-$info" );
- $html .= Xml::radio(
+ $radio = Xml::radio(
$this->mName,
$info,
$info == $value,
$attribs + array( 'id' => $id )
);
- $html .= ' ' .
+ $radio .= ' ' .
Html::rawElement( 'label', array( 'for' => $id ), $label );
- $html .= "<br />\n";
+ $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-radio-item' ), $radio );
}
}
/**
* Button cannot be invalid
+ * @param $value String
+ * @param $alldata Array
+ * @return Bool
*/
public function validate( $value, $alldata ){
return true;
}
}
$msg->inContentLanguage();
-
-
+
+
return '<tr><td></td><td class="mw-input">'
. '<div class="mw-editTools">'
. $msg->parseAsBlock()
. "</div></td></tr>\n";
}
}
+
+/**
+ * Dropdown for namespaces
+ */
+class HTMLNamespacesField extends HTMLSelectField {
+ function __construct( $params ) {
+ global $wgContLang;
+ parent::__construct( $params );
+
+ $namespaces = $wgContLang->getFormattedNamespaces();
+
+ $options = array();
+ $options[ wfMessage( 'namespacesall' )->escaped() ] = ''; // TODO: Make an option
+
+ foreach ( $namespaces as $index => $name ) {
+ // Don't include things like SpecialPages
+ if ( $index < NS_MAIN ) {
+ continue;
+ }
+
+ if ( $index === 0 ) {
+ $name = wfMessage( 'blanknamespace' )->escaped();
+ }
+
+ $options[$name] = $index;
+ }
+
+ $this->mParams['options'] = $options;
+ }
+}
+
+/**
+ * Dropdown for protection levels
+ */
+class HTMLRestrictionLevelsField extends HTMLSelectField {
+
+ /**
+ * Should this field be displayed? If it hits a condition where it should
+ * be hidden, set this to false.
+ *
+ * @var bool
+ */
+ protected $enabled = true;
+
+ function __construct( $params ) {
+ global $wgRestrictionLevels;
+ parent::__construct( $params );
+
+ $options = array( wfMsg('restriction-level-all') => 0 ); // Temporary array
+
+ // First pass to load the level names
+ foreach( $wgRestrictionLevels as $type ) {
+ if ( $type != '' && $type != '*' ) {
+ $text = wfMsg("restriction-level-$type");
+ $options[$text] = $type;
+ }
+ }
+
+ // Is there only one level (aside from "all")?
+ if( count($options) <= 2 ) {
+ $this->enabled = false;
+ return;
+ }
+
+ $this->mParams['options'] = $options;
+ }
+
+ /**
+ * Returns false where
+ *
+ * @param $value
+ * @return String
+ */
+ function getTableRow( $value ) {
+ if ( $this->enabled ) {
+ return parent::getTableRow( $value );
+ }
+
+ return '';
+ }
+}
\ No newline at end of file