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