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