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