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