3 * Base classes for actions done on pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 * @defgroup Actions Action done on pages
27 * Actions are things which can be done to pages (edit, delete, rollback, etc). They
28 * are distinct from Special Pages because an action must apply to exactly one page.
30 * To add an action in an extension, create a subclass of Action, and add the key to
31 * $wgActions. There is also the deprecated UnknownAction hook
33 abstract class Action
{
36 * Page on which we're performing the action
42 * IContextSource if specified; otherwise we'll use the Context from the Page
48 * The fields used to create the HTMLForm
54 * Get the Action subclass which should be used to handle this action, false if
55 * the action is disabled, or null if it's not recognised
56 * @param $action String
57 * @param $overrides Array
58 * @return bool|null|string
60 private final static function getClass( $action, array $overrides ) {
62 $action = strtolower( $action );
64 if ( !isset( $wgActions[$action] ) ) {
68 if ( $wgActions[$action] === false ) {
70 } elseif ( $wgActions[$action] === true && isset( $overrides[$action] ) ) {
71 return $overrides[$action];
72 } elseif ( $wgActions[$action] === true ) {
73 return ucfirst( $action ) . 'Action';
75 return $wgActions[$action];
80 * Get an appropriate Action subclass for the given action
81 * @param $action String
83 * @param $context IContextSource
84 * @return Action|bool|null false if the action is disabled, null
85 * if it is not recognised
87 public final static function factory( $action, Page
$page, IContextSource
$context = null ) {
88 $class = self
::getClass( $action, $page->getActionOverrides() );
90 $obj = new $class( $page, $context );
97 * Get the action that will be executed, not necessarily the one passed
98 * passed through the "action" request parameter. Actions disabled in
99 * $wgActions will be replaced by "nosuchaction".
102 * @param $context IContextSource
103 * @return string: action name
105 public final static function getActionName( IContextSource
$context ) {
108 $request = $context->getRequest();
109 $actionName = $request->getVal( 'action', 'view' );
111 // Check for disabled actions
112 if ( isset( $wgActions[$actionName] ) && $wgActions[$actionName] === false ) {
113 $actionName = 'nosuchaction';
116 // Workaround for bug #20966: inability of IE to provide an action dependent
117 // on which submit button is clicked.
118 if ( $actionName === 'historysubmit' ) {
119 if ( $request->getBool( 'revisiondelete' ) ) {
120 $actionName = 'revisiondelete';
122 $actionName = 'view';
124 } elseif ( $actionName == 'editredlink' ) {
125 $actionName = 'edit';
128 // Trying to get a WikiPage for NS_SPECIAL etc. will result
129 // in WikiPage::factory throwing "Invalid or virtual namespace -1 given."
130 // For SpecialPages et al, default to action=view.
131 if ( !$context->canUseWikiPage() ) {
135 $action = Action
::factory( $actionName, $context->getWikiPage() );
136 if ( $action instanceof Action
) {
137 return $action->getName();
140 return 'nosuchaction';
144 * Check if a given action is recognised, even if it's disabled
146 * @param $name String: name of an action
149 public final static function exists( $name ) {
150 return self
::getClass( $name, array() ) !== null;
154 * Get the IContextSource in use here
155 * @return IContextSource
157 public final function getContext() {
158 if ( $this->context
instanceof IContextSource
) {
159 return $this->context
;
161 return $this->page
->getContext();
165 * Get the WebRequest being used for this instance
169 public final function getRequest() {
170 return $this->getContext()->getRequest();
174 * Get the OutputPage being used for this instance
178 public final function getOutput() {
179 return $this->getContext()->getOutput();
183 * Shortcut to get the User being used for this instance
187 public final function getUser() {
188 return $this->getContext()->getUser();
192 * Shortcut to get the Skin being used for this instance
196 public final function getSkin() {
197 return $this->getContext()->getSkin();
201 * Shortcut to get the user Language being used for this instance
205 public final function getLanguage() {
206 return $this->getContext()->getLanguage();
210 * Shortcut to get the user Language being used for this instance
212 * @deprecated 1.19 Use getLanguage instead
215 public final function getLang() {
216 wfDeprecated( __METHOD__
, '1.19' );
217 return $this->getLanguage();
221 * Shortcut to get the Title object from the page
224 public final function getTitle() {
225 return $this->page
->getTitle();
229 * Get a Message object with context set
230 * Parameters are the same as wfMessage()
232 * @return Message object
234 public final function msg() {
235 $params = func_get_args();
236 return call_user_func_array( array( $this->getContext(), 'msg' ), $params );
240 * Protected constructor: use Action::factory( $action, $page ) to actually build
241 * these things in the real world
243 * @param $context IContextSource
245 protected function __construct( Page
$page, IContextSource
$context = null ) {
247 $this->context
= $context;
251 * Return the name of the action this object responds to
252 * @return String lowercase
254 public abstract function getName();
257 * Get the permission required to perform this action. Often, but not always,
258 * the same as the action name
259 * @return String|null
261 public function getRestriction() {
266 * Checks if the given user (identified by an object) can perform this action. Can be
267 * overridden by sub-classes with more complicated permissions schemes. Failures here
268 * must throw subclasses of ErrorPageError
270 * @param $user User: the user to check, or null to use the context user
271 * @throws ErrorPageError
272 * @return bool True on success
274 protected function checkCanExecute( User
$user ) {
275 $right = $this->getRestriction();
276 if ( $right !== null ) {
277 $errors = $this->getTitle()->getUserPermissionsErrors( $right, $user );
278 if ( count( $errors ) ) {
279 throw new PermissionsError( $right, $errors );
283 if ( $this->requiresUnblock() && $user->isBlocked() ) {
284 $block = $user->getBlock();
285 throw new UserBlockedError( $block );
288 // This should be checked at the end so that the user won't think the
289 // error is only temporary when he also don't have the rights to execute
291 if ( $this->requiresWrite() && wfReadOnly() ) {
292 throw new ReadOnlyError();
298 * Whether this action requires the wiki not to be locked
301 public function requiresWrite() {
306 * Whether this action can still be executed by a blocked user
309 public function requiresUnblock() {
314 * Set output headers for noindexing etc. This function will not be called through
315 * the execute() entry point, so only put UI-related stuff in here.
317 protected function setHeaders() {
318 $out = $this->getOutput();
319 $out->setRobotPolicy( "noindex,nofollow" );
320 $out->setPageTitle( $this->getPageTitle() );
321 $this->getOutput()->setSubtitle( $this->getDescription() );
322 $out->setArticleRelated( true );
326 * Returns the name that goes in the \<h1\> page title
330 protected function getPageTitle() {
331 return $this->getTitle()->getPrefixedText();
335 * Returns the description that goes below the \<h1\> tag
339 protected function getDescription() {
340 return wfMsgHtml( strtolower( $this->getName() ) );
344 * The main action entry point. Do all output for display and send it to the context
345 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
346 * $this->getOutput(), etc.
347 * @throws ErrorPageError
349 public abstract function show();
352 * Execute the action in a silent fashion: do not display anything or release any errors.
353 * @return Bool whether execution was successful
355 public abstract function execute();
358 abstract class FormAction
extends Action
{
361 * Get an HTMLForm descriptor array
364 protected abstract function getFormFields();
367 * Add pre- or post-text to the form
368 * @return String HTML which will be sent to $form->addPreText()
370 protected function preText() { return ''; }
375 protected function postText() { return ''; }
378 * Play with the HTMLForm if you need to more substantially
379 * @param $form HTMLForm
381 protected function alterForm( HTMLForm
$form ) {}
384 * Get the HTMLForm to control behaviour
385 * @return HTMLForm|null
387 protected function getForm() {
388 $this->fields
= $this->getFormFields();
390 // Give hooks a chance to alter the form, adding extra fields or text etc
391 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields
, $this->page
) );
393 $form = new HTMLForm( $this->fields
, $this->getContext() );
394 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
396 // Retain query parameters (uselang etc)
397 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
398 $params = array_diff_key(
399 $this->getRequest()->getQueryValues(),
400 array( 'action' => null, 'title' => null )
402 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
404 $form->addPreText( $this->preText() );
405 $form->addPostText( $this->postText() );
406 $this->alterForm( $form );
408 // Give hooks a chance to alter the form, adding extra fields or text etc
409 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page
) );
415 * Process the form on POST submission. If you return false from getFormFields(),
416 * this will obviously never be reached. If you don't want to do anything with the
417 * form, just return false here
419 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
421 public abstract function onSubmit( $data );
424 * Do something exciting on successful processing of the form. This might be to show
425 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
428 public abstract function onSuccess();
431 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
432 * some stuff underneath (history etc); to do some processing on submission of that
433 * form (delete, protect, etc) and to do something exciting on 'success', be that
434 * display something new or redirect to somewhere. Some actions have more exotic
435 * behaviour, but that's what subclassing is for :D
437 public function show() {
440 // This will throw exceptions if there's a problem
441 $this->checkCanExecute( $this->getUser() );
443 $form = $this->getForm();
444 if ( $form->show() ) {
450 * @see Action::execute()
451 * @throws ErrorPageError
452 * @param array|null $data
453 * @param bool $captureErrors
456 public function execute( array $data = null, $captureErrors = true ) {
458 // Set a new context so output doesn't leak.
459 $this->context
= clone $this->page
->getContext();
461 // This will throw exceptions if there's a problem
462 $this->checkCanExecute( $this->getUser() );
465 foreach ( $this->fields
as $key => $params ) {
466 if ( isset( $data[$key] ) ) {
467 $fields[$key] = $data[$key];
468 } elseif ( isset( $params['default'] ) ) {
469 $fields[$key] = $params['default'];
471 $fields[$key] = null;
474 $status = $this->onSubmit( $fields );
475 if ( $status === true ) {
476 // This might do permanent stuff
483 catch ( ErrorPageError
$e ) {
484 if ( $captureErrors ) {
494 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
495 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
498 abstract class FormlessAction
extends Action
{
501 * Show something on GET request.
502 * @return String|null will be added to the HTMLForm if present, or just added to the
503 * output if not. Return null to not add anything
505 public abstract function onView();
508 * We don't want an HTMLForm
511 protected function getFormFields() {
515 public function onSubmit( $data ) {
519 public function onSuccess() {
523 public function show() {
526 // This will throw exceptions if there's a problem
527 $this->checkCanExecute( $this->getUser() );
529 $this->getOutput()->addHTML( $this->onView() );
533 * Execute the action silently, not giving any output. Since these actions don't have
534 * forms, they probably won't have any data, but some (eg rollback) may do
535 * @param $data Array values that would normally be in the GET request
536 * @param $captureErrors Bool whether to catch exceptions and just return false
537 * @return Bool whether execution was successful
539 public function execute( array $data = null, $captureErrors = true ) {
541 // Set a new context so output doesn't leak.
542 $this->context
= clone $this->page
->getContext();
543 if ( is_array( $data ) ) {
544 $this->context
->setRequest( new FauxRequest( $data, false ) );
547 // This will throw exceptions if there's a problem
548 $this->checkCanExecute( $this->getUser() );
553 catch ( ErrorPageError
$e ) {
554 if ( $captureErrors ) {