Add -f as an alias of --force to cli args of updateCollation.php
[lhc/web/wiklou.git] / includes / specialpage / SpecialPage.php
1 <?php
2 /**
3 * Parent class for all special pages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Parent class for all special pages.
26 *
27 * Includes some static functions for handling the special page list deprecated
28 * in favor of SpecialPageFactory.
29 *
30 * @ingroup SpecialPage
31 */
32 class SpecialPage {
33 // The canonical name of this special page
34 // Also used for the default <h1> heading, @see getDescription()
35 protected $mName;
36
37 // The local name of this special page
38 private $mLocalName;
39
40 // Minimum user level required to access this page, or "" for anyone.
41 // Also used to categorise the pages in Special:Specialpages
42 protected $mRestriction;
43
44 // Listed in Special:Specialpages?
45 private $mListed;
46
47 // Whether or not this special page is being included from an article
48 protected $mIncluding;
49
50 // Whether the special page can be included in an article
51 protected $mIncludable;
52
53 /**
54 * Current request context
55 * @var IContextSource
56 */
57 protected $mContext;
58
59 /**
60 * Get a localised Title object for a specified special page name
61 *
62 * @since 1.9
63 * @since 1.21 $fragment parameter added
64 *
65 * @param string $name
66 * @param string|bool $subpage Subpage string, or false to not use a subpage
67 * @param string $fragment The link fragment (after the "#")
68 * @return Title
69 * @throws MWException
70 */
71 public static function getTitleFor( $name, $subpage = false, $fragment = '' ) {
72 $name = SpecialPageFactory::getLocalNameFor( $name, $subpage );
73
74 return Title::makeTitle( NS_SPECIAL, $name, $fragment );
75 }
76
77 /**
78 * Get a localised Title object for a page name with a possibly unvalidated subpage
79 *
80 * @param string $name
81 * @param string|bool $subpage Subpage string, or false to not use a subpage
82 * @return Title|null Title object or null if the page doesn't exist
83 */
84 public static function getSafeTitleFor( $name, $subpage = false ) {
85 $name = SpecialPageFactory::getLocalNameFor( $name, $subpage );
86 if ( $name ) {
87 return Title::makeTitleSafe( NS_SPECIAL, $name );
88 } else {
89 return null;
90 }
91 }
92
93 /**
94 * Default constructor for special pages
95 * Derivative classes should call this from their constructor
96 * Note that if the user does not have the required level, an error message will
97 * be displayed by the default execute() method, without the global function ever
98 * being called.
99 *
100 * If you override execute(), you can recover the default behavior with userCanExecute()
101 * and displayRestrictionError()
102 *
103 * @param string $name Name of the special page, as seen in links and URLs
104 * @param string $restriction User right required, e.g. "block" or "delete"
105 * @param bool $listed Whether the page is listed in Special:Specialpages
106 * @param callable|bool $function Unused
107 * @param string $file Unused
108 * @param bool $includable Whether the page can be included in normal pages
109 */
110 public function __construct(
111 $name = '', $restriction = '', $listed = true,
112 $function = false, $file = '', $includable = false
113 ) {
114 $this->mName = $name;
115 $this->mRestriction = $restriction;
116 $this->mListed = $listed;
117 $this->mIncludable = $includable;
118 }
119
120 /**
121 * Get the name of this Special Page.
122 * @return string
123 */
124 function getName() {
125 return $this->mName;
126 }
127
128 /**
129 * Get the permission that a user must have to execute this page
130 * @return string
131 */
132 function getRestriction() {
133 return $this->mRestriction;
134 }
135
136 // @todo FIXME: Decide which syntax to use for this, and stick to it
137 /**
138 * Whether this special page is listed in Special:SpecialPages
139 * @since 1.3 (r3583)
140 * @return bool
141 */
142 function isListed() {
143 return $this->mListed;
144 }
145
146 /**
147 * Set whether this page is listed in Special:Specialpages, at run-time
148 * @since 1.3
149 * @param bool $listed
150 * @return bool
151 */
152 function setListed( $listed ) {
153 return wfSetVar( $this->mListed, $listed );
154 }
155
156 /**
157 * Get or set whether this special page is listed in Special:SpecialPages
158 * @since 1.6
159 * @param bool $x
160 * @return bool
161 */
162 function listed( $x = null ) {
163 return wfSetVar( $this->mListed, $x );
164 }
165
166 /**
167 * Whether it's allowed to transclude the special page via {{Special:Foo/params}}
168 * @return bool
169 */
170 public function isIncludable() {
171 return $this->mIncludable;
172 }
173
174 /**
175 * Whether the special page is being evaluated via transclusion
176 * @param bool $x
177 * @return bool
178 */
179 function including( $x = null ) {
180 return wfSetVar( $this->mIncluding, $x );
181 }
182
183 /**
184 * Get the localised name of the special page
185 * @return string
186 */
187 function getLocalName() {
188 if ( !isset( $this->mLocalName ) ) {
189 $this->mLocalName = SpecialPageFactory::getLocalNameFor( $this->mName );
190 }
191
192 return $this->mLocalName;
193 }
194
195 /**
196 * Is this page expensive (for some definition of expensive)?
197 * Expensive pages are disabled or cached in miser mode. Originally used
198 * (and still overridden) by QueryPage and subclasses, moved here so that
199 * Special:SpecialPages can safely call it for all special pages.
200 *
201 * @return bool
202 */
203 public function isExpensive() {
204 return false;
205 }
206
207 /**
208 * Is this page cached?
209 * Expensive pages are cached or disabled in miser mode.
210 * Used by QueryPage and subclasses, moved here so that
211 * Special:SpecialPages can safely call it for all special pages.
212 *
213 * @return bool
214 * @since 1.21
215 */
216 public function isCached() {
217 return false;
218 }
219
220 /**
221 * Can be overridden by subclasses with more complicated permissions
222 * schemes.
223 *
224 * @return bool Should the page be displayed with the restricted-access
225 * pages?
226 */
227 public function isRestricted() {
228 // DWIM: If anons can do something, then it is not restricted
229 return $this->mRestriction != '' && !User::groupHasPermission( '*', $this->mRestriction );
230 }
231
232 /**
233 * Checks if the given user (identified by an object) can execute this
234 * special page (as defined by $mRestriction). Can be overridden by sub-
235 * classes with more complicated permissions schemes.
236 *
237 * @param User $user The user to check
238 * @return bool Does the user have permission to view the page?
239 */
240 public function userCanExecute( User $user ) {
241 return $user->isAllowed( $this->mRestriction );
242 }
243
244 /**
245 * Output an error message telling the user what access level they have to have
246 * @throws PermissionsError
247 */
248 function displayRestrictionError() {
249 throw new PermissionsError( $this->mRestriction );
250 }
251
252 /**
253 * Checks if userCanExecute, and if not throws a PermissionsError
254 *
255 * @since 1.19
256 * @return void
257 * @throws PermissionsError
258 */
259 public function checkPermissions() {
260 if ( !$this->userCanExecute( $this->getUser() ) ) {
261 $this->displayRestrictionError();
262 }
263 }
264
265 /**
266 * If the wiki is currently in readonly mode, throws a ReadOnlyError
267 *
268 * @since 1.19
269 * @return void
270 * @throws ReadOnlyError
271 */
272 public function checkReadOnly() {
273 if ( wfReadOnly() ) {
274 throw new ReadOnlyError;
275 }
276 }
277
278 /**
279 * If the user is not logged in, throws UserNotLoggedIn error
280 *
281 * The user will be redirected to Special:Userlogin with the given message as an error on
282 * the form.
283 *
284 * @since 1.23
285 * @param string $reasonMsg [optional] Message key to be displayed on login page
286 * @param string $titleMsg [optional] Passed on to UserNotLoggedIn constructor
287 * @throws UserNotLoggedIn
288 */
289 public function requireLogin(
290 $reasonMsg = 'exception-nologin-text', $titleMsg = 'exception-nologin'
291 ) {
292 if ( $this->getUser()->isAnon() ) {
293 throw new UserNotLoggedIn( $reasonMsg, $titleMsg );
294 }
295 }
296
297 /**
298 * Return an array of subpages beginning with $search that this special page will accept.
299 *
300 * For example, if a page supports subpages "foo", "bar" and "baz" (as in Special:PageName/foo,
301 * etc.):
302 *
303 * - `prefixSearchSubpages( "ba" )` should return `array( "bar", "baz" )`
304 * - `prefixSearchSubpages( "f" )` should return `array( "foo" )`
305 * - `prefixSearchSubpages( "z" )` should return `array()`
306 * - `prefixSearchSubpages( "" )` should return `array( foo", "bar", "baz" )`
307 *
308 * @param string $search Prefix to search for
309 * @param int $limit Maximum number of results to return (usually 10)
310 * @param int $offset Number of results to skip (usually 0)
311 * @return string[] Matching subpages
312 */
313 public function prefixSearchSubpages( $search, $limit, $offset ) {
314 $subpages = $this->getSubpagesForPrefixSearch();
315 if ( !$subpages ) {
316 return [];
317 }
318
319 return self::prefixSearchArray( $search, $limit, $subpages, $offset );
320 }
321
322 /**
323 * Return an array of subpages that this special page will accept for prefix
324 * searches. If this method requires a query you might instead want to implement
325 * prefixSearchSubpages() directly so you can support $limit and $offset. This
326 * method is better for static-ish lists of things.
327 *
328 * @return string[] subpages to search from
329 */
330 protected function getSubpagesForPrefixSearch() {
331 return [];
332 }
333
334 /**
335 * Perform a regular substring search for prefixSearchSubpages
336 * @param string $search Prefix to search for
337 * @param int $limit Maximum number of results to return (usually 10)
338 * @param int $offset Number of results to skip (usually 0)
339 * @return string[] Matching subpages
340 */
341 protected function prefixSearchString( $search, $limit, $offset ) {
342 $title = Title::newFromText( $search );
343 if ( !$title || !$title->canExist() ) {
344 // No prefix suggestion in special and media namespace
345 return [];
346 }
347
348 $searchEngine = SearchEngine::create();
349 $searchEngine->setLimitOffset( $limit, $offset );
350 $searchEngine->setNamespaces( [] );
351 $result = $searchEngine->defaultPrefixSearch( $search );
352 return array_map( function( Title $t ) {
353 return $t->getPrefixedText();
354 }, $result );
355 }
356
357 /**
358 * Helper function for implementations of prefixSearchSubpages() that
359 * filter the values in memory (as opposed to making a query).
360 *
361 * @since 1.24
362 * @param string $search
363 * @param int $limit
364 * @param array $subpages
365 * @param int $offset
366 * @return string[]
367 */
368 protected static function prefixSearchArray( $search, $limit, array $subpages, $offset ) {
369 $escaped = preg_quote( $search, '/' );
370 return array_slice( preg_grep( "/^$escaped/i",
371 array_slice( $subpages, $offset ) ), 0, $limit );
372 }
373
374 /**
375 * Sets headers - this should be called from the execute() method of all derived classes!
376 */
377 function setHeaders() {
378 $out = $this->getOutput();
379 $out->setArticleRelated( false );
380 $out->setRobotPolicy( $this->getRobotPolicy() );
381 $out->setPageTitle( $this->getDescription() );
382 if ( $this->getConfig()->get( 'UseMediaWikiUIEverywhere' ) ) {
383 $out->addModuleStyles( [
384 'mediawiki.ui.input',
385 'mediawiki.ui.radio',
386 'mediawiki.ui.checkbox',
387 ] );
388 }
389 }
390
391 /**
392 * Entry point.
393 *
394 * @since 1.20
395 *
396 * @param string|null $subPage
397 */
398 final public function run( $subPage ) {
399 /**
400 * Gets called before @see SpecialPage::execute.
401 * Return false to prevent calling execute() (since 1.27+).
402 *
403 * @since 1.20
404 *
405 * @param SpecialPage $this
406 * @param string|null $subPage
407 */
408 if ( !Hooks::run( 'SpecialPageBeforeExecute', [ $this, $subPage ] ) ) {
409 return;
410 }
411
412 if ( $this->beforeExecute( $subPage ) === false ) {
413 return;
414 }
415 $this->execute( $subPage );
416 $this->afterExecute( $subPage );
417
418 /**
419 * Gets called after @see SpecialPage::execute.
420 *
421 * @since 1.20
422 *
423 * @param SpecialPage $this
424 * @param string|null $subPage
425 */
426 Hooks::run( 'SpecialPageAfterExecute', [ $this, $subPage ] );
427 }
428
429 /**
430 * Gets called before @see SpecialPage::execute.
431 * Return false to prevent calling execute() (since 1.27+).
432 *
433 * @since 1.20
434 *
435 * @param string|null $subPage
436 * @return bool|void
437 */
438 protected function beforeExecute( $subPage ) {
439 // No-op
440 }
441
442 /**
443 * Gets called after @see SpecialPage::execute.
444 *
445 * @since 1.20
446 *
447 * @param string|null $subPage
448 */
449 protected function afterExecute( $subPage ) {
450 // No-op
451 }
452
453 /**
454 * Default execute method
455 * Checks user permissions
456 *
457 * This must be overridden by subclasses; it will be made abstract in a future version
458 *
459 * @param string|null $subPage
460 */
461 public function execute( $subPage ) {
462 $this->setHeaders();
463 $this->checkPermissions();
464 $this->outputHeader();
465 }
466
467 /**
468 * Outputs a summary message on top of special pages
469 * Per default the message key is the canonical name of the special page
470 * May be overridden, i.e. by extensions to stick with the naming conventions
471 * for message keys: 'extensionname-xxx'
472 *
473 * @param string $summaryMessageKey Message key of the summary
474 */
475 function outputHeader( $summaryMessageKey = '' ) {
476 global $wgContLang;
477
478 if ( $summaryMessageKey == '' ) {
479 $msg = $wgContLang->lc( $this->getName() ) . '-summary';
480 } else {
481 $msg = $summaryMessageKey;
482 }
483 if ( !$this->msg( $msg )->isDisabled() && !$this->including() ) {
484 $this->getOutput()->wrapWikiMsg(
485 "<div class='mw-specialpage-summary'>\n$1\n</div>", $msg );
486 }
487 }
488
489 /**
490 * Returns the name that goes in the \<h1\> in the special page itself, and
491 * also the name that will be listed in Special:Specialpages
492 *
493 * Derived classes can override this, but usually it is easier to keep the
494 * default behavior.
495 *
496 * @return string
497 */
498 function getDescription() {
499 return $this->msg( strtolower( $this->mName ) )->text();
500 }
501
502 /**
503 * Get a self-referential title object
504 *
505 * @param string|bool $subpage
506 * @return Title
507 * @deprecated since 1.23, use SpecialPage::getPageTitle
508 */
509 function getTitle( $subpage = false ) {
510 return $this->getPageTitle( $subpage );
511 }
512
513 /**
514 * Get a self-referential title object
515 *
516 * @param string|bool $subpage
517 * @return Title
518 * @since 1.23
519 */
520 function getPageTitle( $subpage = false ) {
521 return self::getTitleFor( $this->mName, $subpage );
522 }
523
524 /**
525 * Sets the context this SpecialPage is executed in
526 *
527 * @param IContextSource $context
528 * @since 1.18
529 */
530 public function setContext( $context ) {
531 $this->mContext = $context;
532 }
533
534 /**
535 * Gets the context this SpecialPage is executed in
536 *
537 * @return IContextSource|RequestContext
538 * @since 1.18
539 */
540 public function getContext() {
541 if ( $this->mContext instanceof IContextSource ) {
542 return $this->mContext;
543 } else {
544 wfDebug( __METHOD__ . " called and \$mContext is null. " .
545 "Return RequestContext::getMain(); for sanity\n" );
546
547 return RequestContext::getMain();
548 }
549 }
550
551 /**
552 * Get the WebRequest being used for this instance
553 *
554 * @return WebRequest
555 * @since 1.18
556 */
557 public function getRequest() {
558 return $this->getContext()->getRequest();
559 }
560
561 /**
562 * Get the OutputPage being used for this instance
563 *
564 * @return OutputPage
565 * @since 1.18
566 */
567 public function getOutput() {
568 return $this->getContext()->getOutput();
569 }
570
571 /**
572 * Shortcut to get the User executing this instance
573 *
574 * @return User
575 * @since 1.18
576 */
577 public function getUser() {
578 return $this->getContext()->getUser();
579 }
580
581 /**
582 * Shortcut to get the skin being used for this instance
583 *
584 * @return Skin
585 * @since 1.18
586 */
587 public function getSkin() {
588 return $this->getContext()->getSkin();
589 }
590
591 /**
592 * Shortcut to get user's language
593 *
594 * @return Language
595 * @since 1.19
596 */
597 public function getLanguage() {
598 return $this->getContext()->getLanguage();
599 }
600
601 /**
602 * Shortcut to get main config object
603 * @return Config
604 * @since 1.24
605 */
606 public function getConfig() {
607 return $this->getContext()->getConfig();
608 }
609
610 /**
611 * Return the full title, including $par
612 *
613 * @return Title
614 * @since 1.18
615 */
616 public function getFullTitle() {
617 return $this->getContext()->getTitle();
618 }
619
620 /**
621 * Return the robot policy. Derived classes that override this can change
622 * the robot policy set by setHeaders() from the default 'noindex,nofollow'.
623 *
624 * @return string
625 * @since 1.23
626 */
627 protected function getRobotPolicy() {
628 return 'noindex,nofollow';
629 }
630
631 /**
632 * Wrapper around wfMessage that sets the current context.
633 *
634 * @return Message
635 * @see wfMessage
636 */
637 public function msg( /* $args */ ) {
638 $message = call_user_func_array(
639 [ $this->getContext(), 'msg' ],
640 func_get_args()
641 );
642 // RequestContext passes context to wfMessage, and the language is set from
643 // the context, but setting the language for Message class removes the
644 // interface message status, which breaks for example usernameless gender
645 // invocations. Restore the flag when not including special page in content.
646 if ( $this->including() ) {
647 $message->setInterfaceMessageFlag( false );
648 }
649
650 return $message;
651 }
652
653 /**
654 * Adds RSS/atom links
655 *
656 * @param array $params
657 */
658 protected function addFeedLinks( $params ) {
659 $feedTemplate = wfScript( 'api' );
660
661 foreach ( $this->getConfig()->get( 'FeedClasses' ) as $format => $class ) {
662 $theseParams = $params + [ 'feedformat' => $format ];
663 $url = wfAppendQuery( $feedTemplate, $theseParams );
664 $this->getOutput()->addFeedLink( $format, $url );
665 }
666 }
667
668 /**
669 * Adds help link with an icon via page indicators.
670 * Link target can be overridden by a local message containing a wikilink:
671 * the message key is: lowercase special page name + '-helppage'.
672 * @param string $to Target MediaWiki.org page title or encoded URL.
673 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
674 * @since 1.25
675 */
676 public function addHelpLink( $to, $overrideBaseUrl = false ) {
677 global $wgContLang;
678 $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' );
679
680 if ( !$msg->isDisabled() ) {
681 $helpUrl = Skin::makeUrl( $msg->plain() );
682 $this->getOutput()->addHelpLink( $helpUrl, true );
683 } else {
684 $this->getOutput()->addHelpLink( $to, $overrideBaseUrl );
685 }
686 }
687
688 /**
689 * Get the group that the special page belongs in on Special:SpecialPage
690 * Use this method, instead of getGroupName to allow customization
691 * of the group name from the wiki side
692 *
693 * @return string Group of this special page
694 * @since 1.21
695 */
696 public function getFinalGroupName() {
697 $name = $this->getName();
698
699 // Allow overbidding the group from the wiki side
700 $msg = $this->msg( 'specialpages-specialpagegroup-' . strtolower( $name ) )->inContentLanguage();
701 if ( !$msg->isBlank() ) {
702 $group = $msg->text();
703 } else {
704 // Than use the group from this object
705 $group = $this->getGroupName();
706 }
707
708 return $group;
709 }
710
711 /**
712 * Indicates whether this special page may perform database writes
713 *
714 * @return bool
715 * @since 1.27
716 */
717 public function doesWrites() {
718 return false;
719 }
720
721 /**
722 * Under which header this special page is listed in Special:SpecialPages
723 * See messages 'specialpages-group-*' for valid names
724 * This method defaults to group 'other'
725 *
726 * @return string
727 * @since 1.21
728 */
729 protected function getGroupName() {
730 return 'other';
731 }
732
733 /**
734 * Call wfTransactionalTimeLimit() if this request was POSTed
735 * @since 1.26
736 */
737 protected function useTransactionalTimeLimit() {
738 if ( $this->getRequest()->wasPosted() ) {
739 wfTransactionalTimeLimit();
740 }
741 }
742 }