fix doc grouping for actions
[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|false|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 */
270 protected function checkCanExecute( User $user ) {
271 $right = $this->getRestriction();
272 if ( $right !== null ) {
273 $errors = $this->getTitle()->getUserPermissionsErrors( $right, $user );
274 if ( count( $errors ) ) {
275 throw new PermissionsError( $right, $errors );
276 }
277 }
278
279 if ( $this->requiresUnblock() && $user->isBlocked() ) {
280 $block = $user->mBlock;
281 throw new UserBlockedError( $block );
282 }
283
284 // This should be checked at the end so that the user won't think the
285 // error is only temporary when he also don't have the rights to execute
286 // this action
287 if ( $this->requiresWrite() && wfReadOnly() ) {
288 throw new ReadOnlyError();
289 }
290 }
291
292 /**
293 * Whether this action requires the wiki not to be locked
294 * @return Bool
295 */
296 public function requiresWrite() {
297 return true;
298 }
299
300 /**
301 * Whether this action can still be executed by a blocked user
302 * @return Bool
303 */
304 public function requiresUnblock() {
305 return true;
306 }
307
308 /**
309 * Set output headers for noindexing etc. This function will not be called through
310 * the execute() entry point, so only put UI-related stuff in here.
311 */
312 protected function setHeaders() {
313 $out = $this->getOutput();
314 $out->setRobotPolicy( "noindex,nofollow" );
315 $out->setPageTitle( $this->getPageTitle() );
316 $this->getOutput()->setSubtitle( $this->getDescription() );
317 $out->setArticleRelated( true );
318 }
319
320 /**
321 * Returns the name that goes in the \<h1\> page title
322 *
323 * @return String
324 */
325 protected function getPageTitle() {
326 return $this->getTitle()->getPrefixedText();
327 }
328
329 /**
330 * Returns the description that goes below the \<h1\> tag
331 *
332 * @return String
333 */
334 protected function getDescription() {
335 return wfMsgHtml( strtolower( $this->getName() ) );
336 }
337
338 /**
339 * The main action entry point. Do all output for display and send it to the context
340 * output. Do not use globals $wgOut, $wgRequest, etc, in implementations; use
341 * $this->getOutput(), etc.
342 * @throws ErrorPageError
343 */
344 public abstract function show();
345
346 /**
347 * Execute the action in a silent fashion: do not display anything or release any errors.
348 * @return Bool whether execution was successful
349 */
350 public abstract function execute();
351 }
352
353 abstract class FormAction extends Action {
354
355 /**
356 * Get an HTMLForm descriptor array
357 * @return Array
358 */
359 protected abstract function getFormFields();
360
361 /**
362 * Add pre- or post-text to the form
363 * @return String HTML which will be sent to $form->addPreText()
364 */
365 protected function preText() { return ''; }
366
367 /**
368 * @return string
369 */
370 protected function postText() { return ''; }
371
372 /**
373 * Play with the HTMLForm if you need to more substantially
374 * @param $form HTMLForm
375 */
376 protected function alterForm( HTMLForm $form ) {}
377
378 /**
379 * Get the HTMLForm to control behaviour
380 * @return HTMLForm|null
381 */
382 protected function getForm() {
383 $this->fields = $this->getFormFields();
384
385 // Give hooks a chance to alter the form, adding extra fields or text etc
386 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields, $this->page ) );
387
388 $form = new HTMLForm( $this->fields, $this->getContext() );
389 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
390
391 // Retain query parameters (uselang etc)
392 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
393 $params = array_diff_key(
394 $this->getRequest()->getQueryValues(),
395 array( 'action' => null, 'title' => null )
396 );
397 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
398
399 $form->addPreText( $this->preText() );
400 $form->addPostText( $this->postText() );
401 $this->alterForm( $form );
402
403 // Give hooks a chance to alter the form, adding extra fields or text etc
404 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page ) );
405
406 return $form;
407 }
408
409 /**
410 * Process the form on POST submission. If you return false from getFormFields(),
411 * this will obviously never be reached. If you don't want to do anything with the
412 * form, just return false here
413 * @param $data Array
414 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
415 */
416 public abstract function onSubmit( $data );
417
418 /**
419 * Do something exciting on successful processing of the form. This might be to show
420 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
421 * protect, etc).
422 */
423 public abstract function onSuccess();
424
425 /**
426 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
427 * some stuff underneath (history etc); to do some processing on submission of that
428 * form (delete, protect, etc) and to do something exciting on 'success', be that
429 * display something new or redirect to somewhere. Some actions have more exotic
430 * behaviour, but that's what subclassing is for :D
431 */
432 public function show() {
433 $this->setHeaders();
434
435 // This will throw exceptions if there's a problem
436 $this->checkCanExecute( $this->getUser() );
437
438 $form = $this->getForm();
439 if ( $form->show() ) {
440 $this->onSuccess();
441 }
442 }
443
444 /**
445 * @see Action::execute()
446 * @throws ErrorPageError
447 * @param array|null $data
448 * @param bool $captureErrors
449 * @return bool
450 */
451 public function execute( array $data = null, $captureErrors = true ) {
452 try {
453 // Set a new context so output doesn't leak.
454 $this->context = clone $this->page->getContext();
455
456 // This will throw exceptions if there's a problem
457 $this->checkCanExecute( $this->getUser() );
458
459 $fields = array();
460 foreach ( $this->fields as $key => $params ) {
461 if ( isset( $data[$key] ) ) {
462 $fields[$key] = $data[$key];
463 } elseif ( isset( $params['default'] ) ) {
464 $fields[$key] = $params['default'];
465 } else {
466 $fields[$key] = null;
467 }
468 }
469 $status = $this->onSubmit( $fields );
470 if ( $status === true ) {
471 // This might do permanent stuff
472 $this->onSuccess();
473 return true;
474 } else {
475 return false;
476 }
477 }
478 catch ( ErrorPageError $e ) {
479 if ( $captureErrors ) {
480 return false;
481 } else {
482 throw $e;
483 }
484 }
485 }
486 }
487
488 /**
489 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
490 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
491 * patrol, etc).
492 */
493 abstract class FormlessAction extends Action {
494
495 /**
496 * Show something on GET request.
497 * @return String|null will be added to the HTMLForm if present, or just added to the
498 * output if not. Return null to not add anything
499 */
500 public abstract function onView();
501
502 /**
503 * We don't want an HTMLForm
504 */
505 protected function getFormFields() {
506 return false;
507 }
508
509 public function onSubmit( $data ) {
510 return false;
511 }
512
513 public function onSuccess() {
514 return false;
515 }
516
517 public function show() {
518 $this->setHeaders();
519
520 // This will throw exceptions if there's a problem
521 $this->checkCanExecute( $this->getUser() );
522
523 $this->getOutput()->addHTML( $this->onView() );
524 }
525
526 /**
527 * Execute the action silently, not giving any output. Since these actions don't have
528 * forms, they probably won't have any data, but some (eg rollback) may do
529 * @param $data Array values that would normally be in the GET request
530 * @param $captureErrors Bool whether to catch exceptions and just return false
531 * @return Bool whether execution was successful
532 */
533 public function execute( array $data = null, $captureErrors = true ) {
534 try {
535 // Set a new context so output doesn't leak.
536 $this->context = clone $this->page->getContext();
537 if ( is_array( $data ) ) {
538 $this->context->setRequest( new FauxRequest( $data, false ) );
539 }
540
541 // This will throw exceptions if there's a problem
542 $this->checkCanExecute( $this->getUser() );
543
544 $this->onView();
545 return true;
546 }
547 catch ( ErrorPageError $e ) {
548 if ( $captureErrors ) {
549 return false;
550 } else {
551 throw $e;
552 }
553 }
554 }
555 }