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