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