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