Removed raw Article->field accessing
[mediawiki.git] / includes / Action.php
blobde600844287e6d788a88ce641d39e479756aa3d5
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 * RequestContext if specified; otherwise we'll use the Context from the Page
36 * @var RequestContext
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 * @return bool|null|string
52 private final static function getClass( $action ) {
53 global $wgActions;
54 $action = strtolower( $action );
56 if ( !isset( $wgActions[$action] ) ) {
57 return null;
60 if ( $wgActions[$action] === false ) {
61 return false;
62 } elseif ( $wgActions[$action] === true ) {
63 return ucfirst( $action ) . 'Action';
64 } else {
65 return $wgActions[$action];
69 /**
70 * Get an appropriate Action subclass for the given action
71 * @param $action String
72 * @param $page Article
73 * @return Action|false|null false if the action is disabled, null
74 * if it is not recognised
76 public final static function factory( $action, Article $page ) {
77 $class = self::getClass( $action );
78 if ( $class ) {
79 $obj = new $class( $page );
80 return $obj;
82 return $class;
85 /**
86 * Check if a given action is recognised, even if it's disabled
88 * @param $name String: name of an action
89 * @return Bool
91 public final static function exists( $name ) {
92 return self::getClass( $name ) !== null;
95 /**
96 * Get the RequestContext in use here
97 * @return RequestContext
99 protected final function getContext() {
100 if ( $this->context instanceof RequestContext ) {
101 return $this->context;
103 return $this->page->getContext();
107 * Get the WebRequest being used for this instance
109 * @return WebRequest
111 protected final function getRequest() {
112 return $this->getContext()->getRequest();
116 * Get the OutputPage being used for this instance
118 * @return OutputPage
120 protected final function getOutput() {
121 return $this->getContext()->getOutput();
125 * Shortcut to get the User being used for this instance
127 * @return User
129 protected final function getUser() {
130 return $this->getContext()->getUser();
134 * Shortcut to get the Skin being used for this instance
136 * @return Skin
138 protected final function getSkin() {
139 return $this->getContext()->getSkin();
143 * Shortcut to get the user Language being used for this instance
145 * @return Skin
147 protected final function getLang() {
148 return $this->getContext()->getLang();
152 * Shortcut to get the Title object from the page
153 * @return Title
155 protected final function getTitle() {
156 return $this->page->getTitle();
160 * Protected constructor: use Action::factory( $action, $page ) to actually build
161 * these things in the real world
162 * @param Article $page
164 protected function __construct( Article $page ) {
165 $this->page = $page;
169 * Return the name of the action this object responds to
170 * @return String lowercase
172 public abstract function getName();
175 * Get the permission required to perform this action. Often, but not always,
176 * the same as the action name
178 public abstract function getRestriction();
181 * Checks if the given user (identified by an object) can perform this action. Can be
182 * overridden by sub-classes with more complicated permissions schemes. Failures here
183 * must throw subclasses of ErrorPageError
185 * @param $user User: the user to check, or null to use the context user
186 * @throws ErrorPageError
188 protected function checkCanExecute( User $user ) {
189 if ( $this->requiresWrite() && wfReadOnly() ) {
190 throw new ReadOnlyError();
193 if ( $this->getRestriction() !== null && !$user->isAllowed( $this->getRestriction() ) ) {
194 throw new PermissionsError( $this->getRestriction() );
197 if ( $this->requiresUnblock() && $user->isBlocked() ) {
198 $block = $user->mBlock;
199 throw new UserBlockedError( $block );
204 * Whether this action requires the wiki not to be locked
205 * @return Bool
207 public function requiresWrite() {
208 return true;
212 * Whether this action can still be executed by a blocked user
213 * @return Bool
215 public function requiresUnblock() {
216 return true;
220 * Set output headers for noindexing etc. This function will not be called through
221 * the execute() entry point, so only put UI-related stuff in here.
223 protected function setHeaders() {
224 $out = $this->getOutput();
225 $out->setRobotPolicy( "noindex,nofollow" );
226 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
227 $this->getOutput()->setSubtitle( $this->getDescription() );
228 $out->setArticleRelated( true );
232 * Returns the name that goes in the \<h1\> page title
234 * @return String
236 protected function getDescription() {
237 return wfMsg( strtolower( $this->getName() ) );
241 * The main action entry point. Do all output for display and send it to the context
242 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
243 * $this->getOutput(), etc.
244 * @throws ErrorPageError
246 public abstract function show();
249 * Execute the action in a silent fashion: do not display anything or release any errors.
250 * @param $data Array values that would normally be in the POST request
251 * @param $captureErrors Bool whether to catch exceptions and just return false
252 * @return Bool whether execution was successful
254 public abstract function execute();
257 abstract class FormAction extends Action {
260 * Get an HTMLForm descriptor array
261 * @return Array
263 protected abstract function getFormFields();
266 * Add pre- or post-text to the form
267 * @return String HTML which will be sent to $form->addPreText()
269 protected function preText() { return ''; }
270 protected function postText() { return ''; }
273 * Play with the HTMLForm if you need to more substantially
274 * @param $form HTMLForm
276 protected function alterForm( HTMLForm $form ) {}
279 * Get the HTMLForm to control behaviour
280 * @return HTMLForm|null
282 protected function getForm() {
283 $this->fields = $this->getFormFields();
285 // Give hooks a chance to alter the form, adding extra fields or text etc
286 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields, $this->page ) );
288 $form = new HTMLForm( $this->fields, $this->getContext() );
289 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
291 // Retain query parameters (uselang etc)
292 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
293 $params = array_diff_key(
294 $this->getRequest()->getQueryValues(),
295 array( 'action' => null, 'title' => null )
297 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
299 $form->addPreText( $this->preText() );
300 $form->addPostText( $this->postText() );
301 $this->alterForm( $form );
303 // Give hooks a chance to alter the form, adding extra fields or text etc
304 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page ) );
306 return $form;
310 * Process the form on POST submission. If you return false from getFormFields(),
311 * this will obviously never be reached. If you don't want to do anything with the
312 * form, just return false here
313 * @param $data Array
314 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
316 public abstract function onSubmit( $data );
319 * Do something exciting on successful processing of the form. This might be to show
320 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
321 * protect, etc).
323 public abstract function onSuccess();
326 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
327 * some stuff underneath (history etc); to do some processing on submission of that
328 * form (delete, protect, etc) and to do something exciting on 'success', be that
329 * display something new or redirect to somewhere. Some actions have more exotic
330 * behaviour, but that's what subclassing is for :D
332 public function show() {
333 $this->setHeaders();
335 // This will throw exceptions if there's a problem
336 $this->checkCanExecute( $this->getUser() );
338 $form = $this->getForm();
339 if ( $form->show() ) {
340 $this->onSuccess();
345 * @see Action::execute()
346 * @throws ErrorPageError
347 * @param array|null $data
348 * @param bool $captureErrors
349 * @return bool
351 public function execute( array $data = null, $captureErrors = true ) {
352 try {
353 // Set a new context so output doesn't leak.
354 $this->context = clone $this->page->getContext();
356 // This will throw exceptions if there's a problem
357 $this->checkCanExecute( $this->getUser() );
359 $fields = array();
360 foreach ( $this->fields as $key => $params ) {
361 if ( isset( $data[$key] ) ) {
362 $fields[$key] = $data[$key];
363 } elseif ( isset( $params['default'] ) ) {
364 $fields[$key] = $params['default'];
365 } else {
366 $fields[$key] = null;
369 $status = $this->onSubmit( $fields );
370 if ( $status === true ) {
371 // This might do permanent stuff
372 $this->onSuccess();
373 return true;
374 } else {
375 return false;
378 catch ( ErrorPageError $e ) {
379 if ( $captureErrors ) {
380 return false;
381 } else {
382 throw $e;
389 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
390 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
391 * patrol, etc).
393 abstract class FormlessAction extends Action {
396 * Show something on GET request.
397 * @return String|null will be added to the HTMLForm if present, or just added to the
398 * output if not. Return null to not add anything
400 public abstract function onView();
403 * We don't want an HTMLForm
405 protected function getFormFields() {
406 return false;
409 public function onSubmit( $data ) {
410 return false;
413 public function onSuccess() {
414 return false;
417 public function show() {
418 $this->setHeaders();
420 // This will throw exceptions if there's a problem
421 $this->checkCanExecute( $this->getUser() );
423 $this->getOutput()->addHTML( $this->onView() );
427 * Execute the action silently, not giving any output. Since these actions don't have
428 * forms, they probably won't have any data, but some (eg rollback) may do
429 * @param $data Array values that would normally be in the GET request
430 * @param $captureErrors Bool whether to catch exceptions and just return false
431 * @return Bool whether execution was successful
433 public function execute( array $data = null, $captureErrors = true ) {
434 try {
435 // Set a new context so output doesn't leak.
436 $this->context = clone $this->page->getContext();
437 if ( is_array( $data ) ) {
438 $this->context->setRequest( new FauxRequest( $data, false ) );
441 // This will throw exceptions if there's a problem
442 $this->checkCanExecute( $this->getUser() );
444 $this->onView();
445 return true;
447 catch ( ErrorPageError $e ) {
448 if ( $captureErrors ) {
449 return false;
450 } else {
451 throw $e;