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