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