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