Title: Don't create mSubpages member variable
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
4 *
5 * See title.txt
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 */
24
25 use Wikimedia\Rdbms\Database;
26 use Wikimedia\Rdbms\IDatabase;
27 use MediaWiki\Linker\LinkTarget;
28 use MediaWiki\Interwiki\InterwikiLookup;
29 use MediaWiki\MediaWikiServices;
30
31 /**
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
38 */
39 class Title implements LinkTarget {
40 /** @var HashBagOStuff */
41 static private $titleCache = null;
42
43 /**
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
47 */
48 const CACHE_MAX = 1000;
49
50 /**
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
53 */
54 const GAID_FOR_UPDATE = 1;
55
56 /**
57 * @name Private member variables
58 * Please use the accessor functions instead.
59 * @private
60 */
61 // @{
62
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
65
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
68
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
71
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
74
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN;
77
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
80
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
83
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
86
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
89
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
92
93 /**
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
96 */
97 private $mContentModel = false;
98
99 /**
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
102 */
103 private $mForcedContentModel = false;
104
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
107
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
110
111 /** @var string|bool */
112 protected $mOldRestrictions = false;
113
114 /** @var bool Cascade restrictions on this page to included templates and images? */
115 public $mCascadeRestriction;
116
117 /** Caching the results of getCascadeProtectionSources */
118 public $mCascadingRestrictions;
119
120 /** @var array When do the restrictions on this page expire? */
121 protected $mRestrictionsExpiry = [];
122
123 /** @var bool Are cascading restrictions in effect on this page? */
124 protected $mHasCascadingRestrictions;
125
126 /** @var array Where are the cascading restrictions coming from on this page? */
127 public $mCascadeSources;
128
129 /** @var bool Boolean for initialisation on demand */
130 public $mRestrictionsLoaded = false;
131
132 /** @var string Text form including namespace/interwiki, initialised on demand */
133 protected $mPrefixedText = null;
134
135 /** @var mixed Cached value for getTitleProtection (create protection) */
136 public $mTitleProtection;
137
138 /**
139 * @var int Namespace index when there is no namespace. Don't change the
140 * following default, NS_MAIN is hardcoded in several places. See T2696.
141 * Zero except in {{transclusion}} tags.
142 */
143 public $mDefaultNamespace = NS_MAIN;
144
145 /** @var int The page length, 0 for special pages */
146 protected $mLength = -1;
147
148 /** @var null Is the article at this title a redirect? */
149 public $mRedirect = null;
150
151 /** @var array Associative array of user ID -> timestamp/false */
152 private $mNotificationTimestamp = [];
153
154 /** @var bool Whether a page has any subpages */
155 private $mHasSubpages;
156
157 /** @var bool The (string) language code of the page's language and content code. */
158 private $mPageLanguage = false;
159
160 /** @var string|bool|null The page language code from the database, null if not saved in
161 * the database or false if not loaded, yet. */
162 private $mDbPageLanguage = false;
163
164 /** @var TitleValue A corresponding TitleValue object */
165 private $mTitleValue = null;
166
167 /** @var bool Would deleting this page be a big deletion? */
168 private $mIsBigDeletion = null;
169 // @}
170
171 /**
172 * B/C kludge: provide a TitleParser for use by Title.
173 * Ideally, Title would have no methods that need this.
174 * Avoid usage of this singleton by using TitleValue
175 * and the associated services when possible.
176 *
177 * @return TitleFormatter
178 */
179 private static function getTitleFormatter() {
180 return MediaWikiServices::getInstance()->getTitleFormatter();
181 }
182
183 /**
184 * B/C kludge: provide an InterwikiLookup for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
188 *
189 * @return InterwikiLookup
190 */
191 private static function getInterwikiLookup() {
192 return MediaWikiServices::getInstance()->getInterwikiLookup();
193 }
194
195 /**
196 * @access protected
197 */
198 function __construct() {
199 }
200
201 /**
202 * Create a new Title from a prefixed DB key
203 *
204 * @param string $key The database key, which has underscores
205 * instead of spaces, possibly including namespace and
206 * interwiki prefixes
207 * @return Title|null Title, or null on an error
208 */
209 public static function newFromDBkey( $key ) {
210 $t = new Title();
211 $t->mDbkeyform = $key;
212
213 try {
214 $t->secureAndSplit();
215 return $t;
216 } catch ( MalformedTitleException $ex ) {
217 return null;
218 }
219 }
220
221 /**
222 * Create a new Title from a TitleValue
223 *
224 * @param TitleValue $titleValue Assumed to be safe.
225 *
226 * @return Title
227 */
228 public static function newFromTitleValue( TitleValue $titleValue ) {
229 return self::newFromLinkTarget( $titleValue );
230 }
231
232 /**
233 * Create a new Title from a LinkTarget
234 *
235 * @param LinkTarget $linkTarget Assumed to be safe.
236 *
237 * @return Title
238 */
239 public static function newFromLinkTarget( LinkTarget $linkTarget ) {
240 if ( $linkTarget instanceof Title ) {
241 // Special case if it's already a Title object
242 return $linkTarget;
243 }
244 return self::makeTitle(
245 $linkTarget->getNamespace(),
246 $linkTarget->getText(),
247 $linkTarget->getFragment(),
248 $linkTarget->getInterwiki()
249 );
250 }
251
252 /**
253 * Create a new Title from text, such as what one would find in a link. De-
254 * codes any HTML entities in the text.
255 *
256 * @param string|int|null $text The link text; spaces, prefixes, and an
257 * initial ':' indicating the main namespace are accepted.
258 * @param int $defaultNamespace The namespace to use if none is specified
259 * by a prefix. If you want to force a specific namespace even if
260 * $text might begin with a namespace prefix, use makeTitle() or
261 * makeTitleSafe().
262 * @throws InvalidArgumentException
263 * @return Title|null Title or null on an error.
264 */
265 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
266 // DWIM: Integers can be passed in here when page titles are used as array keys.
267 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
268 throw new InvalidArgumentException( '$text must be a string.' );
269 }
270 if ( $text === null ) {
271 return null;
272 }
273
274 try {
275 return Title::newFromTextThrow( strval( $text ), $defaultNamespace );
276 } catch ( MalformedTitleException $ex ) {
277 return null;
278 }
279 }
280
281 /**
282 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
283 * rather than returning null.
284 *
285 * The exception subclasses encode detailed information about why the title is invalid.
286 *
287 * @see Title::newFromText
288 *
289 * @since 1.25
290 * @param string $text Title text to check
291 * @param int $defaultNamespace
292 * @throws MalformedTitleException If the title is invalid
293 * @return Title
294 */
295 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
296 if ( is_object( $text ) ) {
297 throw new MWException( '$text must be a string, given an object' );
298 }
299
300 $titleCache = self::getTitleCache();
301
302 // Wiki pages often contain multiple links to the same page.
303 // Title normalization and parsing can become expensive on pages with many
304 // links, so we can save a little time by caching them.
305 // In theory these are value objects and won't get changed...
306 if ( $defaultNamespace == NS_MAIN ) {
307 $t = $titleCache->get( $text );
308 if ( $t ) {
309 return $t;
310 }
311 }
312
313 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
314 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
315
316 $t = new Title();
317 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
318 $t->mDefaultNamespace = intval( $defaultNamespace );
319
320 $t->secureAndSplit();
321 if ( $defaultNamespace == NS_MAIN ) {
322 $titleCache->set( $text, $t );
323 }
324 return $t;
325 }
326
327 /**
328 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
329 *
330 * Example of wrong and broken code:
331 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
332 *
333 * Example of right code:
334 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
335 *
336 * Create a new Title from URL-encoded text. Ensures that
337 * the given title's length does not exceed the maximum.
338 *
339 * @param string $url The title, as might be taken from a URL
340 * @return Title|null The new object, or null on an error
341 */
342 public static function newFromURL( $url ) {
343 $t = new Title();
344
345 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
346 # but some URLs used it as a space replacement and they still come
347 # from some external search tools.
348 if ( strpos( self::legalChars(), '+' ) === false ) {
349 $url = strtr( $url, '+', ' ' );
350 }
351
352 $t->mDbkeyform = strtr( $url, ' ', '_' );
353
354 try {
355 $t->secureAndSplit();
356 return $t;
357 } catch ( MalformedTitleException $ex ) {
358 return null;
359 }
360 }
361
362 /**
363 * @return HashBagOStuff
364 */
365 private static function getTitleCache() {
366 if ( self::$titleCache == null ) {
367 self::$titleCache = new HashBagOStuff( [ 'maxKeys' => self::CACHE_MAX ] );
368 }
369 return self::$titleCache;
370 }
371
372 /**
373 * Returns a list of fields that are to be selected for initializing Title
374 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
375 * whether to include page_content_model.
376 *
377 * @return array
378 */
379 protected static function getSelectFields() {
380 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
381
382 $fields = [
383 'page_namespace', 'page_title', 'page_id',
384 'page_len', 'page_is_redirect', 'page_latest',
385 ];
386
387 if ( $wgContentHandlerUseDB ) {
388 $fields[] = 'page_content_model';
389 }
390
391 if ( $wgPageLanguageUseDB ) {
392 $fields[] = 'page_lang';
393 }
394
395 return $fields;
396 }
397
398 /**
399 * Create a new Title from an article ID
400 *
401 * @param int $id The page_id corresponding to the Title to create
402 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
403 * @return Title|null The new object, or null on an error
404 */
405 public static function newFromID( $id, $flags = 0 ) {
406 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
407 $row = $db->selectRow(
408 'page',
409 self::getSelectFields(),
410 [ 'page_id' => $id ],
411 __METHOD__
412 );
413 if ( $row !== false ) {
414 $title = Title::newFromRow( $row );
415 } else {
416 $title = null;
417 }
418 return $title;
419 }
420
421 /**
422 * Make an array of titles from an array of IDs
423 *
424 * @param int[] $ids Array of IDs
425 * @return Title[] Array of Titles
426 */
427 public static function newFromIDs( $ids ) {
428 if ( !count( $ids ) ) {
429 return [];
430 }
431 $dbr = wfGetDB( DB_REPLICA );
432
433 $res = $dbr->select(
434 'page',
435 self::getSelectFields(),
436 [ 'page_id' => $ids ],
437 __METHOD__
438 );
439
440 $titles = [];
441 foreach ( $res as $row ) {
442 $titles[] = Title::newFromRow( $row );
443 }
444 return $titles;
445 }
446
447 /**
448 * Make a Title object from a DB row
449 *
450 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
451 * @return Title Corresponding Title
452 */
453 public static function newFromRow( $row ) {
454 $t = self::makeTitle( $row->page_namespace, $row->page_title );
455 $t->loadFromRow( $row );
456 return $t;
457 }
458
459 /**
460 * Load Title object fields from a DB row.
461 * If false is given, the title will be treated as non-existing.
462 *
463 * @param stdClass|bool $row Database row
464 */
465 public function loadFromRow( $row ) {
466 if ( $row ) { // page found
467 if ( isset( $row->page_id ) ) {
468 $this->mArticleID = (int)$row->page_id;
469 }
470 if ( isset( $row->page_len ) ) {
471 $this->mLength = (int)$row->page_len;
472 }
473 if ( isset( $row->page_is_redirect ) ) {
474 $this->mRedirect = (bool)$row->page_is_redirect;
475 }
476 if ( isset( $row->page_latest ) ) {
477 $this->mLatestID = (int)$row->page_latest;
478 }
479 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
480 $this->mContentModel = strval( $row->page_content_model );
481 } elseif ( !$this->mForcedContentModel ) {
482 $this->mContentModel = false; # initialized lazily in getContentModel()
483 }
484 if ( isset( $row->page_lang ) ) {
485 $this->mDbPageLanguage = (string)$row->page_lang;
486 }
487 if ( isset( $row->page_restrictions ) ) {
488 $this->mOldRestrictions = $row->page_restrictions;
489 }
490 } else { // page not found
491 $this->mArticleID = 0;
492 $this->mLength = 0;
493 $this->mRedirect = false;
494 $this->mLatestID = 0;
495 if ( !$this->mForcedContentModel ) {
496 $this->mContentModel = false; # initialized lazily in getContentModel()
497 }
498 }
499 }
500
501 /**
502 * Create a new Title from a namespace index and a DB key.
503 * It's assumed that $ns and $title are *valid*, for instance when
504 * they came directly from the database or a special page name.
505 * For convenience, spaces are converted to underscores so that
506 * eg user_text fields can be used directly.
507 *
508 * @param int $ns The namespace of the article
509 * @param string $title The unprefixed database key form
510 * @param string $fragment The link fragment (after the "#")
511 * @param string $interwiki The interwiki prefix
512 * @return Title The new object
513 */
514 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
515 $t = new Title();
516 $t->mInterwiki = $interwiki;
517 $t->mFragment = $fragment;
518 $t->mNamespace = $ns = intval( $ns );
519 $t->mDbkeyform = strtr( $title, ' ', '_' );
520 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
521 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
522 $t->mTextform = strtr( $title, '_', ' ' );
523 $t->mContentModel = false; # initialized lazily in getContentModel()
524 return $t;
525 }
526
527 /**
528 * Create a new Title from a namespace index and a DB key.
529 * The parameters will be checked for validity, which is a bit slower
530 * than makeTitle() but safer for user-provided data.
531 *
532 * @param int $ns The namespace of the article
533 * @param string $title Database key form
534 * @param string $fragment The link fragment (after the "#")
535 * @param string $interwiki Interwiki prefix
536 * @return Title|null The new object, or null on an error
537 */
538 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
539 if ( !MWNamespace::exists( $ns ) ) {
540 return null;
541 }
542
543 $t = new Title();
544 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
545
546 try {
547 $t->secureAndSplit();
548 return $t;
549 } catch ( MalformedTitleException $ex ) {
550 return null;
551 }
552 }
553
554 /**
555 * Create a new Title for the Main Page
556 *
557 * @return Title The new object
558 */
559 public static function newMainPage() {
560 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
561 // Don't give fatal errors if the message is broken
562 if ( !$title ) {
563 $title = Title::newFromText( 'Main Page' );
564 }
565 return $title;
566 }
567
568 /**
569 * Get the prefixed DB key associated with an ID
570 *
571 * @param int $id The page_id of the article
572 * @return Title|null An object representing the article, or null if no such article was found
573 */
574 public static function nameOf( $id ) {
575 $dbr = wfGetDB( DB_REPLICA );
576
577 $s = $dbr->selectRow(
578 'page',
579 [ 'page_namespace', 'page_title' ],
580 [ 'page_id' => $id ],
581 __METHOD__
582 );
583 if ( $s === false ) {
584 return null;
585 }
586
587 $n = self::makeName( $s->page_namespace, $s->page_title );
588 return $n;
589 }
590
591 /**
592 * Get a regex character class describing the legal characters in a link
593 *
594 * @return string The list of characters, not delimited
595 */
596 public static function legalChars() {
597 global $wgLegalTitleChars;
598 return $wgLegalTitleChars;
599 }
600
601 /**
602 * Returns a simple regex that will match on characters and sequences invalid in titles.
603 * Note that this doesn't pick up many things that could be wrong with titles, but that
604 * replacing this regex with something valid will make many titles valid.
605 *
606 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
607 *
608 * @return string Regex string
609 */
610 static function getTitleInvalidRegex() {
611 wfDeprecated( __METHOD__, '1.25' );
612 return MediaWikiTitleCodec::getTitleInvalidRegex();
613 }
614
615 /**
616 * Utility method for converting a character sequence from bytes to Unicode.
617 *
618 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
619 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
620 *
621 * @param string $byteClass
622 * @return string
623 */
624 public static function convertByteClassToUnicodeClass( $byteClass ) {
625 $length = strlen( $byteClass );
626 // Input token queue
627 $x0 = $x1 = $x2 = '';
628 // Decoded queue
629 $d0 = $d1 = $d2 = '';
630 // Decoded integer codepoints
631 $ord0 = $ord1 = $ord2 = 0;
632 // Re-encoded queue
633 $r0 = $r1 = $r2 = '';
634 // Output
635 $out = '';
636 // Flags
637 $allowUnicode = false;
638 for ( $pos = 0; $pos < $length; $pos++ ) {
639 // Shift the queues down
640 $x2 = $x1;
641 $x1 = $x0;
642 $d2 = $d1;
643 $d1 = $d0;
644 $ord2 = $ord1;
645 $ord1 = $ord0;
646 $r2 = $r1;
647 $r1 = $r0;
648 // Load the current input token and decoded values
649 $inChar = $byteClass[$pos];
650 if ( $inChar == '\\' ) {
651 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
652 $x0 = $inChar . $m[0];
653 $d0 = chr( hexdec( $m[1] ) );
654 $pos += strlen( $m[0] );
655 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
656 $x0 = $inChar . $m[0];
657 $d0 = chr( octdec( $m[0] ) );
658 $pos += strlen( $m[0] );
659 } elseif ( $pos + 1 >= $length ) {
660 $x0 = $d0 = '\\';
661 } else {
662 $d0 = $byteClass[$pos + 1];
663 $x0 = $inChar . $d0;
664 $pos += 1;
665 }
666 } else {
667 $x0 = $d0 = $inChar;
668 }
669 $ord0 = ord( $d0 );
670 // Load the current re-encoded value
671 if ( $ord0 < 32 || $ord0 == 0x7f ) {
672 $r0 = sprintf( '\x%02x', $ord0 );
673 } elseif ( $ord0 >= 0x80 ) {
674 // Allow unicode if a single high-bit character appears
675 $r0 = sprintf( '\x%02x', $ord0 );
676 $allowUnicode = true;
677 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
678 $r0 = '\\' . $d0;
679 } else {
680 $r0 = $d0;
681 }
682 // Do the output
683 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
684 // Range
685 if ( $ord2 > $ord0 ) {
686 // Empty range
687 } elseif ( $ord0 >= 0x80 ) {
688 // Unicode range
689 $allowUnicode = true;
690 if ( $ord2 < 0x80 ) {
691 // Keep the non-unicode section of the range
692 $out .= "$r2-\\x7F";
693 }
694 } else {
695 // Normal range
696 $out .= "$r2-$r0";
697 }
698 // Reset state to the initial value
699 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
700 } elseif ( $ord2 < 0x80 ) {
701 // ASCII character
702 $out .= $r2;
703 }
704 }
705 if ( $ord1 < 0x80 ) {
706 $out .= $r1;
707 }
708 if ( $ord0 < 0x80 ) {
709 $out .= $r0;
710 }
711 if ( $allowUnicode ) {
712 $out .= '\u0080-\uFFFF';
713 }
714 return $out;
715 }
716
717 /**
718 * Make a prefixed DB key from a DB key and a namespace index
719 *
720 * @param int $ns Numerical representation of the namespace
721 * @param string $title The DB key form the title
722 * @param string $fragment The link fragment (after the "#")
723 * @param string $interwiki The interwiki prefix
724 * @param bool $canonicalNamespace If true, use the canonical name for
725 * $ns instead of the localized version.
726 * @return string The prefixed form of the title
727 */
728 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
729 $canonicalNamespace = false
730 ) {
731 global $wgContLang;
732
733 if ( $canonicalNamespace ) {
734 $namespace = MWNamespace::getCanonicalName( $ns );
735 } else {
736 $namespace = $wgContLang->getNsText( $ns );
737 }
738 $name = $namespace == '' ? $title : "$namespace:$title";
739 if ( strval( $interwiki ) != '' ) {
740 $name = "$interwiki:$name";
741 }
742 if ( strval( $fragment ) != '' ) {
743 $name .= '#' . $fragment;
744 }
745 return $name;
746 }
747
748 /**
749 * Escape a text fragment, say from a link, for a URL
750 *
751 * @param string $fragment Containing a URL or link fragment (after the "#")
752 * @return string Escaped string
753 */
754 static function escapeFragmentForURL( $fragment ) {
755 # Note that we don't urlencode the fragment. urlencoded Unicode
756 # fragments appear not to work in IE (at least up to 7) or in at least
757 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
758 # to care if they aren't encoded.
759 return Sanitizer::escapeId( $fragment, 'noninitial' );
760 }
761
762 /**
763 * Callback for usort() to do title sorts by (namespace, title)
764 *
765 * @param LinkTarget $a
766 * @param LinkTarget $b
767 *
768 * @return int Result of string comparison, or namespace comparison
769 */
770 public static function compare( LinkTarget $a, LinkTarget $b ) {
771 if ( $a->getNamespace() == $b->getNamespace() ) {
772 return strcmp( $a->getText(), $b->getText() );
773 } else {
774 return $a->getNamespace() - $b->getNamespace();
775 }
776 }
777
778 /**
779 * Determine whether the object refers to a page within
780 * this project (either this wiki or a wiki with a local
781 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
782 *
783 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
784 */
785 public function isLocal() {
786 if ( $this->isExternal() ) {
787 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
788 if ( $iw ) {
789 return $iw->isLocal();
790 }
791 }
792 return true;
793 }
794
795 /**
796 * Is this Title interwiki?
797 *
798 * @return bool
799 */
800 public function isExternal() {
801 return $this->mInterwiki !== '';
802 }
803
804 /**
805 * Get the interwiki prefix
806 *
807 * Use Title::isExternal to check if a interwiki is set
808 *
809 * @return string Interwiki prefix
810 */
811 public function getInterwiki() {
812 return $this->mInterwiki;
813 }
814
815 /**
816 * Was this a local interwiki link?
817 *
818 * @return bool
819 */
820 public function wasLocalInterwiki() {
821 return $this->mLocalInterwiki;
822 }
823
824 /**
825 * Determine whether the object refers to a page within
826 * this project and is transcludable.
827 *
828 * @return bool True if this is transcludable
829 */
830 public function isTrans() {
831 if ( !$this->isExternal() ) {
832 return false;
833 }
834
835 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
836 }
837
838 /**
839 * Returns the DB name of the distant wiki which owns the object.
840 *
841 * @return string|false The DB name
842 */
843 public function getTransWikiID() {
844 if ( !$this->isExternal() ) {
845 return false;
846 }
847
848 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
849 }
850
851 /**
852 * Get a TitleValue object representing this Title.
853 *
854 * @note Not all valid Titles have a corresponding valid TitleValue
855 * (e.g. TitleValues cannot represent page-local links that have a
856 * fragment but no title text).
857 *
858 * @return TitleValue|null
859 */
860 public function getTitleValue() {
861 if ( $this->mTitleValue === null ) {
862 try {
863 $this->mTitleValue = new TitleValue(
864 $this->getNamespace(),
865 $this->getDBkey(),
866 $this->getFragment(),
867 $this->getInterwiki()
868 );
869 } catch ( InvalidArgumentException $ex ) {
870 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
871 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
872 }
873 }
874
875 return $this->mTitleValue;
876 }
877
878 /**
879 * Get the text form (spaces not underscores) of the main part
880 *
881 * @return string Main part of the title
882 */
883 public function getText() {
884 return $this->mTextform;
885 }
886
887 /**
888 * Get the URL-encoded form of the main part
889 *
890 * @return string Main part of the title, URL-encoded
891 */
892 public function getPartialURL() {
893 return $this->mUrlform;
894 }
895
896 /**
897 * Get the main part with underscores
898 *
899 * @return string Main part of the title, with underscores
900 */
901 public function getDBkey() {
902 return $this->mDbkeyform;
903 }
904
905 /**
906 * Get the DB key with the initial letter case as specified by the user
907 *
908 * @return string DB key
909 */
910 function getUserCaseDBKey() {
911 if ( !is_null( $this->mUserCaseDBKey ) ) {
912 return $this->mUserCaseDBKey;
913 } else {
914 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
915 return $this->mDbkeyform;
916 }
917 }
918
919 /**
920 * Get the namespace index, i.e. one of the NS_xxxx constants.
921 *
922 * @return int Namespace index
923 */
924 public function getNamespace() {
925 return $this->mNamespace;
926 }
927
928 /**
929 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
930 *
931 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
932 * @return string Content model id
933 */
934 public function getContentModel( $flags = 0 ) {
935 if ( !$this->mForcedContentModel
936 && ( !$this->mContentModel || $flags === Title::GAID_FOR_UPDATE )
937 && $this->getArticleID( $flags )
938 ) {
939 $linkCache = LinkCache::singleton();
940 $linkCache->addLinkObj( $this ); # in case we already had an article ID
941 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
942 }
943
944 if ( !$this->mContentModel ) {
945 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
946 }
947
948 return $this->mContentModel;
949 }
950
951 /**
952 * Convenience method for checking a title's content model name
953 *
954 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
955 * @return bool True if $this->getContentModel() == $id
956 */
957 public function hasContentModel( $id ) {
958 return $this->getContentModel() == $id;
959 }
960
961 /**
962 * Set a proposed content model for the page for permissions
963 * checking. This does not actually change the content model
964 * of a title!
965 *
966 * Additionally, you should make sure you've checked
967 * ContentHandler::canBeUsedOn() first.
968 *
969 * @since 1.28
970 * @param string $model CONTENT_MODEL_XXX constant
971 */
972 public function setContentModel( $model ) {
973 $this->mContentModel = $model;
974 $this->mForcedContentModel = true;
975 }
976
977 /**
978 * Get the namespace text
979 *
980 * @return string|false Namespace text
981 */
982 public function getNsText() {
983 if ( $this->isExternal() ) {
984 // This probably shouldn't even happen,
985 // but for interwiki transclusion it sometimes does.
986 // Use the canonical namespaces if possible to try to
987 // resolve a foreign namespace.
988 if ( MWNamespace::exists( $this->mNamespace ) ) {
989 return MWNamespace::getCanonicalName( $this->mNamespace );
990 }
991 }
992
993 try {
994 $formatter = self::getTitleFormatter();
995 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
996 } catch ( InvalidArgumentException $ex ) {
997 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
998 return false;
999 }
1000 }
1001
1002 /**
1003 * Get the namespace text of the subject (rather than talk) page
1004 *
1005 * @return string Namespace text
1006 */
1007 public function getSubjectNsText() {
1008 global $wgContLang;
1009 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1010 }
1011
1012 /**
1013 * Get the namespace text of the talk page
1014 *
1015 * @return string Namespace text
1016 */
1017 public function getTalkNsText() {
1018 global $wgContLang;
1019 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1020 }
1021
1022 /**
1023 * Can this title have a corresponding talk page?
1024 *
1025 * @deprecated since 1.30, use canHaveTalkPage() instead.
1026 *
1027 * @return bool True if this title either is a talk page or can have a talk page associated.
1028 */
1029 public function canTalk() {
1030 return $this->canHaveTalkPage();
1031 }
1032
1033 /**
1034 * Can this title have a corresponding talk page?
1035 *
1036 * @see MWNamespace::hasTalkNamespace
1037 *
1038 * @return bool True if this title either is a talk page or can have a talk page associated.
1039 */
1040 public function canHaveTalkPage() {
1041 return MWNamespace::hasTalkNamespace( $this->mNamespace );
1042 }
1043
1044 /**
1045 * Is this in a namespace that allows actual pages?
1046 *
1047 * @return bool
1048 */
1049 public function canExist() {
1050 return $this->mNamespace >= NS_MAIN;
1051 }
1052
1053 /**
1054 * Can this title be added to a user's watchlist?
1055 *
1056 * @return bool
1057 */
1058 public function isWatchable() {
1059 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1060 }
1061
1062 /**
1063 * Returns true if this is a special page.
1064 *
1065 * @return bool
1066 */
1067 public function isSpecialPage() {
1068 return $this->getNamespace() == NS_SPECIAL;
1069 }
1070
1071 /**
1072 * Returns true if this title resolves to the named special page
1073 *
1074 * @param string $name The special page name
1075 * @return bool
1076 */
1077 public function isSpecial( $name ) {
1078 if ( $this->isSpecialPage() ) {
1079 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1080 if ( $name == $thisName ) {
1081 return true;
1082 }
1083 }
1084 return false;
1085 }
1086
1087 /**
1088 * If the Title refers to a special page alias which is not the local default, resolve
1089 * the alias, and localise the name as necessary. Otherwise, return $this
1090 *
1091 * @return Title
1092 */
1093 public function fixSpecialName() {
1094 if ( $this->isSpecialPage() ) {
1095 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1096 if ( $canonicalName ) {
1097 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1098 if ( $localName != $this->mDbkeyform ) {
1099 return Title::makeTitle( NS_SPECIAL, $localName );
1100 }
1101 }
1102 }
1103 return $this;
1104 }
1105
1106 /**
1107 * Returns true if the title is inside the specified namespace.
1108 *
1109 * Please make use of this instead of comparing to getNamespace()
1110 * This function is much more resistant to changes we may make
1111 * to namespaces than code that makes direct comparisons.
1112 * @param int $ns The namespace
1113 * @return bool
1114 * @since 1.19
1115 */
1116 public function inNamespace( $ns ) {
1117 return MWNamespace::equals( $this->getNamespace(), $ns );
1118 }
1119
1120 /**
1121 * Returns true if the title is inside one of the specified namespaces.
1122 *
1123 * @param int|int[] $namespaces,... The namespaces to check for
1124 * @return bool
1125 * @since 1.19
1126 */
1127 public function inNamespaces( /* ... */ ) {
1128 $namespaces = func_get_args();
1129 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1130 $namespaces = $namespaces[0];
1131 }
1132
1133 foreach ( $namespaces as $ns ) {
1134 if ( $this->inNamespace( $ns ) ) {
1135 return true;
1136 }
1137 }
1138
1139 return false;
1140 }
1141
1142 /**
1143 * Returns true if the title has the same subject namespace as the
1144 * namespace specified.
1145 * For example this method will take NS_USER and return true if namespace
1146 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1147 * as their subject namespace.
1148 *
1149 * This is MUCH simpler than individually testing for equivalence
1150 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1151 * @since 1.19
1152 * @param int $ns
1153 * @return bool
1154 */
1155 public function hasSubjectNamespace( $ns ) {
1156 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1157 }
1158
1159 /**
1160 * Is this Title in a namespace which contains content?
1161 * In other words, is this a content page, for the purposes of calculating
1162 * statistics, etc?
1163 *
1164 * @return bool
1165 */
1166 public function isContentPage() {
1167 return MWNamespace::isContent( $this->getNamespace() );
1168 }
1169
1170 /**
1171 * Would anybody with sufficient privileges be able to move this page?
1172 * Some pages just aren't movable.
1173 *
1174 * @return bool
1175 */
1176 public function isMovable() {
1177 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1178 // Interwiki title or immovable namespace. Hooks don't get to override here
1179 return false;
1180 }
1181
1182 $result = true;
1183 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1184 return $result;
1185 }
1186
1187 /**
1188 * Is this the mainpage?
1189 * @note Title::newFromText seems to be sufficiently optimized by the title
1190 * cache that we don't need to over-optimize by doing direct comparisons and
1191 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1192 * ends up reporting something differently than $title->isMainPage();
1193 *
1194 * @since 1.18
1195 * @return bool
1196 */
1197 public function isMainPage() {
1198 return $this->equals( Title::newMainPage() );
1199 }
1200
1201 /**
1202 * Is this a subpage?
1203 *
1204 * @return bool
1205 */
1206 public function isSubpage() {
1207 return MWNamespace::hasSubpages( $this->mNamespace )
1208 ? strpos( $this->getText(), '/' ) !== false
1209 : false;
1210 }
1211
1212 /**
1213 * Is this a conversion table for the LanguageConverter?
1214 *
1215 * @return bool
1216 */
1217 public function isConversionTable() {
1218 // @todo ConversionTable should become a separate content model.
1219
1220 return $this->getNamespace() == NS_MEDIAWIKI &&
1221 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1222 }
1223
1224 /**
1225 * Does that page contain wikitext, or it is JS, CSS or whatever?
1226 *
1227 * @return bool
1228 */
1229 public function isWikitextPage() {
1230 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1231 }
1232
1233 /**
1234 * Could this page contain custom CSS or JavaScript for the global UI.
1235 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1236 * or CONTENT_MODEL_JAVASCRIPT.
1237 *
1238 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1239 * for that!
1240 *
1241 * Note that this method should not return true for pages that contain and
1242 * show "inactive" CSS or JS.
1243 *
1244 * @return bool
1245 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1246 */
1247 public function isCssOrJsPage() {
1248 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1249 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1250 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1251
1252 return $isCssOrJsPage;
1253 }
1254
1255 /**
1256 * Is this a .css or .js subpage of a user page?
1257 * @return bool
1258 * @todo FIXME: Rename to isUserConfigPage()
1259 */
1260 public function isCssJsSubpage() {
1261 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1262 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1263 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1264 }
1265
1266 /**
1267 * Trim down a .css or .js subpage title to get the corresponding skin name
1268 *
1269 * @return string Containing skin name from .css or .js subpage title
1270 */
1271 public function getSkinFromCssJsSubpage() {
1272 $subpage = explode( '/', $this->mTextform );
1273 $subpage = $subpage[count( $subpage ) - 1];
1274 $lastdot = strrpos( $subpage, '.' );
1275 if ( $lastdot === false ) {
1276 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1277 }
1278 return substr( $subpage, 0, $lastdot );
1279 }
1280
1281 /**
1282 * Is this a .css subpage of a user page?
1283 *
1284 * @return bool
1285 */
1286 public function isCssSubpage() {
1287 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1288 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1289 }
1290
1291 /**
1292 * Is this a .js subpage of a user page?
1293 *
1294 * @return bool
1295 */
1296 public function isJsSubpage() {
1297 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1298 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1299 }
1300
1301 /**
1302 * Is this a talk page of some sort?
1303 *
1304 * @return bool
1305 */
1306 public function isTalkPage() {
1307 return MWNamespace::isTalk( $this->getNamespace() );
1308 }
1309
1310 /**
1311 * Get a Title object associated with the talk page of this article
1312 *
1313 * @return Title The object for the talk page
1314 */
1315 public function getTalkPage() {
1316 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1317 }
1318
1319 /**
1320 * Get a title object associated with the subject page of this
1321 * talk page
1322 *
1323 * @return Title The object for the subject page
1324 */
1325 public function getSubjectPage() {
1326 // Is this the same title?
1327 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1328 if ( $this->getNamespace() == $subjectNS ) {
1329 return $this;
1330 }
1331 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1332 }
1333
1334 /**
1335 * Get the other title for this page, if this is a subject page
1336 * get the talk page, if it is a subject page get the talk page
1337 *
1338 * @since 1.25
1339 * @throws MWException
1340 * @return Title
1341 */
1342 public function getOtherPage() {
1343 if ( $this->isSpecialPage() ) {
1344 throw new MWException( 'Special pages cannot have other pages' );
1345 }
1346 if ( $this->isTalkPage() ) {
1347 return $this->getSubjectPage();
1348 } else {
1349 return $this->getTalkPage();
1350 }
1351 }
1352
1353 /**
1354 * Get the default namespace index, for when there is no namespace
1355 *
1356 * @return int Default namespace index
1357 */
1358 public function getDefaultNamespace() {
1359 return $this->mDefaultNamespace;
1360 }
1361
1362 /**
1363 * Get the Title fragment (i.e.\ the bit after the #) in text form
1364 *
1365 * Use Title::hasFragment to check for a fragment
1366 *
1367 * @return string Title fragment
1368 */
1369 public function getFragment() {
1370 return $this->mFragment;
1371 }
1372
1373 /**
1374 * Check if a Title fragment is set
1375 *
1376 * @return bool
1377 * @since 1.23
1378 */
1379 public function hasFragment() {
1380 return $this->mFragment !== '';
1381 }
1382
1383 /**
1384 * Get the fragment in URL form, including the "#" character if there is one
1385 * @return string Fragment in URL form
1386 */
1387 public function getFragmentForURL() {
1388 if ( !$this->hasFragment() ) {
1389 return '';
1390 } else {
1391 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1392 }
1393 }
1394
1395 /**
1396 * Set the fragment for this title. Removes the first character from the
1397 * specified fragment before setting, so it assumes you're passing it with
1398 * an initial "#".
1399 *
1400 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1401 * or Title::createFragmentTarget().
1402 * Still in active use privately.
1403 *
1404 * @private
1405 * @param string $fragment Text
1406 */
1407 public function setFragment( $fragment ) {
1408 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1409 }
1410
1411 /**
1412 * Creates a new Title for a different fragment of the same page.
1413 *
1414 * @since 1.27
1415 * @param string $fragment
1416 * @return Title
1417 */
1418 public function createFragmentTarget( $fragment ) {
1419 return self::makeTitle(
1420 $this->getNamespace(),
1421 $this->getText(),
1422 $fragment,
1423 $this->getInterwiki()
1424 );
1425 }
1426
1427 /**
1428 * Prefix some arbitrary text with the namespace or interwiki prefix
1429 * of this object
1430 *
1431 * @param string $name The text
1432 * @return string The prefixed text
1433 */
1434 private function prefix( $name ) {
1435 global $wgContLang;
1436
1437 $p = '';
1438 if ( $this->isExternal() ) {
1439 $p = $this->mInterwiki . ':';
1440 }
1441
1442 if ( 0 != $this->mNamespace ) {
1443 $nsText = $this->getNsText();
1444
1445 if ( $nsText === false ) {
1446 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1447 $nsText = $wgContLang->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1448 }
1449
1450 $p .= $nsText . ':';
1451 }
1452 return $p . $name;
1453 }
1454
1455 /**
1456 * Get the prefixed database key form
1457 *
1458 * @return string The prefixed title, with underscores and
1459 * any interwiki and namespace prefixes
1460 */
1461 public function getPrefixedDBkey() {
1462 $s = $this->prefix( $this->mDbkeyform );
1463 $s = strtr( $s, ' ', '_' );
1464 return $s;
1465 }
1466
1467 /**
1468 * Get the prefixed title with spaces.
1469 * This is the form usually used for display
1470 *
1471 * @return string The prefixed title, with spaces
1472 */
1473 public function getPrefixedText() {
1474 if ( $this->mPrefixedText === null ) {
1475 $s = $this->prefix( $this->mTextform );
1476 $s = strtr( $s, '_', ' ' );
1477 $this->mPrefixedText = $s;
1478 }
1479 return $this->mPrefixedText;
1480 }
1481
1482 /**
1483 * Return a string representation of this title
1484 *
1485 * @return string Representation of this title
1486 */
1487 public function __toString() {
1488 return $this->getPrefixedText();
1489 }
1490
1491 /**
1492 * Get the prefixed title with spaces, plus any fragment
1493 * (part beginning with '#')
1494 *
1495 * @return string The prefixed title, with spaces and the fragment, including '#'
1496 */
1497 public function getFullText() {
1498 $text = $this->getPrefixedText();
1499 if ( $this->hasFragment() ) {
1500 $text .= '#' . $this->getFragment();
1501 }
1502 return $text;
1503 }
1504
1505 /**
1506 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1507 *
1508 * @par Example:
1509 * @code
1510 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1511 * # returns: 'Foo'
1512 * @endcode
1513 *
1514 * @return string Root name
1515 * @since 1.20
1516 */
1517 public function getRootText() {
1518 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1519 return $this->getText();
1520 }
1521
1522 return strtok( $this->getText(), '/' );
1523 }
1524
1525 /**
1526 * Get the root page name title, i.e. the leftmost part before any slashes
1527 *
1528 * @par Example:
1529 * @code
1530 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1531 * # returns: Title{User:Foo}
1532 * @endcode
1533 *
1534 * @return Title Root title
1535 * @since 1.20
1536 */
1537 public function getRootTitle() {
1538 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1539 }
1540
1541 /**
1542 * Get the base page name without a namespace, i.e. the part before the subpage name
1543 *
1544 * @par Example:
1545 * @code
1546 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1547 * # returns: 'Foo/Bar'
1548 * @endcode
1549 *
1550 * @return string Base name
1551 */
1552 public function getBaseText() {
1553 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1554 return $this->getText();
1555 }
1556
1557 $parts = explode( '/', $this->getText() );
1558 # Don't discard the real title if there's no subpage involved
1559 if ( count( $parts ) > 1 ) {
1560 unset( $parts[count( $parts ) - 1] );
1561 }
1562 return implode( '/', $parts );
1563 }
1564
1565 /**
1566 * Get the base page name title, i.e. the part before the subpage name
1567 *
1568 * @par Example:
1569 * @code
1570 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1571 * # returns: Title{User:Foo/Bar}
1572 * @endcode
1573 *
1574 * @return Title Base title
1575 * @since 1.20
1576 */
1577 public function getBaseTitle() {
1578 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1579 }
1580
1581 /**
1582 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1583 *
1584 * @par Example:
1585 * @code
1586 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1587 * # returns: "Baz"
1588 * @endcode
1589 *
1590 * @return string Subpage name
1591 */
1592 public function getSubpageText() {
1593 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1594 return $this->mTextform;
1595 }
1596 $parts = explode( '/', $this->mTextform );
1597 return $parts[count( $parts ) - 1];
1598 }
1599
1600 /**
1601 * Get the title for a subpage of the current page
1602 *
1603 * @par Example:
1604 * @code
1605 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1606 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1607 * @endcode
1608 *
1609 * @param string $text The subpage name to add to the title
1610 * @return Title Subpage title
1611 * @since 1.20
1612 */
1613 public function getSubpage( $text ) {
1614 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1615 }
1616
1617 /**
1618 * Get a URL-encoded form of the subpage text
1619 *
1620 * @return string URL-encoded subpage name
1621 */
1622 public function getSubpageUrlForm() {
1623 $text = $this->getSubpageText();
1624 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1625 return $text;
1626 }
1627
1628 /**
1629 * Get a URL-encoded title (not an actual URL) including interwiki
1630 *
1631 * @return string The URL-encoded form
1632 */
1633 public function getPrefixedURL() {
1634 $s = $this->prefix( $this->mDbkeyform );
1635 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1636 return $s;
1637 }
1638
1639 /**
1640 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1641 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1642 * second argument named variant. This was deprecated in favor
1643 * of passing an array of option with a "variant" key
1644 * Once $query2 is removed for good, this helper can be dropped
1645 * and the wfArrayToCgi moved to getLocalURL();
1646 *
1647 * @since 1.19 (r105919)
1648 * @param array|string $query
1649 * @param string|string[]|bool $query2
1650 * @return string
1651 */
1652 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1653 if ( $query2 !== false ) {
1654 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1655 "method called with a second parameter is deprecated. Add your " .
1656 "parameter to an array passed as the first parameter.", "1.19" );
1657 }
1658 if ( is_array( $query ) ) {
1659 $query = wfArrayToCgi( $query );
1660 }
1661 if ( $query2 ) {
1662 if ( is_string( $query2 ) ) {
1663 // $query2 is a string, we will consider this to be
1664 // a deprecated $variant argument and add it to the query
1665 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1666 } else {
1667 $query2 = wfArrayToCgi( $query2 );
1668 }
1669 // If we have $query content add a & to it first
1670 if ( $query ) {
1671 $query .= '&';
1672 }
1673 // Now append the queries together
1674 $query .= $query2;
1675 }
1676 return $query;
1677 }
1678
1679 /**
1680 * Get a real URL referring to this title, with interwiki link and
1681 * fragment
1682 *
1683 * @see self::getLocalURL for the arguments.
1684 * @see wfExpandUrl
1685 * @param string|string[] $query
1686 * @param string|string[]|bool $query2
1687 * @param string $proto Protocol type to use in URL
1688 * @return string The URL
1689 */
1690 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1691 $query = self::fixUrlQueryArgs( $query, $query2 );
1692
1693 # Hand off all the decisions on urls to getLocalURL
1694 $url = $this->getLocalURL( $query );
1695
1696 # Expand the url to make it a full url. Note that getLocalURL has the
1697 # potential to output full urls for a variety of reasons, so we use
1698 # wfExpandUrl instead of simply prepending $wgServer
1699 $url = wfExpandUrl( $url, $proto );
1700
1701 # Finally, add the fragment.
1702 $url .= $this->getFragmentForURL();
1703 // Avoid PHP 7.1 warning from passing $this by reference
1704 $titleRef = $this;
1705 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1706 return $url;
1707 }
1708
1709 /**
1710 * Get a url appropriate for making redirects based on an untrusted url arg
1711 *
1712 * This is basically the same as getFullUrl(), but in the case of external
1713 * interwikis, we send the user to a landing page, to prevent possible
1714 * phishing attacks and the like.
1715 *
1716 * @note Uses current protocol by default, since technically relative urls
1717 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1718 * places where the url gets cached, as might pollute between
1719 * https and non-https users.
1720 * @see self::getLocalURL for the arguments.
1721 * @param array|string $query
1722 * @param string $proto Protocol type to use in URL
1723 * @return String. A url suitable to use in an HTTP location header.
1724 */
1725 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
1726 $target = $this;
1727 if ( $this->isExternal() ) {
1728 $target = SpecialPage::getTitleFor(
1729 'GoToInterwiki',
1730 $this->getPrefixedDBKey()
1731 );
1732 }
1733 return $target->getFullUrl( $query, false, $proto );
1734 }
1735
1736 /**
1737 * Get a URL with no fragment or server name (relative URL) from a Title object.
1738 * If this page is generated with action=render, however,
1739 * $wgServer is prepended to make an absolute URL.
1740 *
1741 * @see self::getFullURL to always get an absolute URL.
1742 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1743 * valid to link, locally, to the current Title.
1744 * @see self::newFromText to produce a Title object.
1745 *
1746 * @param string|string[] $query An optional query string,
1747 * not used for interwiki links. Can be specified as an associative array as well,
1748 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1749 * Some query patterns will trigger various shorturl path replacements.
1750 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1751 * be an array. If a string is passed it will be interpreted as a deprecated
1752 * variant argument and urlencoded into a variant= argument.
1753 * This second query argument will be added to the $query
1754 * The second parameter is deprecated since 1.19. Pass it as a key,value
1755 * pair in the first parameter array instead.
1756 *
1757 * @return string String of the URL.
1758 */
1759 public function getLocalURL( $query = '', $query2 = false ) {
1760 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1761
1762 $query = self::fixUrlQueryArgs( $query, $query2 );
1763
1764 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1765 if ( $interwiki ) {
1766 $namespace = $this->getNsText();
1767 if ( $namespace != '' ) {
1768 # Can this actually happen? Interwikis shouldn't be parsed.
1769 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1770 $namespace .= ':';
1771 }
1772 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1773 $url = wfAppendQuery( $url, $query );
1774 } else {
1775 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1776 if ( $query == '' ) {
1777 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1778 // Avoid PHP 7.1 warning from passing $this by reference
1779 $titleRef = $this;
1780 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1781 } else {
1782 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1783 $url = false;
1784 $matches = [];
1785
1786 if ( !empty( $wgActionPaths )
1787 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1788 ) {
1789 $action = urldecode( $matches[2] );
1790 if ( isset( $wgActionPaths[$action] ) ) {
1791 $query = $matches[1];
1792 if ( isset( $matches[4] ) ) {
1793 $query .= $matches[4];
1794 }
1795 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1796 if ( $query != '' ) {
1797 $url = wfAppendQuery( $url, $query );
1798 }
1799 }
1800 }
1801
1802 if ( $url === false
1803 && $wgVariantArticlePath
1804 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1805 && $this->getPageLanguage()->equals( $wgContLang )
1806 && $this->getPageLanguage()->hasVariants()
1807 ) {
1808 $variant = urldecode( $matches[1] );
1809 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1810 // Only do the variant replacement if the given variant is a valid
1811 // variant for the page's language.
1812 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1813 $url = str_replace( '$1', $dbkey, $url );
1814 }
1815 }
1816
1817 if ( $url === false ) {
1818 if ( $query == '-' ) {
1819 $query = '';
1820 }
1821 $url = "{$wgScript}?title={$dbkey}&{$query}";
1822 }
1823 }
1824 // Avoid PHP 7.1 warning from passing $this by reference
1825 $titleRef = $this;
1826 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1827
1828 // @todo FIXME: This causes breakage in various places when we
1829 // actually expected a local URL and end up with dupe prefixes.
1830 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1831 $url = $wgServer . $url;
1832 }
1833 }
1834 // Avoid PHP 7.1 warning from passing $this by reference
1835 $titleRef = $this;
1836 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1837 return $url;
1838 }
1839
1840 /**
1841 * Get a URL that's the simplest URL that will be valid to link, locally,
1842 * to the current Title. It includes the fragment, but does not include
1843 * the server unless action=render is used (or the link is external). If
1844 * there's a fragment but the prefixed text is empty, we just return a link
1845 * to the fragment.
1846 *
1847 * The result obviously should not be URL-escaped, but does need to be
1848 * HTML-escaped if it's being output in HTML.
1849 *
1850 * @param string|string[] $query
1851 * @param bool $query2
1852 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1853 * or false (default) for no expansion
1854 * @see self::getLocalURL for the arguments.
1855 * @return string The URL
1856 */
1857 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1858 if ( $this->isExternal() || $proto !== false ) {
1859 $ret = $this->getFullURL( $query, $query2, $proto );
1860 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1861 $ret = $this->getFragmentForURL();
1862 } else {
1863 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1864 }
1865 return $ret;
1866 }
1867
1868 /**
1869 * Get the URL form for an internal link.
1870 * - Used in various CDN-related code, in case we have a different
1871 * internal hostname for the server from the exposed one.
1872 *
1873 * This uses $wgInternalServer to qualify the path, or $wgServer
1874 * if $wgInternalServer is not set. If the server variable used is
1875 * protocol-relative, the URL will be expanded to http://
1876 *
1877 * @see self::getLocalURL for the arguments.
1878 * @return string The URL
1879 */
1880 public function getInternalURL( $query = '', $query2 = false ) {
1881 global $wgInternalServer, $wgServer;
1882 $query = self::fixUrlQueryArgs( $query, $query2 );
1883 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1884 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1885 // Avoid PHP 7.1 warning from passing $this by reference
1886 $titleRef = $this;
1887 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1888 return $url;
1889 }
1890
1891 /**
1892 * Get the URL for a canonical link, for use in things like IRC and
1893 * e-mail notifications. Uses $wgCanonicalServer and the
1894 * GetCanonicalURL hook.
1895 *
1896 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1897 *
1898 * @see self::getLocalURL for the arguments.
1899 * @return string The URL
1900 * @since 1.18
1901 */
1902 public function getCanonicalURL( $query = '', $query2 = false ) {
1903 $query = self::fixUrlQueryArgs( $query, $query2 );
1904 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1905 // Avoid PHP 7.1 warning from passing $this by reference
1906 $titleRef = $this;
1907 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1908 return $url;
1909 }
1910
1911 /**
1912 * Get the edit URL for this Title
1913 *
1914 * @return string The URL, or a null string if this is an interwiki link
1915 */
1916 public function getEditURL() {
1917 if ( $this->isExternal() ) {
1918 return '';
1919 }
1920 $s = $this->getLocalURL( 'action=edit' );
1921
1922 return $s;
1923 }
1924
1925 /**
1926 * Can $user perform $action on this page?
1927 * This skips potentially expensive cascading permission checks
1928 * as well as avoids expensive error formatting
1929 *
1930 * Suitable for use for nonessential UI controls in common cases, but
1931 * _not_ for functional access control.
1932 *
1933 * May provide false positives, but should never provide a false negative.
1934 *
1935 * @param string $action Action that permission needs to be checked for
1936 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1937 * @return bool
1938 */
1939 public function quickUserCan( $action, $user = null ) {
1940 return $this->userCan( $action, $user, false );
1941 }
1942
1943 /**
1944 * Can $user perform $action on this page?
1945 *
1946 * @param string $action Action that permission needs to be checked for
1947 * @param User $user User to check (since 1.19); $wgUser will be used if not
1948 * provided.
1949 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1950 * @return bool
1951 */
1952 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1953 if ( !$user instanceof User ) {
1954 global $wgUser;
1955 $user = $wgUser;
1956 }
1957
1958 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1959 }
1960
1961 /**
1962 * Can $user perform $action on this page?
1963 *
1964 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1965 *
1966 * @param string $action Action that permission needs to be checked for
1967 * @param User $user User to check
1968 * @param string $rigor One of (quick,full,secure)
1969 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1970 * - full : does cheap and expensive checks possibly from a replica DB
1971 * - secure : does cheap and expensive checks, using the master as needed
1972 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1973 * whose corresponding errors may be ignored.
1974 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1975 */
1976 public function getUserPermissionsErrors(
1977 $action, $user, $rigor = 'secure', $ignoreErrors = []
1978 ) {
1979 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1980
1981 // Remove the errors being ignored.
1982 foreach ( $errors as $index => $error ) {
1983 $errKey = is_array( $error ) ? $error[0] : $error;
1984
1985 if ( in_array( $errKey, $ignoreErrors ) ) {
1986 unset( $errors[$index] );
1987 }
1988 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
1989 unset( $errors[$index] );
1990 }
1991 }
1992
1993 return $errors;
1994 }
1995
1996 /**
1997 * Permissions checks that fail most often, and which are easiest to test.
1998 *
1999 * @param string $action The action to check
2000 * @param User $user User to check
2001 * @param array $errors List of current errors
2002 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2003 * @param bool $short Short circuit on first error
2004 *
2005 * @return array List of errors
2006 */
2007 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2008 if ( !Hooks::run( 'TitleQuickPermissions',
2009 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2010 ) {
2011 return $errors;
2012 }
2013
2014 if ( $action == 'create' ) {
2015 if (
2016 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2017 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2018 ) {
2019 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2020 }
2021 } elseif ( $action == 'move' ) {
2022 if ( !$user->isAllowed( 'move-rootuserpages' )
2023 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2024 // Show user page-specific message only if the user can move other pages
2025 $errors[] = [ 'cant-move-user-page' ];
2026 }
2027
2028 // Check if user is allowed to move files if it's a file
2029 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2030 $errors[] = [ 'movenotallowedfile' ];
2031 }
2032
2033 // Check if user is allowed to move category pages if it's a category page
2034 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2035 $errors[] = [ 'cant-move-category-page' ];
2036 }
2037
2038 if ( !$user->isAllowed( 'move' ) ) {
2039 // User can't move anything
2040 $userCanMove = User::groupHasPermission( 'user', 'move' );
2041 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2042 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2043 // custom message if logged-in users without any special rights can move
2044 $errors[] = [ 'movenologintext' ];
2045 } else {
2046 $errors[] = [ 'movenotallowed' ];
2047 }
2048 }
2049 } elseif ( $action == 'move-target' ) {
2050 if ( !$user->isAllowed( 'move' ) ) {
2051 // User can't move anything
2052 $errors[] = [ 'movenotallowed' ];
2053 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2054 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2055 // Show user page-specific message only if the user can move other pages
2056 $errors[] = [ 'cant-move-to-user-page' ];
2057 } elseif ( !$user->isAllowed( 'move-categorypages' )
2058 && $this->mNamespace == NS_CATEGORY ) {
2059 // Show category page-specific message only if the user can move other pages
2060 $errors[] = [ 'cant-move-to-category-page' ];
2061 }
2062 } elseif ( !$user->isAllowed( $action ) ) {
2063 $errors[] = $this->missingPermissionError( $action, $short );
2064 }
2065
2066 return $errors;
2067 }
2068
2069 /**
2070 * Add the resulting error code to the errors array
2071 *
2072 * @param array $errors List of current errors
2073 * @param array $result Result of errors
2074 *
2075 * @return array List of errors
2076 */
2077 private function resultToError( $errors, $result ) {
2078 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2079 // A single array representing an error
2080 $errors[] = $result;
2081 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2082 // A nested array representing multiple errors
2083 $errors = array_merge( $errors, $result );
2084 } elseif ( $result !== '' && is_string( $result ) ) {
2085 // A string representing a message-id
2086 $errors[] = [ $result ];
2087 } elseif ( $result instanceof MessageSpecifier ) {
2088 // A message specifier representing an error
2089 $errors[] = [ $result ];
2090 } elseif ( $result === false ) {
2091 // a generic "We don't want them to do that"
2092 $errors[] = [ 'badaccess-group0' ];
2093 }
2094 return $errors;
2095 }
2096
2097 /**
2098 * Check various permission hooks
2099 *
2100 * @param string $action The action to check
2101 * @param User $user User to check
2102 * @param array $errors List of current errors
2103 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2104 * @param bool $short Short circuit on first error
2105 *
2106 * @return array List of errors
2107 */
2108 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2109 // Use getUserPermissionsErrors instead
2110 $result = '';
2111 // Avoid PHP 7.1 warning from passing $this by reference
2112 $titleRef = $this;
2113 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2114 return $result ? [] : [ [ 'badaccess-group0' ] ];
2115 }
2116 // Check getUserPermissionsErrors hook
2117 // Avoid PHP 7.1 warning from passing $this by reference
2118 $titleRef = $this;
2119 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2120 $errors = $this->resultToError( $errors, $result );
2121 }
2122 // Check getUserPermissionsErrorsExpensive hook
2123 if (
2124 $rigor !== 'quick'
2125 && !( $short && count( $errors ) > 0 )
2126 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2127 ) {
2128 $errors = $this->resultToError( $errors, $result );
2129 }
2130
2131 return $errors;
2132 }
2133
2134 /**
2135 * Check permissions on special pages & namespaces
2136 *
2137 * @param string $action The action to check
2138 * @param User $user User to check
2139 * @param array $errors List of current errors
2140 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2141 * @param bool $short Short circuit on first error
2142 *
2143 * @return array List of errors
2144 */
2145 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2146 # Only 'createaccount' can be performed on special pages,
2147 # which don't actually exist in the DB.
2148 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2149 $errors[] = [ 'ns-specialprotected' ];
2150 }
2151
2152 # Check $wgNamespaceProtection for restricted namespaces
2153 if ( $this->isNamespaceProtected( $user ) ) {
2154 $ns = $this->mNamespace == NS_MAIN ?
2155 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2156 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2157 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2158 }
2159
2160 return $errors;
2161 }
2162
2163 /**
2164 * Check CSS/JS sub-page permissions
2165 *
2166 * @param string $action The action to check
2167 * @param User $user User to check
2168 * @param array $errors List of current errors
2169 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2170 * @param bool $short Short circuit on first error
2171 *
2172 * @return array List of errors
2173 */
2174 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2175 # Protect css/js subpages of user pages
2176 # XXX: this might be better using restrictions
2177 if ( $action != 'patrol' ) {
2178 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2179 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2180 $errors[] = [ 'mycustomcssprotected', $action ];
2181 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2182 $errors[] = [ 'mycustomjsprotected', $action ];
2183 }
2184 } else {
2185 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2186 $errors[] = [ 'customcssprotected', $action ];
2187 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2188 $errors[] = [ 'customjsprotected', $action ];
2189 }
2190 }
2191 }
2192
2193 return $errors;
2194 }
2195
2196 /**
2197 * Check against page_restrictions table requirements on this
2198 * page. The user must possess all required rights for this
2199 * action.
2200 *
2201 * @param string $action The action to check
2202 * @param User $user User to check
2203 * @param array $errors List of current errors
2204 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2205 * @param bool $short Short circuit on first error
2206 *
2207 * @return array List of errors
2208 */
2209 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2210 foreach ( $this->getRestrictions( $action ) as $right ) {
2211 // Backwards compatibility, rewrite sysop -> editprotected
2212 if ( $right == 'sysop' ) {
2213 $right = 'editprotected';
2214 }
2215 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2216 if ( $right == 'autoconfirmed' ) {
2217 $right = 'editsemiprotected';
2218 }
2219 if ( $right == '' ) {
2220 continue;
2221 }
2222 if ( !$user->isAllowed( $right ) ) {
2223 $errors[] = [ 'protectedpagetext', $right, $action ];
2224 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2225 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2226 }
2227 }
2228
2229 return $errors;
2230 }
2231
2232 /**
2233 * Check restrictions on cascading pages.
2234 *
2235 * @param string $action The action to check
2236 * @param User $user User to check
2237 * @param array $errors List of current errors
2238 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2239 * @param bool $short Short circuit on first error
2240 *
2241 * @return array List of errors
2242 */
2243 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2244 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2245 # We /could/ use the protection level on the source page, but it's
2246 # fairly ugly as we have to establish a precedence hierarchy for pages
2247 # included by multiple cascade-protected pages. So just restrict
2248 # it to people with 'protect' permission, as they could remove the
2249 # protection anyway.
2250 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2251 # Cascading protection depends on more than this page...
2252 # Several cascading protected pages may include this page...
2253 # Check each cascading level
2254 # This is only for protection restrictions, not for all actions
2255 if ( isset( $restrictions[$action] ) ) {
2256 foreach ( $restrictions[$action] as $right ) {
2257 // Backwards compatibility, rewrite sysop -> editprotected
2258 if ( $right == 'sysop' ) {
2259 $right = 'editprotected';
2260 }
2261 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2262 if ( $right == 'autoconfirmed' ) {
2263 $right = 'editsemiprotected';
2264 }
2265 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2266 $pages = '';
2267 foreach ( $cascadingSources as $page ) {
2268 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2269 }
2270 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2271 }
2272 }
2273 }
2274 }
2275
2276 return $errors;
2277 }
2278
2279 /**
2280 * Check action permissions not already checked in checkQuickPermissions
2281 *
2282 * @param string $action The action to check
2283 * @param User $user User to check
2284 * @param array $errors List of current errors
2285 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2286 * @param bool $short Short circuit on first error
2287 *
2288 * @return array List of errors
2289 */
2290 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2291 global $wgDeleteRevisionsLimit, $wgLang;
2292
2293 if ( $action == 'protect' ) {
2294 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2295 // If they can't edit, they shouldn't protect.
2296 $errors[] = [ 'protect-cantedit' ];
2297 }
2298 } elseif ( $action == 'create' ) {
2299 $title_protection = $this->getTitleProtection();
2300 if ( $title_protection ) {
2301 if ( $title_protection['permission'] == ''
2302 || !$user->isAllowed( $title_protection['permission'] )
2303 ) {
2304 $errors[] = [
2305 'titleprotected',
2306 User::whoIs( $title_protection['user'] ),
2307 $title_protection['reason']
2308 ];
2309 }
2310 }
2311 } elseif ( $action == 'move' ) {
2312 // Check for immobile pages
2313 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2314 // Specific message for this case
2315 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2316 } elseif ( !$this->isMovable() ) {
2317 // Less specific message for rarer cases
2318 $errors[] = [ 'immobile-source-page' ];
2319 }
2320 } elseif ( $action == 'move-target' ) {
2321 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2322 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2323 } elseif ( !$this->isMovable() ) {
2324 $errors[] = [ 'immobile-target-page' ];
2325 }
2326 } elseif ( $action == 'delete' ) {
2327 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2328 if ( !$tempErrors ) {
2329 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2330 $user, $tempErrors, $rigor, true );
2331 }
2332 if ( $tempErrors ) {
2333 // If protection keeps them from editing, they shouldn't be able to delete.
2334 $errors[] = [ 'deleteprotected' ];
2335 }
2336 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2337 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2338 ) {
2339 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2340 }
2341 } elseif ( $action === 'undelete' ) {
2342 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2343 // Undeleting implies editing
2344 $errors[] = [ 'undelete-cantedit' ];
2345 }
2346 if ( !$this->exists()
2347 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2348 ) {
2349 // Undeleting where nothing currently exists implies creating
2350 $errors[] = [ 'undelete-cantcreate' ];
2351 }
2352 }
2353 return $errors;
2354 }
2355
2356 /**
2357 * Check that the user isn't blocked from editing.
2358 *
2359 * @param string $action The action to check
2360 * @param User $user User to check
2361 * @param array $errors List of current errors
2362 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2363 * @param bool $short Short circuit on first error
2364 *
2365 * @return array List of errors
2366 */
2367 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2368 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2369 // Account creation blocks handled at userlogin.
2370 // Unblocking handled in SpecialUnblock
2371 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2372 return $errors;
2373 }
2374
2375 // Optimize for a very common case
2376 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2377 return $errors;
2378 }
2379
2380 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2381 $errors[] = [ 'confirmedittext' ];
2382 }
2383
2384 $useSlave = ( $rigor !== 'secure' );
2385 if ( ( $action == 'edit' || $action == 'create' )
2386 && !$user->isBlockedFrom( $this, $useSlave )
2387 ) {
2388 // Don't block the user from editing their own talk page unless they've been
2389 // explicitly blocked from that too.
2390 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2391 // @todo FIXME: Pass the relevant context into this function.
2392 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2393 }
2394
2395 return $errors;
2396 }
2397
2398 /**
2399 * Check that the user is allowed to read this page.
2400 *
2401 * @param string $action The action to check
2402 * @param User $user User to check
2403 * @param array $errors List of current errors
2404 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2405 * @param bool $short Short circuit on first error
2406 *
2407 * @return array List of errors
2408 */
2409 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2410 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2411
2412 $whitelisted = false;
2413 if ( User::isEveryoneAllowed( 'read' ) ) {
2414 # Shortcut for public wikis, allows skipping quite a bit of code
2415 $whitelisted = true;
2416 } elseif ( $user->isAllowed( 'read' ) ) {
2417 # If the user is allowed to read pages, he is allowed to read all pages
2418 $whitelisted = true;
2419 } elseif ( $this->isSpecial( 'Userlogin' )
2420 || $this->isSpecial( 'PasswordReset' )
2421 || $this->isSpecial( 'Userlogout' )
2422 ) {
2423 # Always grant access to the login page.
2424 # Even anons need to be able to log in.
2425 $whitelisted = true;
2426 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2427 # Time to check the whitelist
2428 # Only do these checks is there's something to check against
2429 $name = $this->getPrefixedText();
2430 $dbName = $this->getPrefixedDBkey();
2431
2432 // Check for explicit whitelisting with and without underscores
2433 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2434 $whitelisted = true;
2435 } elseif ( $this->getNamespace() == NS_MAIN ) {
2436 # Old settings might have the title prefixed with
2437 # a colon for main-namespace pages
2438 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2439 $whitelisted = true;
2440 }
2441 } elseif ( $this->isSpecialPage() ) {
2442 # If it's a special page, ditch the subpage bit and check again
2443 $name = $this->getDBkey();
2444 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2445 if ( $name ) {
2446 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2447 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2448 $whitelisted = true;
2449 }
2450 }
2451 }
2452 }
2453
2454 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2455 $name = $this->getPrefixedText();
2456 // Check for regex whitelisting
2457 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2458 if ( preg_match( $listItem, $name ) ) {
2459 $whitelisted = true;
2460 break;
2461 }
2462 }
2463 }
2464
2465 if ( !$whitelisted ) {
2466 # If the title is not whitelisted, give extensions a chance to do so...
2467 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2468 if ( !$whitelisted ) {
2469 $errors[] = $this->missingPermissionError( $action, $short );
2470 }
2471 }
2472
2473 return $errors;
2474 }
2475
2476 /**
2477 * Get a description array when the user doesn't have the right to perform
2478 * $action (i.e. when User::isAllowed() returns false)
2479 *
2480 * @param string $action The action to check
2481 * @param bool $short Short circuit on first error
2482 * @return array Array containing an error message key and any parameters
2483 */
2484 private function missingPermissionError( $action, $short ) {
2485 // We avoid expensive display logic for quickUserCan's and such
2486 if ( $short ) {
2487 return [ 'badaccess-group0' ];
2488 }
2489
2490 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2491 }
2492
2493 /**
2494 * Can $user perform $action on this page? This is an internal function,
2495 * with multiple levels of checks depending on performance needs; see $rigor below.
2496 * It does not check wfReadOnly().
2497 *
2498 * @param string $action Action that permission needs to be checked for
2499 * @param User $user User to check
2500 * @param string $rigor One of (quick,full,secure)
2501 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2502 * - full : does cheap and expensive checks possibly from a replica DB
2503 * - secure : does cheap and expensive checks, using the master as needed
2504 * @param bool $short Set this to true to stop after the first permission error.
2505 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2506 */
2507 protected function getUserPermissionsErrorsInternal(
2508 $action, $user, $rigor = 'secure', $short = false
2509 ) {
2510 if ( $rigor === true ) {
2511 $rigor = 'secure'; // b/c
2512 } elseif ( $rigor === false ) {
2513 $rigor = 'quick'; // b/c
2514 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2515 throw new Exception( "Invalid rigor parameter '$rigor'." );
2516 }
2517
2518 # Read has special handling
2519 if ( $action == 'read' ) {
2520 $checks = [
2521 'checkPermissionHooks',
2522 'checkReadPermissions',
2523 'checkUserBlock', // for wgBlockDisablesLogin
2524 ];
2525 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2526 # here as it will lead to duplicate error messages. This is okay to do
2527 # since anywhere that checks for create will also check for edit, and
2528 # those checks are called for edit.
2529 } elseif ( $action == 'create' ) {
2530 $checks = [
2531 'checkQuickPermissions',
2532 'checkPermissionHooks',
2533 'checkPageRestrictions',
2534 'checkCascadingSourcesRestrictions',
2535 'checkActionPermissions',
2536 'checkUserBlock'
2537 ];
2538 } else {
2539 $checks = [
2540 'checkQuickPermissions',
2541 'checkPermissionHooks',
2542 'checkSpecialsAndNSPermissions',
2543 'checkCSSandJSPermissions',
2544 'checkPageRestrictions',
2545 'checkCascadingSourcesRestrictions',
2546 'checkActionPermissions',
2547 'checkUserBlock'
2548 ];
2549 }
2550
2551 $errors = [];
2552 while ( count( $checks ) > 0 &&
2553 !( $short && count( $errors ) > 0 ) ) {
2554 $method = array_shift( $checks );
2555 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2556 }
2557
2558 return $errors;
2559 }
2560
2561 /**
2562 * Get a filtered list of all restriction types supported by this wiki.
2563 * @param bool $exists True to get all restriction types that apply to
2564 * titles that do exist, False for all restriction types that apply to
2565 * titles that do not exist
2566 * @return array
2567 */
2568 public static function getFilteredRestrictionTypes( $exists = true ) {
2569 global $wgRestrictionTypes;
2570 $types = $wgRestrictionTypes;
2571 if ( $exists ) {
2572 # Remove the create restriction for existing titles
2573 $types = array_diff( $types, [ 'create' ] );
2574 } else {
2575 # Only the create and upload restrictions apply to non-existing titles
2576 $types = array_intersect( $types, [ 'create', 'upload' ] );
2577 }
2578 return $types;
2579 }
2580
2581 /**
2582 * Returns restriction types for the current Title
2583 *
2584 * @return array Applicable restriction types
2585 */
2586 public function getRestrictionTypes() {
2587 if ( $this->isSpecialPage() ) {
2588 return [];
2589 }
2590
2591 $types = self::getFilteredRestrictionTypes( $this->exists() );
2592
2593 if ( $this->getNamespace() != NS_FILE ) {
2594 # Remove the upload restriction for non-file titles
2595 $types = array_diff( $types, [ 'upload' ] );
2596 }
2597
2598 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2599
2600 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2601 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2602
2603 return $types;
2604 }
2605
2606 /**
2607 * Is this title subject to title protection?
2608 * Title protection is the one applied against creation of such title.
2609 *
2610 * @return array|bool An associative array representing any existent title
2611 * protection, or false if there's none.
2612 */
2613 public function getTitleProtection() {
2614 $protection = $this->getTitleProtectionInternal();
2615 if ( $protection ) {
2616 if ( $protection['permission'] == 'sysop' ) {
2617 $protection['permission'] = 'editprotected'; // B/C
2618 }
2619 if ( $protection['permission'] == 'autoconfirmed' ) {
2620 $protection['permission'] = 'editsemiprotected'; // B/C
2621 }
2622 }
2623 return $protection;
2624 }
2625
2626 /**
2627 * Fetch title protection settings
2628 *
2629 * To work correctly, $this->loadRestrictions() needs to have access to the
2630 * actual protections in the database without munging 'sysop' =>
2631 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2632 * callers probably want $this->getTitleProtection() instead.
2633 *
2634 * @return array|bool
2635 */
2636 protected function getTitleProtectionInternal() {
2637 // Can't protect pages in special namespaces
2638 if ( $this->getNamespace() < 0 ) {
2639 return false;
2640 }
2641
2642 // Can't protect pages that exist.
2643 if ( $this->exists() ) {
2644 return false;
2645 }
2646
2647 if ( $this->mTitleProtection === null ) {
2648 $dbr = wfGetDB( DB_REPLICA );
2649 $res = $dbr->select(
2650 'protected_titles',
2651 [
2652 'user' => 'pt_user',
2653 'reason' => 'pt_reason',
2654 'expiry' => 'pt_expiry',
2655 'permission' => 'pt_create_perm'
2656 ],
2657 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2658 __METHOD__
2659 );
2660
2661 // fetchRow returns false if there are no rows.
2662 $row = $dbr->fetchRow( $res );
2663 if ( $row ) {
2664 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2665 }
2666 $this->mTitleProtection = $row;
2667 }
2668 return $this->mTitleProtection;
2669 }
2670
2671 /**
2672 * Remove any title protection due to page existing
2673 */
2674 public function deleteTitleProtection() {
2675 $dbw = wfGetDB( DB_MASTER );
2676
2677 $dbw->delete(
2678 'protected_titles',
2679 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2680 __METHOD__
2681 );
2682 $this->mTitleProtection = false;
2683 }
2684
2685 /**
2686 * Is this page "semi-protected" - the *only* protection levels are listed
2687 * in $wgSemiprotectedRestrictionLevels?
2688 *
2689 * @param string $action Action to check (default: edit)
2690 * @return bool
2691 */
2692 public function isSemiProtected( $action = 'edit' ) {
2693 global $wgSemiprotectedRestrictionLevels;
2694
2695 $restrictions = $this->getRestrictions( $action );
2696 $semi = $wgSemiprotectedRestrictionLevels;
2697 if ( !$restrictions || !$semi ) {
2698 // Not protected, or all protection is full protection
2699 return false;
2700 }
2701
2702 // Remap autoconfirmed to editsemiprotected for BC
2703 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2704 $semi[$key] = 'editsemiprotected';
2705 }
2706 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2707 $restrictions[$key] = 'editsemiprotected';
2708 }
2709
2710 return !array_diff( $restrictions, $semi );
2711 }
2712
2713 /**
2714 * Does the title correspond to a protected article?
2715 *
2716 * @param string $action The action the page is protected from,
2717 * by default checks all actions.
2718 * @return bool
2719 */
2720 public function isProtected( $action = '' ) {
2721 global $wgRestrictionLevels;
2722
2723 $restrictionTypes = $this->getRestrictionTypes();
2724
2725 # Special pages have inherent protection
2726 if ( $this->isSpecialPage() ) {
2727 return true;
2728 }
2729
2730 # Check regular protection levels
2731 foreach ( $restrictionTypes as $type ) {
2732 if ( $action == $type || $action == '' ) {
2733 $r = $this->getRestrictions( $type );
2734 foreach ( $wgRestrictionLevels as $level ) {
2735 if ( in_array( $level, $r ) && $level != '' ) {
2736 return true;
2737 }
2738 }
2739 }
2740 }
2741
2742 return false;
2743 }
2744
2745 /**
2746 * Determines if $user is unable to edit this page because it has been protected
2747 * by $wgNamespaceProtection.
2748 *
2749 * @param User $user User object to check permissions
2750 * @return bool
2751 */
2752 public function isNamespaceProtected( User $user ) {
2753 global $wgNamespaceProtection;
2754
2755 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2756 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2757 if ( $right != '' && !$user->isAllowed( $right ) ) {
2758 return true;
2759 }
2760 }
2761 }
2762 return false;
2763 }
2764
2765 /**
2766 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2767 *
2768 * @return bool If the page is subject to cascading restrictions.
2769 */
2770 public function isCascadeProtected() {
2771 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2772 return ( $sources > 0 );
2773 }
2774
2775 /**
2776 * Determines whether cascading protection sources have already been loaded from
2777 * the database.
2778 *
2779 * @param bool $getPages True to check if the pages are loaded, or false to check
2780 * if the status is loaded.
2781 * @return bool Whether or not the specified information has been loaded
2782 * @since 1.23
2783 */
2784 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2785 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2786 }
2787
2788 /**
2789 * Cascading protection: Get the source of any cascading restrictions on this page.
2790 *
2791 * @param bool $getPages Whether or not to retrieve the actual pages
2792 * that the restrictions have come from and the actual restrictions
2793 * themselves.
2794 * @return array Two elements: First is an array of Title objects of the
2795 * pages from which cascading restrictions have come, false for
2796 * none, or true if such restrictions exist but $getPages was not
2797 * set. Second is an array like that returned by
2798 * Title::getAllRestrictions(), or an empty array if $getPages is
2799 * false.
2800 */
2801 public function getCascadeProtectionSources( $getPages = true ) {
2802 $pagerestrictions = [];
2803
2804 if ( $this->mCascadeSources !== null && $getPages ) {
2805 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2806 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2807 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2808 }
2809
2810 $dbr = wfGetDB( DB_REPLICA );
2811
2812 if ( $this->getNamespace() == NS_FILE ) {
2813 $tables = [ 'imagelinks', 'page_restrictions' ];
2814 $where_clauses = [
2815 'il_to' => $this->getDBkey(),
2816 'il_from=pr_page',
2817 'pr_cascade' => 1
2818 ];
2819 } else {
2820 $tables = [ 'templatelinks', 'page_restrictions' ];
2821 $where_clauses = [
2822 'tl_namespace' => $this->getNamespace(),
2823 'tl_title' => $this->getDBkey(),
2824 'tl_from=pr_page',
2825 'pr_cascade' => 1
2826 ];
2827 }
2828
2829 if ( $getPages ) {
2830 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2831 'pr_expiry', 'pr_type', 'pr_level' ];
2832 $where_clauses[] = 'page_id=pr_page';
2833 $tables[] = 'page';
2834 } else {
2835 $cols = [ 'pr_expiry' ];
2836 }
2837
2838 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2839
2840 $sources = $getPages ? [] : false;
2841 $now = wfTimestampNow();
2842
2843 foreach ( $res as $row ) {
2844 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2845 if ( $expiry > $now ) {
2846 if ( $getPages ) {
2847 $page_id = $row->pr_page;
2848 $page_ns = $row->page_namespace;
2849 $page_title = $row->page_title;
2850 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2851 # Add groups needed for each restriction type if its not already there
2852 # Make sure this restriction type still exists
2853
2854 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2855 $pagerestrictions[$row->pr_type] = [];
2856 }
2857
2858 if (
2859 isset( $pagerestrictions[$row->pr_type] )
2860 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2861 ) {
2862 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2863 }
2864 } else {
2865 $sources = true;
2866 }
2867 }
2868 }
2869
2870 if ( $getPages ) {
2871 $this->mCascadeSources = $sources;
2872 $this->mCascadingRestrictions = $pagerestrictions;
2873 } else {
2874 $this->mHasCascadingRestrictions = $sources;
2875 }
2876
2877 return [ $sources, $pagerestrictions ];
2878 }
2879
2880 /**
2881 * Accessor for mRestrictionsLoaded
2882 *
2883 * @return bool Whether or not the page's restrictions have already been
2884 * loaded from the database
2885 * @since 1.23
2886 */
2887 public function areRestrictionsLoaded() {
2888 return $this->mRestrictionsLoaded;
2889 }
2890
2891 /**
2892 * Accessor/initialisation for mRestrictions
2893 *
2894 * @param string $action Action that permission needs to be checked for
2895 * @return array Restriction levels needed to take the action. All levels are
2896 * required. Note that restriction levels are normally user rights, but 'sysop'
2897 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2898 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2899 */
2900 public function getRestrictions( $action ) {
2901 if ( !$this->mRestrictionsLoaded ) {
2902 $this->loadRestrictions();
2903 }
2904 return isset( $this->mRestrictions[$action] )
2905 ? $this->mRestrictions[$action]
2906 : [];
2907 }
2908
2909 /**
2910 * Accessor/initialisation for mRestrictions
2911 *
2912 * @return array Keys are actions, values are arrays as returned by
2913 * Title::getRestrictions()
2914 * @since 1.23
2915 */
2916 public function getAllRestrictions() {
2917 if ( !$this->mRestrictionsLoaded ) {
2918 $this->loadRestrictions();
2919 }
2920 return $this->mRestrictions;
2921 }
2922
2923 /**
2924 * Get the expiry time for the restriction against a given action
2925 *
2926 * @param string $action
2927 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2928 * or not protected at all, or false if the action is not recognised.
2929 */
2930 public function getRestrictionExpiry( $action ) {
2931 if ( !$this->mRestrictionsLoaded ) {
2932 $this->loadRestrictions();
2933 }
2934 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2935 }
2936
2937 /**
2938 * Returns cascading restrictions for the current article
2939 *
2940 * @return bool
2941 */
2942 function areRestrictionsCascading() {
2943 if ( !$this->mRestrictionsLoaded ) {
2944 $this->loadRestrictions();
2945 }
2946
2947 return $this->mCascadeRestriction;
2948 }
2949
2950 /**
2951 * Compiles list of active page restrictions from both page table (pre 1.10)
2952 * and page_restrictions table for this existing page.
2953 * Public for usage by LiquidThreads.
2954 *
2955 * @param array $rows Array of db result objects
2956 * @param string $oldFashionedRestrictions Comma-separated list of page
2957 * restrictions from page table (pre 1.10)
2958 */
2959 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2960 $dbr = wfGetDB( DB_REPLICA );
2961
2962 $restrictionTypes = $this->getRestrictionTypes();
2963
2964 foreach ( $restrictionTypes as $type ) {
2965 $this->mRestrictions[$type] = [];
2966 $this->mRestrictionsExpiry[$type] = 'infinity';
2967 }
2968
2969 $this->mCascadeRestriction = false;
2970
2971 # Backwards-compatibility: also load the restrictions from the page record (old format).
2972 if ( $oldFashionedRestrictions !== null ) {
2973 $this->mOldRestrictions = $oldFashionedRestrictions;
2974 }
2975
2976 if ( $this->mOldRestrictions === false ) {
2977 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2978 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
2979 }
2980
2981 if ( $this->mOldRestrictions != '' ) {
2982 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2983 $temp = explode( '=', trim( $restrict ) );
2984 if ( count( $temp ) == 1 ) {
2985 // old old format should be treated as edit/move restriction
2986 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2987 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2988 } else {
2989 $restriction = trim( $temp[1] );
2990 if ( $restriction != '' ) { // some old entries are empty
2991 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2992 }
2993 }
2994 }
2995 }
2996
2997 if ( count( $rows ) ) {
2998 # Current system - load second to make them override.
2999 $now = wfTimestampNow();
3000
3001 # Cycle through all the restrictions.
3002 foreach ( $rows as $row ) {
3003 // Don't take care of restrictions types that aren't allowed
3004 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
3005 continue;
3006 }
3007
3008 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3009
3010 // Only apply the restrictions if they haven't expired!
3011 if ( !$expiry || $expiry > $now ) {
3012 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
3013 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
3014
3015 $this->mCascadeRestriction |= $row->pr_cascade;
3016 }
3017 }
3018 }
3019
3020 $this->mRestrictionsLoaded = true;
3021 }
3022
3023 /**
3024 * Load restrictions from the page_restrictions table
3025 *
3026 * @param string $oldFashionedRestrictions Comma-separated list of page
3027 * restrictions from page table (pre 1.10)
3028 */
3029 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3030 if ( $this->mRestrictionsLoaded ) {
3031 return;
3032 }
3033
3034 $id = $this->getArticleID();
3035 if ( $id ) {
3036 $cache = ObjectCache::getMainWANInstance();
3037 $rows = $cache->getWithSetCallback(
3038 // Page protections always leave a new null revision
3039 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3040 $cache::TTL_DAY,
3041 function ( $curValue, &$ttl, array &$setOpts ) {
3042 $dbr = wfGetDB( DB_REPLICA );
3043
3044 $setOpts += Database::getCacheSetOptions( $dbr );
3045
3046 return iterator_to_array(
3047 $dbr->select(
3048 'page_restrictions',
3049 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3050 [ 'pr_page' => $this->getArticleID() ],
3051 __METHOD__
3052 )
3053 );
3054 }
3055 );
3056
3057 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3058 } else {
3059 $title_protection = $this->getTitleProtectionInternal();
3060
3061 if ( $title_protection ) {
3062 $now = wfTimestampNow();
3063 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3064
3065 if ( !$expiry || $expiry > $now ) {
3066 // Apply the restrictions
3067 $this->mRestrictionsExpiry['create'] = $expiry;
3068 $this->mRestrictions['create'] =
3069 explode( ',', trim( $title_protection['permission'] ) );
3070 } else { // Get rid of the old restrictions
3071 $this->mTitleProtection = false;
3072 }
3073 } else {
3074 $this->mRestrictionsExpiry['create'] = 'infinity';
3075 }
3076 $this->mRestrictionsLoaded = true;
3077 }
3078 }
3079
3080 /**
3081 * Flush the protection cache in this object and force reload from the database.
3082 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3083 */
3084 public function flushRestrictions() {
3085 $this->mRestrictionsLoaded = false;
3086 $this->mTitleProtection = null;
3087 }
3088
3089 /**
3090 * Purge expired restrictions from the page_restrictions table
3091 *
3092 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3093 */
3094 static function purgeExpiredRestrictions() {
3095 if ( wfReadOnly() ) {
3096 return;
3097 }
3098
3099 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3100 wfGetDB( DB_MASTER ),
3101 __METHOD__,
3102 function ( IDatabase $dbw, $fname ) {
3103 $config = MediaWikiServices::getInstance()->getMainConfig();
3104 $ids = $dbw->selectFieldValues(
3105 'page_restrictions',
3106 'pr_id',
3107 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3108 $fname,
3109 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3110 );
3111 if ( $ids ) {
3112 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3113 }
3114 }
3115 ) );
3116
3117 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3118 wfGetDB( DB_MASTER ),
3119 __METHOD__,
3120 function ( IDatabase $dbw, $fname ) {
3121 $dbw->