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