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