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