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