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