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