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