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