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