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