Reverted r109223 per CR
[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 Language
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 Language
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 * @return Bool whether execution was successful
298 */
299 public abstract function execute();
300 }
301
302 abstract class FormAction extends Action {
303
304 /**
305 * Get an HTMLForm descriptor array
306 * @return Array
307 */
308 protected abstract function getFormFields();
309
310 /**
311 * Add pre- or post-text to the form
312 * @return String HTML which will be sent to $form->addPreText()
313 */
314 protected function preText() { return ''; }
315
316 /**
317 * @return string
318 */
319 protected function postText() { return ''; }
320
321 /**
322 * Play with the HTMLForm if you need to more substantially
323 * @param $form HTMLForm
324 */
325 protected function alterForm( HTMLForm $form ) {}
326
327 /**
328 * Get the HTMLForm to control behaviour
329 * @return HTMLForm|null
330 */
331 protected function getForm() {
332 $this->fields = $this->getFormFields();
333
334 // Give hooks a chance to alter the form, adding extra fields or text etc
335 wfRunHooks( 'ActionModifyFormFields', array( $this->getName(), &$this->fields, $this->page ) );
336
337 $form = new HTMLForm( $this->fields, $this->getContext() );
338 $form->setSubmitCallback( array( $this, 'onSubmit' ) );
339
340 // Retain query parameters (uselang etc)
341 $form->addHiddenField( 'action', $this->getName() ); // Might not be the same as the query string
342 $params = array_diff_key(
343 $this->getRequest()->getQueryValues(),
344 array( 'action' => null, 'title' => null )
345 );
346 $form->addHiddenField( 'redirectparams', wfArrayToCGI( $params ) );
347
348 $form->addPreText( $this->preText() );
349 $form->addPostText( $this->postText() );
350 $this->alterForm( $form );
351
352 // Give hooks a chance to alter the form, adding extra fields or text etc
353 wfRunHooks( 'ActionBeforeFormDisplay', array( $this->getName(), &$form, $this->page ) );
354
355 return $form;
356 }
357
358 /**
359 * Process the form on POST submission. If you return false from getFormFields(),
360 * this will obviously never be reached. If you don't want to do anything with the
361 * form, just return false here
362 * @param $data Array
363 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
364 */
365 public abstract function onSubmit( $data );
366
367 /**
368 * Do something exciting on successful processing of the form. This might be to show
369 * a confirmation message (watch, rollback, etc) or to redirect somewhere else (edit,
370 * protect, etc).
371 */
372 public abstract function onSuccess();
373
374 /**
375 * The basic pattern for actions is to display some sort of HTMLForm UI, maybe with
376 * some stuff underneath (history etc); to do some processing on submission of that
377 * form (delete, protect, etc) and to do something exciting on 'success', be that
378 * display something new or redirect to somewhere. Some actions have more exotic
379 * behaviour, but that's what subclassing is for :D
380 */
381 public function show() {
382 $this->setHeaders();
383
384 // This will throw exceptions if there's a problem
385 $this->checkCanExecute( $this->getUser() );
386
387 $form = $this->getForm();
388 if ( $form->show() ) {
389 $this->onSuccess();
390 }
391 }
392
393 /**
394 * @see Action::execute()
395 * @throws ErrorPageError
396 * @param array|null $data
397 * @param bool $captureErrors
398 * @return bool
399 */
400 public function execute( array $data = null, $captureErrors = true ) {
401 try {
402 // Set a new context so output doesn't leak.
403 $this->context = clone $this->page->getContext();
404
405 // This will throw exceptions if there's a problem
406 $this->checkCanExecute( $this->getUser() );
407
408 $fields = array();
409 foreach ( $this->fields as $key => $params ) {
410 if ( isset( $data[$key] ) ) {
411 $fields[$key] = $data[$key];
412 } elseif ( isset( $params['default'] ) ) {
413 $fields[$key] = $params['default'];
414 } else {
415 $fields[$key] = null;
416 }
417 }
418 $status = $this->onSubmit( $fields );
419 if ( $status === true ) {
420 // This might do permanent stuff
421 $this->onSuccess();
422 return true;
423 } else {
424 return false;
425 }
426 }
427 catch ( ErrorPageError $e ) {
428 if ( $captureErrors ) {
429 return false;
430 } else {
431 throw $e;
432 }
433 }
434 }
435 }
436
437 /**
438 * Actions generally fall into two groups: the show-a-form-then-do-something-with-the-input
439 * format (protect, delete, move, etc), and the just-do-something format (watch, rollback,
440 * patrol, etc).
441 */
442 abstract class FormlessAction extends Action {
443
444 /**
445 * Show something on GET request.
446 * @return String|null will be added to the HTMLForm if present, or just added to the
447 * output if not. Return null to not add anything
448 */
449 public abstract function onView();
450
451 /**
452 * We don't want an HTMLForm
453 */
454 protected function getFormFields() {
455 return false;
456 }
457
458 public function onSubmit( $data ) {
459 return false;
460 }
461
462 public function onSuccess() {
463 return false;
464 }
465
466 public function show() {
467 $this->setHeaders();
468
469 // This will throw exceptions if there's a problem
470 $this->checkCanExecute( $this->getUser() );
471
472 $this->getOutput()->addHTML( $this->onView() );
473 }
474
475 /**
476 * Execute the action silently, not giving any output. Since these actions don't have
477 * forms, they probably won't have any data, but some (eg rollback) may do
478 * @param $data Array values that would normally be in the GET request
479 * @param $captureErrors Bool whether to catch exceptions and just return false
480 * @return Bool whether execution was successful
481 */
482 public function execute( array $data = null, $captureErrors = true ) {
483 try {
484 // Set a new context so output doesn't leak.
485 $this->context = clone $this->page->getContext();
486 if ( is_array( $data ) ) {
487 $this->context->setRequest( new FauxRequest( $data, false ) );
488 }
489
490 // This will throw exceptions if there's a problem
491 $this->checkCanExecute( $this->getUser() );
492
493 $this->onView();
494 return true;
495 }
496 catch ( ErrorPageError $e ) {
497 if ( $captureErrors ) {
498 return false;
499 } else {
500 throw $e;
501 }
502 }
503 }
504 }