correct typo in r102393
[mediawiki.git] / includes / Action.php
blob22879410a53fc9529dce7a9ce6988b762984b078
1 <?php
2 /**
3 * Actions are things which can be done to pages (edit, delete, rollback, etc). They
4 * are distinct from Special Pages because an action must apply to exactly one page.
6 * To add an action in an extension, create a subclass of Action, and add the key to
7 * $wgActions. There is also the deprecated UnknownAction hook
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 * @file
26 abstract class Action {
28 /**
29 * Page on which we're performing the action
30 * @var Article
32 protected $page;
34 /**
35 * IContextSource if specified; otherwise we'll use the Context from the Page
36 * @var IContextSource
38 protected $context;
40 /**
41 * The fields used to create the HTMLForm
42 * @var Array
44 protected $fields;
46 /**
47 * Get the Action subclass which should be used to handle this action, false if
48 * the action is disabled, or null if it's not recognised
49 * @param $action String
50 * @param $overrides Array
51 * @return bool|null|string
53 private final static function getClass( $action, array $overrides ) {
54 global $wgActions;
55 $action = strtolower( $action );
57 if ( !isset( $wgActions[$action] ) ) {
58 return null;
61 if ( $wgActions[$action] === false ) {
62 return false;
63 } elseif ( $wgActions[$action] === true && isset( $overrides[$action] ) ) {
64 return $overrides[$action];
65 } elseif ( $wgActions[$action] === true ) {
66 return ucfirst( $action ) . 'Action';
67 } else {
68 return $wgActions[$action];
72 /**
73 * Get an appropriate Action subclass for the given action
74 * @param $action String
75 * @param $page Article
76 * @return Action|false|null false if the action is disabled, null
77 * if it is not recognised
79 public final static function factory( $action, Page $page ) {
80 $class = self::getClass( $action, $page->getActionOverrides() );
81 if ( $class ) {
82 $obj = new $class( $page );
83 return $obj;
85 return $class;
88 /**
89 * Check if a given action is recognised, even if it's disabled
91 * @param $name String: name of an action
92 * @return Bool
94 public final static function exists( $name ) {
95 return self::getClass( $name, array() ) !== null;
98 /**
99 * Get the IContextSource in use here
100 * @return IContextSource
102 public final function getContext() {
103 if ( $this->context instanceof IContextSource ) {
104 return $this->context;
106 return $this->page->getContext();
110 * Get the WebRequest being used for this instance
112 * @return WebRequest
114 public final function getRequest() {
115 return $this->getContext()->getRequest();
119 * Get the OutputPage being used for this instance
121 * @return OutputPage
123 public final function getOutput() {
124 return $this->getContext()->getOutput();
128 * Shortcut to get the User being used for this instance
130 * @return User
132 public final function getUser() {
133 return $this->getContext()->getUser();
137 * Shortcut to get the Skin being used for this instance
139 * @return Skin
141 public final function getSkin() {
142 return $this->getContext()->getSkin();
146 * Shortcut to get the user Language being used for this instance
148 * @return Skin
150 public final function getLang() {
151 return $this->getContext()->getLang();
155 * Shortcut to get the Title object from the page
156 * @return Title
158 public final function getTitle() {
159 return $this->page->getTitle();
163 * Get a Message object with context set
164 * Parameters are the same as wfMessage()
166 * @return Message object
168 public final function msg() {
169 $params = func_get_args();
170 return call_user_func_array( array( $this->getContext(), 'msg' ), $params );
174 * Protected constructor: use Action::factory( $action, $page ) to actually build
175 * these things in the real world
176 * @param Page $page
178 protected function __construct( Page $page ) {
179 $this->page = $page;
183 * Return the name of the action this object responds to
184 * @return String lowercase
186 public abstract function getName();
189 * Get the permission required to perform this action. Often, but not always,
190 * the same as the action name
192 public abstract function getRestriction();
195 * Checks if the given user (identified by an object) can perform this action. Can be
196 * overridden by sub-classes with more complicated permissions schemes. Failures here
197 * must throw subclasses of ErrorPageError
199 * @param $user User: the user to check, or null to use the context user
200 * @throws ErrorPageError
202 protected function checkCanExecute( User $user ) {
203 $right = $this->getRestriction();
204 if ( $right !== null ) {
205 $errors = $this->getTitle()->getUserPermissionsErrors( $right, $user );
206 if ( count( $errors ) ) {
207 throw new PermissionsError( $right, $errors );
211 if ( $this->requiresUnblock() && $user->isBlocked() ) {
212 $block = $user->mBlock;
213 throw new UserBlockedError( $block );
216 // This should be checked at the end so that the user won't think the
217 // error is only temporary when he also don't have the rights to execute
218 // this action
219 if ( $this->requiresWrite() && wfReadOnly() ) {
220 throw new ReadOnlyError();
225 * Whether this action requires the wiki not to be locked
226 * @return Bool
228 public function requiresWrite() {
229 return true;
233 * Whether this action can still be executed by a blocked user
234 * @return Bool
236 public function requiresUnblock() {
237 return true;
241 * Set output headers for noindexing etc. This function will not be called through
242 * the execute() entry point, so only put UI-related stuff in here.
244 protected function setHeaders() {
245 $out = $this->getOutput();
246 $out->setRobotPolicy( "noindex,nofollow" );
247 $out->setPageTitle( $this->getPageTitle() );
248 $this->getOutput()->setSubtitle( $this->getDescription() );
249 $out->setArticleRelated( true );
253 * Returns the name that goes in the \<h1\> page title
255 * @return String
257 protected function getPageTitle() {
258 return $this->getTitle()->getPrefixedText();
262 * Returns the description that goes below the \<h1\> tag
264 * @return String
266 protected function getDescription() {
267 return wfMsg( strtolower( $this->getName() ) );
271 * The main action entry point. Do all output for display and send it to the context
272 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
273 * $this->getOutput(), etc.
274 * @throws ErrorPageError
276 public abstract function show();
279 * Execute the action in a silent fashion: do not display anything or release any errors.
280 * @param $data Array values that would normally be in the POST request
281 * @param $captureErrors Bool whether to catch exceptions and just return false
282 * @return Bool whether execution was successful
284 public abstract function execute();
287 abstract class FormAction extends Action {
290 * Get an HTMLForm descriptor array
291 * @return Array
293 protected abstract function getFormFields();
296 * Add pre- or post-text to the form
297 * @return String HTML which will be sent to $form->addPreText()
299 protected function preText() { return ''; }
302 * @return string
304 protected function postText() { return ''; }
307 * Play with the HTMLForm if you need to more substantially
308 * @param $form HTMLForm
310 protected function alterForm( HTMLForm $form ) {}
313 * Get the HTMLForm to control behaviour
314 * @return HTMLForm|null
316 protected function getForm() {
317 $this->fields = $this->getFormFields();
319 // Give hooks a chance to alter the form, adding extra fields or text etc
320 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields, $this->page ) );
322 $form = new HTMLForm( $this->fields, $this->getContext() );
323 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
325 // Retain query parameters (uselang etc)
326 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
327 $params = array_diff_key(
328 $this->getRequest()->getQueryValues(),
329 array( 'action' => null, 'title' => null )
331 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
333 $form->addPreText( $this->preText() );
334 $form->addPostText( $this->postText() );
335 $this->alterForm( $form );
337 // Give hooks a chance to alter the form, adding extra fields or text etc
338 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page ) );
340 return $form;
344 * Process the form on POST submission. If you return false from getFormFields(),
345 * this will obviously never be reached. If you don't want to do anything with the
346 * form, just return false here
347 * @param $data Array
348 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
350 public abstract function onSubmit( $data );
353 * Do something exciting on successful processing of the form. This might be to show
354 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
355 * protect, etc).
357 public abstract function onSuccess();
360 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
361 * some stuff underneath (history etc); to do some processing on submission of that
362 * form (delete, protect, etc) and to do something exciting on 'success', be that
363 * display something new or redirect to somewhere. Some actions have more exotic
364 * behaviour, but that's what subclassing is for :D
366 public function show() {
367 $this->setHeaders();
369 // This will throw exceptions if there's a problem
370 $this->checkCanExecute( $this->getUser() );
372 $form = $this->getForm();
373 if ( $form->show() ) {
374 $this->onSuccess();
379 * @see Action::execute()
380 * @throws ErrorPageError
381 * @param array|null $data
382 * @param bool $captureErrors
383 * @return bool
385 public function execute( array $data = null, $captureErrors = true ) {
386 try {
387 // Set a new context so output doesn't leak.
388 $this->context = clone $this->page->getContext();
390 // This will throw exceptions if there's a problem
391 $this->checkCanExecute( $this->getUser() );
393 $fields = array();
394 foreach ( $this->fields as $key => $params ) {
395 if ( isset( $data[$key] ) ) {
396 $fields[$key] = $data[$key];
397 } elseif ( isset( $params['default'] ) ) {
398 $fields[$key] = $params['default'];
399 } else {
400 $fields[$key] = null;
403 $status = $this->onSubmit( $fields );
404 if ( $status === true ) {
405 // This might do permanent stuff
406 $this->onSuccess();
407 return true;
408 } else {
409 return false;
412 catch ( ErrorPageError $e ) {
413 if ( $captureErrors ) {
414 return false;
415 } else {
416 throw $e;
423 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
424 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
425 * patrol, etc).
427 abstract class FormlessAction extends Action {
430 * Show something on GET request.
431 * @return String|null will be added to the HTMLForm if present, or just added to the
432 * output if not. Return null to not add anything
434 public abstract function onView();
437 * We don't want an HTMLForm
439 protected function getFormFields() {
440 return false;
443 public function onSubmit( $data ) {
444 return false;
447 public function onSuccess() {
448 return false;
451 public function show() {
452 $this->setHeaders();
454 // This will throw exceptions if there's a problem
455 $this->checkCanExecute( $this->getUser() );
457 $this->getOutput()->addHTML( $this->onView() );
461 * Execute the action silently, not giving any output. Since these actions don't have
462 * forms, they probably won't have any data, but some (eg rollback) may do
463 * @param $data Array values that would normally be in the GET request
464 * @param $captureErrors Bool whether to catch exceptions and just return false
465 * @return Bool whether execution was successful
467 public function execute( array $data = null, $captureErrors = true ) {
468 try {
469 // Set a new context so output doesn't leak.
470 $this->context = clone $this->page->getContext();
471 if ( is_array( $data ) ) {
472 $this->context->setRequest( new FauxRequest( $data, false ) );
475 // This will throw exceptions if there's a problem
476 $this->checkCanExecute( $this->getUser() );
478 $this->onView();
479 return true;
481 catch ( ErrorPageError $e ) {
482 if ( $captureErrors ) {
483 return false;
484 } else {
485 throw $e;