[Actions] Move action logic out of MediaWiki::getAction/MediaWiki::performAction...
[lhc/web/wiklou.git] / includes / Action.php
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.
5 *
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
8 *
9 *
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.
14 *
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.
19 *
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
23 *
24 * @file
25 */
26 abstract class Action {
27
28 /**
29 * Page on which we're performing the action
30 * @var Page
31 */
32 protected $page;
33
34 /**
35 * IContextSource if specified; otherwise we'll use the Context from the Page
36 * @var IContextSource
37 */
38 protected $context;
39
40 /**
41 * The fields used to create the HTMLForm
42 * @var Array
43 */
44 protected $fields;
45
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
52 */
53 private final static function getClass( $action, array $overrides ) {
54 global $wgActions;
55 $action = strtolower( $action );
56
57 if ( !isset( $wgActions[$action] ) ) {
58 return null;
59 }
60
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];
69 }
70 }
71
72 /**
73 * Get an appropriate Action subclass for the given action
74 * @param $action String
75 * @param $page Page
76 * @param $context IContextSource
77 * @return Action|false|null false if the action is disabled, null
78 * if it is not recognised
79 */
80 public final static function factory( $action, Page $page, IContextSource $context = null ) {
81 $class = self::getClass( $action, $page->getActionOverrides() );
82 if ( $class ) {
83 $obj = new $class( $page, $context );
84 return $obj;
85 }
86 return $class;
87 }
88
89 /**
90 * Get the action that will be executed, not necessarily the one passed
91 * passed through the "action" request parameter. Actions disabled in
92 * $wgDisabledActions will be replaced by "nosuchaction".
93 *
94 * @param $context IContextSource
95 * @return string: action name
96 */
97 public final static function getActionName( IContextSource $context ) {
98 global $wgDisabledActions;
99
100 $request = $context->getRequest();
101 $actionName = $request->getVal( 'action', 'view' );
102
103 // Check for disabled actions
104 if ( in_array( $actionName, $wgDisabledActions ) ) {
105 $actionName = 'nosuchaction';
106 }
107
108 // Workaround for bug #20966: inability of IE to provide an action dependent
109 // on which submit button is clicked.
110 if ( $actionName === 'historysubmit' ) {
111 if ( $request->getBool( 'revisiondelete' ) ) {
112 $actionName = 'revisiondelete';
113 } else {
114 $actionName = 'view';
115 }
116 } elseif ( $actionName == 'editredlink' ) {
117 $actionName = 'edit';
118 }
119
120 $action = Action::factory( $actionName, $context->getWikiPage() );
121 if ( $action instanceof Action ) {
122 return $action->getName();
123 }
124
125 return 'nosuchaction';
126 }
127
128 /**
129 * Check if a given action is recognised, even if it's disabled
130 *
131 * @param $name String: name of an action
132 * @return Bool
133 */
134 public final static function exists( $name ) {
135 return self::getClass( $name, array() ) !== null;
136 }
137
138 /**
139 * Get the IContextSource in use here
140 * @return IContextSource
141 */
142 public final function getContext() {
143 if ( $this->context instanceof IContextSource ) {
144 return $this->context;
145 }
146 return $this->page->getContext();
147 }
148
149 /**
150 * Get the WebRequest being used for this instance
151 *
152 * @return WebRequest
153 */
154 public final function getRequest() {
155 return $this->getContext()->getRequest();
156 }
157
158 /**
159 * Get the OutputPage being used for this instance
160 *
161 * @return OutputPage
162 */
163 public final function getOutput() {
164 return $this->getContext()->getOutput();
165 }
166
167 /**
168 * Shortcut to get the User being used for this instance
169 *
170 * @return User
171 */
172 public final function getUser() {
173 return $this->getContext()->getUser();
174 }
175
176 /**
177 * Shortcut to get the Skin being used for this instance
178 *
179 * @return Skin
180 */
181 public final function getSkin() {
182 return $this->getContext()->getSkin();
183 }
184
185 /**
186 * Shortcut to get the user Language being used for this instance
187 *
188 * @return Language
189 */
190 public final function getLanguage() {
191 return $this->getContext()->getLanguage();
192 }
193
194 /**
195 * Shortcut to get the user Language being used for this instance
196 *
197 * @deprecated 1.19 Use getLanguage instead
198 * @return Language
199 */
200 public final function getLang() {
201 wfDeprecated( __METHOD__, '1.19' );
202 return $this->getLanguage();
203 }
204
205 /**
206 * Shortcut to get the Title object from the page
207 * @return Title
208 */
209 public final function getTitle() {
210 return $this->page->getTitle();
211 }
212
213 /**
214 * Get a Message object with context set
215 * Parameters are the same as wfMessage()
216 *
217 * @return Message object
218 */
219 public final function msg() {
220 $params = func_get_args();
221 return call_user_func_array( array( $this->getContext(), 'msg' ), $params );
222 }
223
224 /**
225 * Protected constructor: use Action::factory( $action, $page ) to actually build
226 * these things in the real world
227 * @param $page Page
228 * @param $context IContextSource
229 */
230 protected function __construct( Page $page, IContextSource $context = null ) {
231 $this->page = $page;
232 $this->context = $context;
233 }
234
235 /**
236 * Return the name of the action this object responds to
237 * @return String lowercase
238 */
239 public abstract function getName();
240
241 /**
242 * Get the permission required to perform this action. Often, but not always,
243 * the same as the action name
244 * @return String|null
245 */
246 public function getRestriction() {
247 return null;
248 }
249
250 /**
251 * Checks if the given user (identified by an object) can perform this action. Can be
252 * overridden by sub-classes with more complicated permissions schemes. Failures here
253 * must throw subclasses of ErrorPageError
254 *
255 * @param $user User: the user to check, or null to use the context user
256 * @throws ErrorPageError
257 */
258 protected function checkCanExecute( User $user ) {
259 $right = $this->getRestriction();
260 if ( $right !== null ) {
261 $errors = $this->getTitle()->getUserPermissionsErrors( $right, $user );
262 if ( count( $errors ) ) {
263 throw new PermissionsError( $right, $errors );
264 }
265 }
266
267 if ( $this->requiresUnblock() && $user->isBlocked() ) {
268 $block = $user->mBlock;
269 throw new UserBlockedError( $block );
270 }
271
272 // This should be checked at the end so that the user won't think the
273 // error is only temporary when he also don't have the rights to execute
274 // this action
275 if ( $this->requiresWrite() && wfReadOnly() ) {
276 throw new ReadOnlyError();
277 }
278 }
279
280 /**
281 * Whether this action requires the wiki not to be locked
282 * @return Bool
283 */
284 public function requiresWrite() {
285 return true;
286 }
287
288 /**
289 * Whether this action can still be executed by a blocked user
290 * @return Bool
291 */
292 public function requiresUnblock() {
293 return true;
294 }
295
296 /**
297 * Set output headers for noindexing etc. This function will not be called through
298 * the execute() entry point, so only put UI-related stuff in here.
299 */
300 protected function setHeaders() {
301 $out = $this->getOutput();
302 $out->setRobotPolicy( "noindex,nofollow" );
303 $out->setPageTitle( $this->getPageTitle() );
304 $this->getOutput()->setSubtitle( $this->getDescription() );
305 $out->setArticleRelated( true );
306 }
307
308 /**
309 * Returns the name that goes in the \<h1\> page title
310 *
311 * @return String
312 */
313 protected function getPageTitle() {
314 return $this->getTitle()->getPrefixedText();
315 }
316
317 /**
318 * Returns the description that goes below the \<h1\> tag
319 *
320 * @return String
321 */
322 protected function getDescription() {
323 return wfMsg( strtolower( $this->getName() ) );
324 }
325
326 /**
327 * The main action entry point. Do all output for display and send it to the context
328 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
329 * $this->getOutput(), etc.
330 * @throws ErrorPageError
331 */
332 public abstract function show();
333
334 /**
335 * Execute the action in a silent fashion: do not display anything or release any errors.
336 * @return Bool whether execution was successful
337 */
338 public abstract function execute();
339 }
340
341 abstract class FormAction extends Action {
342
343 /**
344 * Get an HTMLForm descriptor array
345 * @return Array
346 */
347 protected abstract function getFormFields();
348
349 /**
350 * Add pre- or post-text to the form
351 * @return String HTML which will be sent to $form->addPreText()
352 */
353 protected function preText() { return ''; }
354
355 /**
356 * @return string
357 */
358 protected function postText() { return ''; }
359
360 /**
361 * Play with the HTMLForm if you need to more substantially
362 * @param $form HTMLForm
363 */
364 protected function alterForm( HTMLForm $form ) {}
365
366 /**
367 * Get the HTMLForm to control behaviour
368 * @return HTMLForm|null
369 */
370 protected function getForm() {
371 $this->fields = $this->getFormFields();
372
373 // Give hooks a chance to alter the form, adding extra fields or text etc
374 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields, $this->page ) );
375
376 $form = new HTMLForm( $this->fields, $this->getContext() );
377 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
378
379 // Retain query parameters (uselang etc)
380 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
381 $params = array_diff_key(
382 $this->getRequest()->getQueryValues(),
383 array( 'action' => null, 'title' => null )
384 );
385 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
386
387 $form->addPreText( $this->preText() );
388 $form->addPostText( $this->postText() );
389 $this->alterForm( $form );
390
391 // Give hooks a chance to alter the form, adding extra fields or text etc
392 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page ) );
393
394 return $form;
395 }
396
397 /**
398 * Process the form on POST submission. If you return false from getFormFields(),
399 * this will obviously never be reached. If you don't want to do anything with the
400 * form, just return false here
401 * @param $data Array
402 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
403 */
404 public abstract function onSubmit( $data );
405
406 /**
407 * Do something exciting on successful processing of the form. This might be to show
408 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
409 * protect, etc).
410 */
411 public abstract function onSuccess();
412
413 /**
414 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
415 * some stuff underneath (history etc); to do some processing on submission of that
416 * form (delete, protect, etc) and to do something exciting on 'success', be that
417 * display something new or redirect to somewhere. Some actions have more exotic
418 * behaviour, but that's what subclassing is for :D
419 */
420 public function show() {
421 $this->setHeaders();
422
423 // This will throw exceptions if there's a problem
424 $this->checkCanExecute( $this->getUser() );
425
426 $form = $this->getForm();
427 if ( $form->show() ) {
428 $this->onSuccess();
429 }
430 }
431
432 /**
433 * @see Action::execute()
434 * @throws ErrorPageError
435 * @param array|null $data
436 * @param bool $captureErrors
437 * @return bool
438 */
439 public function execute( array $data = null, $captureErrors = true ) {
440 try {
441 // Set a new context so output doesn't leak.
442 $this->context = clone $this->page->getContext();
443
444 // This will throw exceptions if there's a problem
445 $this->checkCanExecute( $this->getUser() );
446
447 $fields = array();
448 foreach ( $this->fields as $key => $params ) {
449 if ( isset( $data[$key] ) ) {
450 $fields[$key] = $data[$key];
451 } elseif ( isset( $params['default'] ) ) {
452 $fields[$key] = $params['default'];
453 } else {
454 $fields[$key] = null;
455 }
456 }
457 $status = $this->onSubmit( $fields );
458 if ( $status === true ) {
459 // This might do permanent stuff
460 $this->onSuccess();
461 return true;
462 } else {
463 return false;
464 }
465 }
466 catch ( ErrorPageError $e ) {
467 if ( $captureErrors ) {
468 return false;
469 } else {
470 throw $e;
471 }
472 }
473 }
474 }
475
476 /**
477 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
478 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
479 * patrol, etc).
480 */
481 abstract class FormlessAction extends Action {
482
483 /**
484 * Show something on GET request.
485 * @return String|null will be added to the HTMLForm if present, or just added to the
486 * output if not. Return null to not add anything
487 */
488 public abstract function onView();
489
490 /**
491 * We don't want an HTMLForm
492 */
493 protected function getFormFields() {
494 return false;
495 }
496
497 public function onSubmit( $data ) {
498 return false;
499 }
500
501 public function onSuccess() {
502 return false;
503 }
504
505 public function show() {
506 $this->setHeaders();
507
508 // This will throw exceptions if there's a problem
509 $this->checkCanExecute( $this->getUser() );
510
511 $this->getOutput()->addHTML( $this->onView() );
512 }
513
514 /**
515 * Execute the action silently, not giving any output. Since these actions don't have
516 * forms, they probably won't have any data, but some (eg rollback) may do
517 * @param $data Array values that would normally be in the GET request
518 * @param $captureErrors Bool whether to catch exceptions and just return false
519 * @return Bool whether execution was successful
520 */
521 public function execute( array $data = null, $captureErrors = true ) {
522 try {
523 // Set a new context so output doesn't leak.
524 $this->context = clone $this->page->getContext();
525 if ( is_array( $data ) ) {
526 $this->context->setRequest( new FauxRequest( $data, false ) );
527 }
528
529 // This will throw exceptions if there's a problem
530 $this->checkCanExecute( $this->getUser() );
531
532 $this->onView();
533 return true;
534 }
535 catch ( ErrorPageError $e ) {
536 if ( $captureErrors ) {
537 return false;
538 } else {
539 throw $e;
540 }
541 }
542 }
543 }