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 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
34 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
35 * patrol, etc). The FormAction and FormlessAction classes represent these two groups.
37 abstract class Action
{
40 * Page on which we're performing the action
41 * @var WikiPage|Article|ImagePage|CategoryPage|Page $page
46 * IContextSource if specified; otherwise we'll use the Context from the Page
47 * @var IContextSource $context
52 * The fields used to create the HTMLForm
58 * Get the Action subclass which should be used to handle this action, false if
59 * the action is disabled, or null if it's not recognised
60 * @param $action String
61 * @param $overrides Array
62 * @return bool|null|string|callable
64 final private static function getClass( $action, array $overrides ) {
66 $action = strtolower( $action );
68 if ( !isset( $wgActions[$action] ) ) {
72 if ( $wgActions[$action] === false ) {
74 } elseif ( $wgActions[$action] === true && isset( $overrides[$action] ) ) {
75 return $overrides[$action];
76 } elseif ( $wgActions[$action] === true ) {
77 return ucfirst( $action ) . 'Action';
79 return $wgActions[$action];
84 * Get an appropriate Action subclass for the given action
85 * @param $action String
87 * @param $context IContextSource
88 * @return Action|bool|null false if the action is disabled, null
89 * if it is not recognised
91 final public static function factory( $action, Page
$page, IContextSource
$context = null ) {
92 $classOrCallable = self
::getClass( $action, $page->getActionOverrides() );
94 if ( is_string( $classOrCallable ) ) {
95 $obj = new $classOrCallable( $page, $context );
99 if ( is_callable( $classOrCallable ) ) {
100 return call_user_func_array( $classOrCallable, array( $page, $context ) );
103 return $classOrCallable;
107 * Get the action that will be executed, not necessarily the one passed
108 * passed through the "action" request parameter. Actions disabled in
109 * $wgActions will be replaced by "nosuchaction".
112 * @param $context IContextSource
113 * @return string: action name
115 final public static function getActionName( IContextSource
$context ) {
118 $request = $context->getRequest();
119 $actionName = $request->getVal( 'action', 'view' );
121 // Check for disabled actions
122 if ( isset( $wgActions[$actionName] ) && $wgActions[$actionName] === false ) {
123 $actionName = 'nosuchaction';
126 // Workaround for bug #20966: inability of IE to provide an action dependent
127 // on which submit button is clicked.
128 if ( $actionName === 'historysubmit' ) {
129 if ( $request->getBool( 'revisiondelete' ) ) {
130 $actionName = 'revisiondelete';
132 $actionName = 'view';
134 } elseif ( $actionName == 'editredlink' ) {
135 $actionName = 'edit';
138 // Trying to get a WikiPage for NS_SPECIAL etc. will result
139 // in WikiPage::factory throwing "Invalid or virtual namespace -1 given."
140 // For SpecialPages et al, default to action=view.
141 if ( !$context->canUseWikiPage() ) {
145 $action = Action
::factory( $actionName, $context->getWikiPage() );
146 if ( $action instanceof Action
) {
147 return $action->getName();
150 return 'nosuchaction';
154 * Check if a given action is recognised, even if it's disabled
156 * @param string $name name of an action
159 final public static function exists( $name ) {
160 return self
::getClass( $name, array() ) !== null;
164 * Get the IContextSource in use here
165 * @return IContextSource
167 final public function getContext() {
168 if ( $this->context
instanceof IContextSource
) {
169 return $this->context
;
171 return $this->page
->getContext();
175 * Get the WebRequest being used for this instance
179 final public function getRequest() {
180 return $this->getContext()->getRequest();
184 * Get the OutputPage being used for this instance
188 final public function getOutput() {
189 return $this->getContext()->getOutput();
193 * Shortcut to get the User being used for this instance
197 final public function getUser() {
198 return $this->getContext()->getUser();
202 * Shortcut to get the Skin being used for this instance
206 final public function getSkin() {
207 return $this->getContext()->getSkin();
211 * Shortcut to get the user Language being used for this instance
215 final public function getLanguage() {
216 return $this->getContext()->getLanguage();
220 * Shortcut to get the user Language being used for this instance
222 * @deprecated since 1.19 Use getLanguage instead
225 final public function getLang() {
226 wfDeprecated( __METHOD__
, '1.19' );
227 return $this->getLanguage();
231 * Shortcut to get the Title object from the page
234 final public function getTitle() {
235 return $this->page
->getTitle();
239 * Get a Message object with context set
240 * Parameters are the same as wfMessage()
242 * @return Message object
244 final public function msg() {
245 $params = func_get_args();
246 return call_user_func_array( array( $this->getContext(), 'msg' ), $params );
252 * Only public since 1.21
255 * @param $context IContextSource
257 public function __construct( Page
$page, IContextSource
$context = null ) {
259 $this->context
= $context;
263 * Return the name of the action this object responds to
264 * @return String lowercase
266 abstract public function getName();
269 * Get the permission required to perform this action. Often, but not always,
270 * the same as the action name
271 * @return String|null
273 public function getRestriction() {
278 * Checks if the given user (identified by an object) can perform this action. Can be
279 * overridden by sub-classes with more complicated permissions schemes. Failures here
280 * must throw subclasses of ErrorPageError
282 * @param $user User: the user to check, or null to use the context user
283 * @throws UserBlockedError|ReadOnlyError|PermissionsError
284 * @return bool True on success
286 protected function checkCanExecute( User
$user ) {
287 $right = $this->getRestriction();
288 if ( $right !== null ) {
289 $errors = $this->getTitle()->getUserPermissionsErrors( $right, $user );
290 if ( count( $errors ) ) {
291 throw new PermissionsError( $right, $errors );
295 if ( $this->requiresUnblock() && $user->isBlocked() ) {
296 $block = $user->getBlock();
297 throw new UserBlockedError( $block );
300 // This should be checked at the end so that the user won't think the
301 // error is only temporary when he also don't have the rights to execute
303 if ( $this->requiresWrite() && wfReadOnly() ) {
304 throw new ReadOnlyError();
310 * Whether this action requires the wiki not to be locked
313 public function requiresWrite() {
318 * Whether this action can still be executed by a blocked user
321 public function requiresUnblock() {
326 * Set output headers for noindexing etc. This function will not be called through
327 * the execute() entry point, so only put UI-related stuff in here.
329 protected function setHeaders() {
330 $out = $this->getOutput();
331 $out->setRobotPolicy( "noindex,nofollow" );
332 $out->setPageTitle( $this->getPageTitle() );
333 $this->getOutput()->setSubtitle( $this->getDescription() );
334 $out->setArticleRelated( true );
338 * Returns the name that goes in the \<h1\> page title
342 protected function getPageTitle() {
343 return $this->getTitle()->getPrefixedText();
347 * Returns the description that goes below the \<h1\> tag
351 protected function getDescription() {
352 return $this->msg( strtolower( $this->getName() ) )->escaped();
356 * The main action entry point. Do all output for display and send it to the context
357 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
358 * $this->getOutput(), etc.
359 * @throws ErrorPageError
361 abstract public function show();
364 * Execute the action in a silent fashion: do not display anything or release any errors.
365 * @return Bool whether execution was successful
367 abstract public function execute();
371 * An action which shows a form and does something based on the input from the form
373 abstract class FormAction
extends Action
{
376 * Get an HTMLForm descriptor array
379 abstract protected function getFormFields();
382 * Add pre- or post-text to the form
383 * @return String HTML which will be sent to $form->addPreText()
385 protected function preText() {
392 protected function postText() {
397 * Play with the HTMLForm if you need to more substantially
398 * @param $form HTMLForm
400 protected function alterForm( HTMLForm
$form ) {
404 * Get the HTMLForm to control behavior
405 * @return HTMLForm|null
407 protected function getForm() {
408 $this->fields
= $this->getFormFields();
410 // Give hooks a chance to alter the form, adding extra fields or text etc
411 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields
, $this->page
) );
413 $form = new HTMLForm( $this->fields
, $this->getContext(), $this->getName() );
414 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
416 // Retain query parameters (uselang etc)
417 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
418 $params = array_diff_key(
419 $this->getRequest()->getQueryValues(),
420 array( 'action' => null, 'title' => null )
422 $form->addHiddenField( 'redirectparams', wfArrayToCgi( $params ) );
424 $form->addPreText( $this->preText() );
425 $form->addPostText( $this->postText() );
426 $this->alterForm( $form );
428 // Give hooks a chance to alter the form, adding extra fields or text etc
429 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page
) );
435 * Process the form on POST submission. If you return false from getFormFields(),
436 * this will obviously never be reached. If you don't want to do anything with the
437 * form, just return false here
439 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
441 abstract public function onSubmit( $data );
444 * Do something exciting on successful processing of the form. This might be to show
445 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
448 abstract public function onSuccess();
451 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
452 * some stuff underneath (history etc); to do some processing on submission of that
453 * form (delete, protect, etc) and to do something exciting on 'success', be that
454 * display something new or redirect to somewhere. Some actions have more exotic
455 * behavior, but that's what subclassing is for :D
457 public function show() {
460 // This will throw exceptions if there's a problem
461 $this->checkCanExecute( $this->getUser() );
463 $form = $this->getForm();
464 if ( $form->show() ) {
470 * @see Action::execute()
472 * @param $data array|null
473 * @param $captureErrors bool
474 * @throws ErrorPageError|Exception
477 public function execute( array $data = null, $captureErrors = true ) {
479 // Set a new context so output doesn't leak.
480 $this->context
= clone $this->page
->getContext();
482 // This will throw exceptions if there's a problem
483 $this->checkCanExecute( $this->getUser() );
486 foreach ( $this->fields
as $key => $params ) {
487 if ( isset( $data[$key] ) ) {
488 $fields[$key] = $data[$key];
489 } elseif ( isset( $params['default'] ) ) {
490 $fields[$key] = $params['default'];
492 $fields[$key] = null;
495 $status = $this->onSubmit( $fields );
496 if ( $status === true ) {
497 // This might do permanent stuff
504 catch ( ErrorPageError
$e ) {
505 if ( $captureErrors ) {
515 * An action which just does something, without showing a form first.
517 abstract class FormlessAction
extends Action
{
520 * Show something on GET request.
521 * @return String|null will be added to the HTMLForm if present, or just added to the
522 * output if not. Return null to not add anything
524 abstract public function onView();
527 * We don't want an HTMLForm
530 protected function getFormFields() {
538 public function onSubmit( $data ) {
545 public function onSuccess() {
549 public function show() {
552 // This will throw exceptions if there's a problem
553 $this->checkCanExecute( $this->getUser() );
555 $this->getOutput()->addHTML( $this->onView() );
559 * Execute the action silently, not giving any output. Since these actions don't have
560 * forms, they probably won't have any data, but some (eg rollback) may do
561 * @param array $data values that would normally be in the GET request
562 * @param bool $captureErrors whether to catch exceptions and just return false
563 * @throws ErrorPageError|Exception
564 * @return Bool whether execution was successful
566 public function execute( array $data = null, $captureErrors = true ) {
568 // Set a new context so output doesn't leak.
569 $this->context
= clone $this->page
->getContext();
570 if ( is_array( $data ) ) {
571 $this->context
->setRequest( new FauxRequest( $data, false ) );
574 // This will throw exceptions if there's a problem
575 $this->checkCanExecute( $this->getUser() );
580 catch ( ErrorPageError
$e ) {
581 if ( $captureErrors ) {