Merge "Fix Special:Undelete search - use variable and not request param"
[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 self::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 = self::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[] = self::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 = self::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 = self::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
561 // Don't give fatal errors if the message is broken
562 if ( !$title ) {
563 $title = self::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 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
752 *
753 * @param string $fragment Containing a URL or link fragment (after the "#")
754 * @return string Escaped string
755 */
756 static function escapeFragmentForURL( $fragment ) {
757 # Note that we don't urlencode the fragment. urlencoded Unicode
758 # fragments appear not to work in IE (at least up to 7) or in at least
759 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
760 # to care if they aren't encoded.
761 return Sanitizer::escapeId( $fragment, 'noninitial' );
762 }
763
764 /**
765 * Callback for usort() to do title sorts by (namespace, title)
766 *
767 * @param LinkTarget $a
768 * @param LinkTarget $b
769 *
770 * @return int Result of string comparison, or namespace comparison
771 */
772 public static function compare( LinkTarget $a, LinkTarget $b ) {
773 if ( $a->getNamespace() == $b->getNamespace() ) {
774 return strcmp( $a->getText(), $b->getText() );
775 } else {
776 return $a->getNamespace() - $b->getNamespace();
777 }
778 }
779
780 /**
781 * Determine whether the object refers to a page within
782 * this project (either this wiki or a wiki with a local
783 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
784 *
785 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
786 */
787 public function isLocal() {
788 if ( $this->isExternal() ) {
789 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
790 if ( $iw ) {
791 return $iw->isLocal();
792 }
793 }
794 return true;
795 }
796
797 /**
798 * Is this Title interwiki?
799 *
800 * @return bool
801 */
802 public function isExternal() {
803 return $this->mInterwiki !== '';
804 }
805
806 /**
807 * Get the interwiki prefix
808 *
809 * Use Title::isExternal to check if a interwiki is set
810 *
811 * @return string Interwiki prefix
812 */
813 public function getInterwiki() {
814 return $this->mInterwiki;
815 }
816
817 /**
818 * Was this a local interwiki link?
819 *
820 * @return bool
821 */
822 public function wasLocalInterwiki() {
823 return $this->mLocalInterwiki;
824 }
825
826 /**
827 * Determine whether the object refers to a page within
828 * this project and is transcludable.
829 *
830 * @return bool True if this is transcludable
831 */
832 public function isTrans() {
833 if ( !$this->isExternal() ) {
834 return false;
835 }
836
837 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
838 }
839
840 /**
841 * Returns the DB name of the distant wiki which owns the object.
842 *
843 * @return string|false The DB name
844 */
845 public function getTransWikiID() {
846 if ( !$this->isExternal() ) {
847 return false;
848 }
849
850 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
851 }
852
853 /**
854 * Get a TitleValue object representing this Title.
855 *
856 * @note Not all valid Titles have a corresponding valid TitleValue
857 * (e.g. TitleValues cannot represent page-local links that have a
858 * fragment but no title text).
859 *
860 * @return TitleValue|null
861 */
862 public function getTitleValue() {
863 if ( $this->mTitleValue === null ) {
864 try {
865 $this->mTitleValue = new TitleValue(
866 $this->getNamespace(),
867 $this->getDBkey(),
868 $this->getFragment(),
869 $this->getInterwiki()
870 );
871 } catch ( InvalidArgumentException $ex ) {
872 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
873 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
874 }
875 }
876
877 return $this->mTitleValue;
878 }
879
880 /**
881 * Get the text form (spaces not underscores) of the main part
882 *
883 * @return string Main part of the title
884 */
885 public function getText() {
886 return $this->mTextform;
887 }
888
889 /**
890 * Get the URL-encoded form of the main part
891 *
892 * @return string Main part of the title, URL-encoded
893 */
894 public function getPartialURL() {
895 return $this->mUrlform;
896 }
897
898 /**
899 * Get the main part with underscores
900 *
901 * @return string Main part of the title, with underscores
902 */
903 public function getDBkey() {
904 return $this->mDbkeyform;
905 }
906
907 /**
908 * Get the DB key with the initial letter case as specified by the user
909 *
910 * @return string DB key
911 */
912 function getUserCaseDBKey() {
913 if ( !is_null( $this->mUserCaseDBKey ) ) {
914 return $this->mUserCaseDBKey;
915 } else {
916 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
917 return $this->mDbkeyform;
918 }
919 }
920
921 /**
922 * Get the namespace index, i.e. one of the NS_xxxx constants.
923 *
924 * @return int Namespace index
925 */
926 public function getNamespace() {
927 return $this->mNamespace;
928 }
929
930 /**
931 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
932 *
933 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
934 * @return string Content model id
935 */
936 public function getContentModel( $flags = 0 ) {
937 if ( !$this->mForcedContentModel
938 && ( !$this->mContentModel || $flags === self::GAID_FOR_UPDATE )
939 && $this->getArticleID( $flags )
940 ) {
941 $linkCache = LinkCache::singleton();
942 $linkCache->addLinkObj( $this ); # in case we already had an article ID
943 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
944 }
945
946 if ( !$this->mContentModel ) {
947 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
948 }
949
950 return $this->mContentModel;
951 }
952
953 /**
954 * Convenience method for checking a title's content model name
955 *
956 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
957 * @return bool True if $this->getContentModel() == $id
958 */
959 public function hasContentModel( $id ) {
960 return $this->getContentModel() == $id;
961 }
962
963 /**
964 * Set a proposed content model for the page for permissions
965 * checking. This does not actually change the content model
966 * of a title!
967 *
968 * Additionally, you should make sure you've checked
969 * ContentHandler::canBeUsedOn() first.
970 *
971 * @since 1.28
972 * @param string $model CONTENT_MODEL_XXX constant
973 */
974 public function setContentModel( $model ) {
975 $this->mContentModel = $model;
976 $this->mForcedContentModel = true;
977 }
978
979 /**
980 * Get the namespace text
981 *
982 * @return string|false Namespace text
983 */
984 public function getNsText() {
985 if ( $this->isExternal() ) {
986 // This probably shouldn't even happen,
987 // but for interwiki transclusion it sometimes does.
988 // Use the canonical namespaces if possible to try to
989 // resolve a foreign namespace.
990 if ( MWNamespace::exists( $this->mNamespace ) ) {
991 return MWNamespace::getCanonicalName( $this->mNamespace );
992 }
993 }
994
995 try {
996 $formatter = self::getTitleFormatter();
997 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
998 } catch ( InvalidArgumentException $ex ) {
999 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1000 return false;
1001 }
1002 }
1003
1004 /**
1005 * Get the namespace text of the subject (rather than talk) page
1006 *
1007 * @return string Namespace text
1008 */
1009 public function getSubjectNsText() {
1010 global $wgContLang;
1011 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1012 }
1013
1014 /**
1015 * Get the namespace text of the talk page
1016 *
1017 * @return string Namespace text
1018 */
1019 public function getTalkNsText() {
1020 global $wgContLang;
1021 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1022 }
1023
1024 /**
1025 * Can this title have a corresponding talk page?
1026 *
1027 * @deprecated since 1.30, use canHaveTalkPage() instead.
1028 *
1029 * @return bool True if this title either is a talk page or can have a talk page associated.
1030 */
1031 public function canTalk() {
1032 return $this->canHaveTalkPage();
1033 }
1034
1035 /**
1036 * Can this title have a corresponding talk page?
1037 *
1038 * @see MWNamespace::hasTalkNamespace
1039 *
1040 * @return bool True if this title either is a talk page or can have a talk page associated.
1041 */
1042 public function canHaveTalkPage() {
1043 return MWNamespace::hasTalkNamespace( $this->mNamespace );
1044 }
1045
1046 /**
1047 * Is this in a namespace that allows actual pages?
1048 *
1049 * @return bool
1050 */
1051 public function canExist() {
1052 return $this->mNamespace >= NS_MAIN;
1053 }
1054
1055 /**
1056 * Can this title be added to a user's watchlist?
1057 *
1058 * @return bool
1059 */
1060 public function isWatchable() {
1061 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1062 }
1063
1064 /**
1065 * Returns true if this is a special page.
1066 *
1067 * @return bool
1068 */
1069 public function isSpecialPage() {
1070 return $this->getNamespace() == NS_SPECIAL;
1071 }
1072
1073 /**
1074 * Returns true if this title resolves to the named special page
1075 *
1076 * @param string $name The special page name
1077 * @return bool
1078 */
1079 public function isSpecial( $name ) {
1080 if ( $this->isSpecialPage() ) {
1081 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1082 if ( $name == $thisName ) {
1083 return true;
1084 }
1085 }
1086 return false;
1087 }
1088
1089 /**
1090 * If the Title refers to a special page alias which is not the local default, resolve
1091 * the alias, and localise the name as necessary. Otherwise, return $this
1092 *
1093 * @return Title
1094 */
1095 public function fixSpecialName() {
1096 if ( $this->isSpecialPage() ) {
1097 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1098 if ( $canonicalName ) {
1099 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1100 if ( $localName != $this->mDbkeyform ) {
1101 return self::makeTitle( NS_SPECIAL, $localName );
1102 }
1103 }
1104 }
1105 return $this;
1106 }
1107
1108 /**
1109 * Returns true if the title is inside the specified namespace.
1110 *
1111 * Please make use of this instead of comparing to getNamespace()
1112 * This function is much more resistant to changes we may make
1113 * to namespaces than code that makes direct comparisons.
1114 * @param int $ns The namespace
1115 * @return bool
1116 * @since 1.19
1117 */
1118 public function inNamespace( $ns ) {
1119 return MWNamespace::equals( $this->getNamespace(), $ns );
1120 }
1121
1122 /**
1123 * Returns true if the title is inside one of the specified namespaces.
1124 *
1125 * @param int|int[] $namespaces,... The namespaces to check for
1126 * @return bool
1127 * @since 1.19
1128 */
1129 public function inNamespaces( /* ... */ ) {
1130 $namespaces = func_get_args();
1131 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1132 $namespaces = $namespaces[0];
1133 }
1134
1135 foreach ( $namespaces as $ns ) {
1136 if ( $this->inNamespace( $ns ) ) {
1137 return true;
1138 }
1139 }
1140
1141 return false;
1142 }
1143
1144 /**
1145 * Returns true if the title has the same subject namespace as the
1146 * namespace specified.
1147 * For example this method will take NS_USER and return true if namespace
1148 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1149 * as their subject namespace.
1150 *
1151 * This is MUCH simpler than individually testing for equivalence
1152 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1153 * @since 1.19
1154 * @param int $ns
1155 * @return bool
1156 */
1157 public function hasSubjectNamespace( $ns ) {
1158 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1159 }
1160
1161 /**
1162 * Is this Title in a namespace which contains content?
1163 * In other words, is this a content page, for the purposes of calculating
1164 * statistics, etc?
1165 *
1166 * @return bool
1167 */
1168 public function isContentPage() {
1169 return MWNamespace::isContent( $this->getNamespace() );
1170 }
1171
1172 /**
1173 * Would anybody with sufficient privileges be able to move this page?
1174 * Some pages just aren't movable.
1175 *
1176 * @return bool
1177 */
1178 public function isMovable() {
1179 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1180 // Interwiki title or immovable namespace. Hooks don't get to override here
1181 return false;
1182 }
1183
1184 $result = true;
1185 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1186 return $result;
1187 }
1188
1189 /**
1190 * Is this the mainpage?
1191 * @note Title::newFromText seems to be sufficiently optimized by the title
1192 * cache that we don't need to over-optimize by doing direct comparisons and
1193 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1194 * ends up reporting something differently than $title->isMainPage();
1195 *
1196 * @since 1.18
1197 * @return bool
1198 */
1199 public function isMainPage() {
1200 return $this->equals( self::newMainPage() );
1201 }
1202
1203 /**
1204 * Is this a subpage?
1205 *
1206 * @return bool
1207 */
1208 public function isSubpage() {
1209 return MWNamespace::hasSubpages( $this->mNamespace )
1210 ? strpos( $this->getText(), '/' ) !== false
1211 : false;
1212 }
1213
1214 /**
1215 * Is this a conversion table for the LanguageConverter?
1216 *
1217 * @return bool
1218 */
1219 public function isConversionTable() {
1220 // @todo ConversionTable should become a separate content model.
1221
1222 return $this->getNamespace() == NS_MEDIAWIKI &&
1223 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1224 }
1225
1226 /**
1227 * Does that page contain wikitext, or it is JS, CSS or whatever?
1228 *
1229 * @return bool
1230 */
1231 public function isWikitextPage() {
1232 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1233 }
1234
1235 /**
1236 * Could this page contain custom CSS or JavaScript for the global UI.
1237 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1238 * or CONTENT_MODEL_JAVASCRIPT.
1239 *
1240 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1241 * for that!
1242 *
1243 * Note that this method should not return true for pages that contain and
1244 * show "inactive" CSS or JS.
1245 *
1246 * @return bool
1247 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1248 */
1249 public function isCssOrJsPage() {
1250 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1251 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1252 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1253
1254 return $isCssOrJsPage;
1255 }
1256
1257 /**
1258 * Is this a .css or .js subpage of a user page?
1259 * @return bool
1260 * @todo FIXME: Rename to isUserConfigPage()
1261 */
1262 public function isCssJsSubpage() {
1263 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1264 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1265 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1266 }
1267
1268 /**
1269 * Trim down a .css or .js subpage title to get the corresponding skin name
1270 *
1271 * @return string Containing skin name from .css or .js subpage title
1272 */
1273 public function getSkinFromCssJsSubpage() {
1274 $subpage = explode( '/', $this->mTextform );
1275 $subpage = $subpage[count( $subpage ) - 1];
1276 $lastdot = strrpos( $subpage, '.' );
1277 if ( $lastdot === false ) {
1278 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1279 }
1280 return substr( $subpage, 0, $lastdot );
1281 }
1282
1283 /**
1284 * Is this a .css subpage of a user page?
1285 *
1286 * @return bool
1287 */
1288 public function isCssSubpage() {
1289 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1290 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1291 }
1292
1293 /**
1294 * Is this a .js subpage of a user page?
1295 *
1296 * @return bool
1297 */
1298 public function isJsSubpage() {
1299 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1300 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1301 }
1302
1303 /**
1304 * Is this a talk page of some sort?
1305 *
1306 * @return bool
1307 */
1308 public function isTalkPage() {
1309 return MWNamespace::isTalk( $this->getNamespace() );
1310 }
1311
1312 /**
1313 * Get a Title object associated with the talk page of this article
1314 *
1315 * @return Title The object for the talk page
1316 */
1317 public function getTalkPage() {
1318 return self::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1319 }
1320
1321 /**
1322 * Get a Title object associated with the talk page of this article,
1323 * if such a talk page can exist.
1324 *
1325 * @return Title The object for the talk page,
1326 * or null if no associated talk page can exist, according to canHaveTalkPage().
1327 */
1328 public function getTalkPageIfDefined() {
1329 if ( !$this->canHaveTalkPage() ) {
1330 return null;
1331 }
1332
1333 return $this->getTalkPage();
1334 }
1335
1336 /**
1337 * Get a title object associated with the subject page of this
1338 * talk page
1339 *
1340 * @return Title The object for the subject page
1341 */
1342 public function getSubjectPage() {
1343 // Is this the same title?
1344 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1345 if ( $this->getNamespace() == $subjectNS ) {
1346 return $this;
1347 }
1348 return self::makeTitle( $subjectNS, $this->getDBkey() );
1349 }
1350
1351 /**
1352 * Get the other title for this page, if this is a subject page
1353 * get the talk page, if it is a subject page get the talk page
1354 *
1355 * @since 1.25
1356 * @throws MWException
1357 * @return Title
1358 */
1359 public function getOtherPage() {
1360 if ( $this->isSpecialPage() ) {
1361 throw new MWException( 'Special pages cannot have other pages' );
1362 }
1363 if ( $this->isTalkPage() ) {
1364 return $this->getSubjectPage();
1365 } else {
1366 return $this->getTalkPage();
1367 }
1368 }
1369
1370 /**
1371 * Get the default namespace index, for when there is no namespace
1372 *
1373 * @return int Default namespace index
1374 */
1375 public function getDefaultNamespace() {
1376 return $this->mDefaultNamespace;
1377 }
1378
1379 /**
1380 * Get the Title fragment (i.e.\ the bit after the #) in text form
1381 *
1382 * Use Title::hasFragment to check for a fragment
1383 *
1384 * @return string Title fragment
1385 */
1386 public function getFragment() {
1387 return $this->mFragment;
1388 }
1389
1390 /**
1391 * Check if a Title fragment is set
1392 *
1393 * @return bool
1394 * @since 1.23
1395 */
1396 public function hasFragment() {
1397 return $this->mFragment !== '';
1398 }
1399
1400 /**
1401 * Get the fragment in URL form, including the "#" character if there is one
1402 *
1403 * @return string Fragment in URL form
1404 */
1405 public function getFragmentForURL() {
1406 if ( !$this->hasFragment() ) {
1407 return '';
1408 } elseif ( $this->isExternal() && !$this->getTransWikiID() ) {
1409 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->getFragment() );
1410 }
1411 return '#' . Sanitizer::escapeIdForLink( $this->getFragment() );
1412 }
1413
1414 /**
1415 * Set the fragment for this title. Removes the first character from the
1416 * specified fragment before setting, so it assumes you're passing it with
1417 * an initial "#".
1418 *
1419 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1420 * or Title::createFragmentTarget().
1421 * Still in active use privately.
1422 *
1423 * @private
1424 * @param string $fragment Text
1425 */
1426 public function setFragment( $fragment ) {
1427 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1428 }
1429
1430 /**
1431 * Creates a new Title for a different fragment of the same page.
1432 *
1433 * @since 1.27
1434 * @param string $fragment
1435 * @return Title
1436 */
1437 public function createFragmentTarget( $fragment ) {
1438 return self::makeTitle(
1439 $this->getNamespace(),
1440 $this->getText(),
1441 $fragment,
1442 $this->getInterwiki()
1443 );
1444 }
1445
1446 /**
1447 * Prefix some arbitrary text with the namespace or interwiki prefix
1448 * of this object
1449 *
1450 * @param string $name The text
1451 * @return string The prefixed text
1452 */
1453 private function prefix( $name ) {
1454 global $wgContLang;
1455
1456 $p = '';
1457 if ( $this->isExternal() ) {
1458 $p = $this->mInterwiki . ':';
1459 }
1460
1461 if ( 0 != $this->mNamespace ) {
1462 $nsText = $this->getNsText();
1463
1464 if ( $nsText === false ) {
1465 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1466 $nsText = $wgContLang->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1467 }
1468
1469 $p .= $nsText . ':';
1470 }
1471 return $p . $name;
1472 }
1473
1474 /**
1475 * Get the prefixed database key form
1476 *
1477 * @return string The prefixed title, with underscores and
1478 * any interwiki and namespace prefixes
1479 */
1480 public function getPrefixedDBkey() {
1481 $s = $this->prefix( $this->mDbkeyform );
1482 $s = strtr( $s, ' ', '_' );
1483 return $s;
1484 }
1485
1486 /**
1487 * Get the prefixed title with spaces.
1488 * This is the form usually used for display
1489 *
1490 * @return string The prefixed title, with spaces
1491 */
1492 public function getPrefixedText() {
1493 if ( $this->mPrefixedText === null ) {
1494 $s = $this->prefix( $this->mTextform );
1495 $s = strtr( $s, '_', ' ' );
1496 $this->mPrefixedText = $s;
1497 }
1498 return $this->mPrefixedText;
1499 }
1500
1501 /**
1502 * Return a string representation of this title
1503 *
1504 * @return string Representation of this title
1505 */
1506 public function __toString() {
1507 return $this->getPrefixedText();
1508 }
1509
1510 /**
1511 * Get the prefixed title with spaces, plus any fragment
1512 * (part beginning with '#')
1513 *
1514 * @return string The prefixed title, with spaces and the fragment, including '#'
1515 */
1516 public function getFullText() {
1517 $text = $this->getPrefixedText();
1518 if ( $this->hasFragment() ) {
1519 $text .= '#' . $this->getFragment();
1520 }
1521 return $text;
1522 }
1523
1524 /**
1525 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1526 *
1527 * @par Example:
1528 * @code
1529 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1530 * # returns: 'Foo'
1531 * @endcode
1532 *
1533 * @return string Root name
1534 * @since 1.20
1535 */
1536 public function getRootText() {
1537 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1538 return $this->getText();
1539 }
1540
1541 return strtok( $this->getText(), '/' );
1542 }
1543
1544 /**
1545 * Get the root page name title, i.e. the leftmost part before any slashes
1546 *
1547 * @par Example:
1548 * @code
1549 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1550 * # returns: Title{User:Foo}
1551 * @endcode
1552 *
1553 * @return Title Root title
1554 * @since 1.20
1555 */
1556 public function getRootTitle() {
1557 return self::makeTitle( $this->getNamespace(), $this->getRootText() );
1558 }
1559
1560 /**
1561 * Get the base page name without a namespace, i.e. the part before the subpage name
1562 *
1563 * @par Example:
1564 * @code
1565 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1566 * # returns: 'Foo/Bar'
1567 * @endcode
1568 *
1569 * @return string Base name
1570 */
1571 public function getBaseText() {
1572 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1573 return $this->getText();
1574 }
1575
1576 $parts = explode( '/', $this->getText() );
1577 # Don't discard the real title if there's no subpage involved
1578 if ( count( $parts ) > 1 ) {
1579 unset( $parts[count( $parts ) - 1] );
1580 }
1581 return implode( '/', $parts );
1582 }
1583
1584 /**
1585 * Get the base page name title, i.e. the part before the subpage name
1586 *
1587 * @par Example:
1588 * @code
1589 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1590 * # returns: Title{User:Foo/Bar}
1591 * @endcode
1592 *
1593 * @return Title Base title
1594 * @since 1.20
1595 */
1596 public function getBaseTitle() {
1597 return self::makeTitle( $this->getNamespace(), $this->getBaseText() );
1598 }
1599
1600 /**
1601 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1602 *
1603 * @par Example:
1604 * @code
1605 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1606 * # returns: "Baz"
1607 * @endcode
1608 *
1609 * @return string Subpage name
1610 */
1611 public function getSubpageText() {
1612 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1613 return $this->mTextform;
1614 }
1615 $parts = explode( '/', $this->mTextform );
1616 return $parts[count( $parts ) - 1];
1617 }
1618
1619 /**
1620 * Get the title for a subpage of the current page
1621 *
1622 * @par Example:
1623 * @code
1624 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1625 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1626 * @endcode
1627 *
1628 * @param string $text The subpage name to add to the title
1629 * @return Title Subpage title
1630 * @since 1.20
1631 */
1632 public function getSubpage( $text ) {
1633 return self::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1634 }
1635
1636 /**
1637 * Get a URL-encoded form of the subpage text
1638 *
1639 * @return string URL-encoded subpage name
1640 */
1641 public function getSubpageUrlForm() {
1642 $text = $this->getSubpageText();
1643 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1644 return $text;
1645 }
1646
1647 /**
1648 * Get a URL-encoded title (not an actual URL) including interwiki
1649 *
1650 * @return string The URL-encoded form
1651 */
1652 public function getPrefixedURL() {
1653 $s = $this->prefix( $this->mDbkeyform );
1654 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1655 return $s;
1656 }
1657
1658 /**
1659 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1660 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1661 * second argument named variant. This was deprecated in favor
1662 * of passing an array of option with a "variant" key
1663 * Once $query2 is removed for good, this helper can be dropped
1664 * and the wfArrayToCgi moved to getLocalURL();
1665 *
1666 * @since 1.19 (r105919)
1667 * @param array|string $query
1668 * @param string|string[]|bool $query2
1669 * @return string
1670 */
1671 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1672 if ( $query2 !== false ) {
1673 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1674 "method called with a second parameter is deprecated. Add your " .
1675 "parameter to an array passed as the first parameter.", "1.19" );
1676 }
1677 if ( is_array( $query ) ) {
1678 $query = wfArrayToCgi( $query );
1679 }
1680 if ( $query2 ) {
1681 if ( is_string( $query2 ) ) {
1682 // $query2 is a string, we will consider this to be
1683 // a deprecated $variant argument and add it to the query
1684 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1685 } else {
1686 $query2 = wfArrayToCgi( $query2 );
1687 }
1688 // If we have $query content add a & to it first
1689 if ( $query ) {
1690 $query .= '&';
1691 }
1692 // Now append the queries together
1693 $query .= $query2;
1694 }
1695 return $query;
1696 }
1697
1698 /**
1699 * Get a real URL referring to this title, with interwiki link and
1700 * fragment
1701 *
1702 * @see self::getLocalURL for the arguments.
1703 * @see wfExpandUrl
1704 * @param string|string[] $query
1705 * @param string|string[]|bool $query2
1706 * @param string $proto Protocol type to use in URL
1707 * @return string The URL
1708 */
1709 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1710 $query = self::fixUrlQueryArgs( $query, $query2 );
1711
1712 # Hand off all the decisions on urls to getLocalURL
1713 $url = $this->getLocalURL( $query );
1714
1715 # Expand the url to make it a full url. Note that getLocalURL has the
1716 # potential to output full urls for a variety of reasons, so we use
1717 # wfExpandUrl instead of simply prepending $wgServer
1718 $url = wfExpandUrl( $url, $proto );
1719
1720 # Finally, add the fragment.
1721 $url .= $this->getFragmentForURL();
1722 // Avoid PHP 7.1 warning from passing $this by reference
1723 $titleRef = $this;
1724 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1725 return $url;
1726 }
1727
1728 /**
1729 * Get a url appropriate for making redirects based on an untrusted url arg
1730 *
1731 * This is basically the same as getFullUrl(), but in the case of external
1732 * interwikis, we send the user to a landing page, to prevent possible
1733 * phishing attacks and the like.
1734 *
1735 * @note Uses current protocol by default, since technically relative urls
1736 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1737 * places where the url gets cached, as might pollute between
1738 * https and non-https users.
1739 * @see self::getLocalURL for the arguments.
1740 * @param array|string $query
1741 * @param string $proto Protocol type to use in URL
1742 * @return String. A url suitable to use in an HTTP location header.
1743 */
1744 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
1745 $target = $this;
1746 if ( $this->isExternal() ) {
1747 $target = SpecialPage::getTitleFor(
1748 'GoToInterwiki',
1749 $this->getPrefixedDBKey()
1750 );
1751 }
1752 return $target->getFullUrl( $query, false, $proto );
1753 }
1754
1755 /**
1756 * Get a URL with no fragment or server name (relative URL) from a Title object.
1757 * If this page is generated with action=render, however,
1758 * $wgServer is prepended to make an absolute URL.
1759 *
1760 * @see self::getFullURL to always get an absolute URL.
1761 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1762 * valid to link, locally, to the current Title.
1763 * @see self::newFromText to produce a Title object.
1764 *
1765 * @param string|string[] $query An optional query string,
1766 * not used for interwiki links. Can be specified as an associative array as well,
1767 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1768 * Some query patterns will trigger various shorturl path replacements.
1769 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1770 * be an array. If a string is passed it will be interpreted as a deprecated
1771 * variant argument and urlencoded into a variant= argument.
1772 * This second query argument will be added to the $query
1773 * The second parameter is deprecated since 1.19. Pass it as a key,value
1774 * pair in the first parameter array instead.
1775 *
1776 * @return string String of the URL.
1777 */
1778 public function getLocalURL( $query = '', $query2 = false ) {
1779 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1780
1781 $query = self::fixUrlQueryArgs( $query, $query2 );
1782
1783 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1784 if ( $interwiki ) {
1785 $namespace = $this->getNsText();
1786 if ( $namespace != '' ) {
1787 # Can this actually happen? Interwikis shouldn't be parsed.
1788 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1789 $namespace .= ':';
1790 }
1791 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1792 $url = wfAppendQuery( $url, $query );
1793 } else {
1794 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1795 if ( $query == '' ) {
1796 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1797 // Avoid PHP 7.1 warning from passing $this by reference
1798 $titleRef = $this;
1799 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1800 } else {
1801 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1802 $url = false;
1803 $matches = [];
1804
1805 if ( !empty( $wgActionPaths )
1806 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1807 ) {
1808 $action = urldecode( $matches[2] );
1809 if ( isset( $wgActionPaths[$action] ) ) {
1810 $query = $matches[1];
1811 if ( isset( $matches[4] ) ) {
1812 $query .= $matches[4];
1813 }
1814 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1815 if ( $query != '' ) {
1816 $url = wfAppendQuery( $url, $query );
1817 }
1818 }
1819 }
1820
1821 if ( $url === false
1822 && $wgVariantArticlePath
1823 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1824 && $this->getPageLanguage()->equals( $wgContLang )
1825 && $this->getPageLanguage()->hasVariants()
1826 ) {
1827 $variant = urldecode( $matches[1] );
1828 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1829 // Only do the variant replacement if the given variant is a valid
1830 // variant for the page's language.
1831 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1832 $url = str_replace( '$1', $dbkey, $url );
1833 }
1834 }
1835
1836 if ( $url === false ) {
1837 if ( $query == '-' ) {
1838 $query = '';
1839 }
1840 $url = "{$wgScript}?title={$dbkey}&{$query}";
1841 }
1842 }
1843 // Avoid PHP 7.1 warning from passing $this by reference
1844 $titleRef = $this;
1845 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1846
1847 // @todo FIXME: This causes breakage in various places when we
1848 // actually expected a local URL and end up with dupe prefixes.
1849 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1850 $url = $wgServer . $url;
1851 }
1852 }
1853 // Avoid PHP 7.1 warning from passing $this by reference
1854 $titleRef = $this;
1855 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1856 return $url;
1857 }
1858
1859 /**
1860 * Get a URL that's the simplest URL that will be valid to link, locally,
1861 * to the current Title. It includes the fragment, but does not include
1862 * the server unless action=render is used (or the link is external). If
1863 * there's a fragment but the prefixed text is empty, we just return a link
1864 * to the fragment.
1865 *
1866 * The result obviously should not be URL-escaped, but does need to be
1867 * HTML-escaped if it's being output in HTML.
1868 *
1869 * @param string|string[] $query
1870 * @param bool $query2
1871 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1872 * or false (default) for no expansion
1873 * @see self::getLocalURL for the arguments.
1874 * @return string The URL
1875 */
1876 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1877 if ( $this->isExternal() || $proto !== false ) {
1878 $ret = $this->getFullURL( $query, $query2, $proto );
1879 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1880 $ret = $this->getFragmentForURL();
1881 } else {
1882 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1883 }
1884 return $ret;
1885 }
1886
1887 /**
1888 * Get the URL form for an internal link.
1889 * - Used in various CDN-related code, in case we have a different
1890 * internal hostname for the server from the exposed one.
1891 *
1892 * This uses $wgInternalServer to qualify the path, or $wgServer
1893 * if $wgInternalServer is not set. If the server variable used is
1894 * protocol-relative, the URL will be expanded to http://
1895 *
1896 * @see self::getLocalURL for the arguments.
1897 * @return string The URL
1898 */
1899 public function getInternalURL( $query = '', $query2 = false ) {
1900 global $wgInternalServer, $wgServer;
1901 $query = self::fixUrlQueryArgs( $query, $query2 );
1902 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1903 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1904 // Avoid PHP 7.1 warning from passing $this by reference
1905 $titleRef = $this;
1906 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1907 return $url;
1908 }
1909
1910 /**
1911 * Get the URL for a canonical link, for use in things like IRC and
1912 * e-mail notifications. Uses $wgCanonicalServer and the
1913 * GetCanonicalURL hook.
1914 *
1915 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1916 *
1917 * @see self::getLocalURL for the arguments.
1918 * @return string The URL
1919 * @since 1.18
1920 */
1921 public function getCanonicalURL( $query = '', $query2 = false ) {
1922 $query = self::fixUrlQueryArgs( $query, $query2 );
1923 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1924 // Avoid PHP 7.1 warning from passing $this by reference
1925 $titleRef = $this;
1926 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1927 return $url;
1928 }
1929
1930 /**
1931 * Get the edit URL for this Title
1932 *
1933 * @return string The URL, or a null string if this is an interwiki link
1934 */
1935 public function getEditURL() {
1936 if ( $this->isExternal() ) {
1937 return '';
1938 }
1939 $s = $this->getLocalURL( 'action=edit' );
1940
1941 return $s;
1942 }
1943
1944 /**
1945 * Can $user perform $action on this page?
1946 * This skips potentially expensive cascading permission checks
1947 * as well as avoids expensive error formatting
1948 *
1949 * Suitable for use for nonessential UI controls in common cases, but
1950 * _not_ for functional access control.
1951 *
1952 * May provide false positives, but should never provide a false negative.
1953 *
1954 * @param string $action Action that permission needs to be checked for
1955 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1956 * @return bool
1957 */
1958 public function quickUserCan( $action, $user = null ) {
1959 return $this->userCan( $action, $user, false );
1960 }
1961
1962 /**
1963 * Can $user perform $action on this page?
1964 *
1965 * @param string $action Action that permission needs to be checked for
1966 * @param User $user User to check (since 1.19); $wgUser will be used if not
1967 * provided.
1968 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1969 * @return bool
1970 */
1971 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1972 if ( !$user instanceof User ) {
1973 global $wgUser;
1974 $user = $wgUser;
1975 }
1976
1977 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1978 }
1979
1980 /**
1981 * Can $user perform $action on this page?
1982 *
1983 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1984 *
1985 * @param string $action Action that permission needs to be checked for
1986 * @param User $user User to check
1987 * @param string $rigor One of (quick,full,secure)
1988 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1989 * - full : does cheap and expensive checks possibly from a replica DB
1990 * - secure : does cheap and expensive checks, using the master as needed
1991 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1992 * whose corresponding errors may be ignored.
1993 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1994 */
1995 public function getUserPermissionsErrors(
1996 $action, $user, $rigor = 'secure', $ignoreErrors = []
1997 ) {
1998 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1999
2000 // Remove the errors being ignored.
2001 foreach ( $errors as $index => $error ) {
2002 $errKey = is_array( $error ) ? $error[0] : $error;
2003
2004 if ( in_array( $errKey, $ignoreErrors ) ) {
2005 unset( $errors[$index] );
2006 }
2007 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
2008 unset( $errors[$index] );
2009 }
2010 }
2011
2012 return $errors;
2013 }
2014
2015 /**
2016 * Permissions checks that fail most often, and which are easiest to test.
2017 *
2018 * @param string $action The action to check
2019 * @param User $user User to check
2020 * @param array $errors List of current errors
2021 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2022 * @param bool $short Short circuit on first error
2023 *
2024 * @return array List of errors
2025 */
2026 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2027 if ( !Hooks::run( 'TitleQuickPermissions',
2028 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2029 ) {
2030 return $errors;
2031 }
2032
2033 if ( $action == 'create' ) {
2034 if (
2035 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2036 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2037 ) {
2038 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2039 }
2040 } elseif ( $action == 'move' ) {
2041 if ( !$user->isAllowed( 'move-rootuserpages' )
2042 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2043 // Show user page-specific message only if the user can move other pages
2044 $errors[] = [ 'cant-move-user-page' ];
2045 }
2046
2047 // Check if user is allowed to move files if it's a file
2048 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2049 $errors[] = [ 'movenotallowedfile' ];
2050 }
2051
2052 // Check if user is allowed to move category pages if it's a category page
2053 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2054 $errors[] = [ 'cant-move-category-page' ];
2055 }
2056
2057 if ( !$user->isAllowed( 'move' ) ) {
2058 // User can't move anything
2059 $userCanMove = User::groupHasPermission( 'user', 'move' );
2060 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2061 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2062 // custom message if logged-in users without any special rights can move
2063 $errors[] = [ 'movenologintext' ];
2064 } else {
2065 $errors[] = [ 'movenotallowed' ];
2066 }
2067 }
2068 } elseif ( $action == 'move-target' ) {
2069 if ( !$user->isAllowed( 'move' ) ) {
2070 // User can't move anything
2071 $errors[] = [ 'movenotallowed' ];
2072 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2073 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2074 // Show user page-specific message only if the user can move other pages
2075 $errors[] = [ 'cant-move-to-user-page' ];
2076 } elseif ( !$user->isAllowed( 'move-categorypages' )
2077 && $this->mNamespace == NS_CATEGORY ) {
2078 // Show category page-specific message only if the user can move other pages
2079 $errors[] = [ 'cant-move-to-category-page' ];
2080 }
2081 } elseif ( !$user->isAllowed( $action ) ) {
2082 $errors[] = $this->missingPermissionError( $action, $short );
2083 }
2084
2085 return $errors;
2086 }
2087
2088 /**
2089 * Add the resulting error code to the errors array
2090 *
2091 * @param array $errors List of current errors
2092 * @param array $result Result of errors
2093 *
2094 * @return array List of errors
2095 */
2096 private function resultToError( $errors, $result ) {
2097 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2098 // A single array representing an error
2099 $errors[] = $result;
2100 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2101 // A nested array representing multiple errors
2102 $errors = array_merge( $errors, $result );
2103 } elseif ( $result !== '' && is_string( $result ) ) {
2104 // A string representing a message-id
2105 $errors[] = [ $result ];
2106 } elseif ( $result instanceof MessageSpecifier ) {
2107 // A message specifier representing an error
2108 $errors[] = [ $result ];
2109 } elseif ( $result === false ) {
2110 // a generic "We don't want them to do that"
2111 $errors[] = [ 'badaccess-group0' ];
2112 }
2113 return $errors;
2114 }
2115
2116 /**
2117 * Check various permission hooks
2118 *
2119 * @param string $action The action to check
2120 * @param User $user User to check
2121 * @param array $errors List of current errors
2122 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2123 * @param bool $short Short circuit on first error
2124 *
2125 * @return array List of errors
2126 */
2127 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2128 // Use getUserPermissionsErrors instead
2129 $result = '';
2130 // Avoid PHP 7.1 warning from passing $this by reference
2131 $titleRef = $this;
2132 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2133 return $result ? [] : [ [ 'badaccess-group0' ] ];
2134 }
2135 // Check getUserPermissionsErrors hook
2136 // Avoid PHP 7.1 warning from passing $this by reference
2137 $titleRef = $this;
2138 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2139 $errors = $this->resultToError( $errors, $result );
2140 }
2141 // Check getUserPermissionsErrorsExpensive hook
2142 if (
2143 $rigor !== 'quick'
2144 && !( $short && count( $errors ) > 0 )
2145 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2146 ) {
2147 $errors = $this->resultToError( $errors, $result );
2148 }
2149
2150 return $errors;
2151 }
2152
2153 /**
2154 * Check permissions on special pages & namespaces
2155 *
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @param bool $short Short circuit on first error
2161 *
2162 * @return array List of errors
2163 */
2164 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2165 # Only 'createaccount' can be performed on special pages,
2166 # which don't actually exist in the DB.
2167 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2168 $errors[] = [ 'ns-specialprotected' ];
2169 }
2170
2171 # Check $wgNamespaceProtection for restricted namespaces
2172 if ( $this->isNamespaceProtected( $user ) ) {
2173 $ns = $this->mNamespace == NS_MAIN ?
2174 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2175 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2176 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2177 }
2178
2179 return $errors;
2180 }
2181
2182 /**
2183 * Check CSS/JS sub-page permissions
2184 *
2185 * @param string $action The action to check
2186 * @param User $user User to check
2187 * @param array $errors List of current errors
2188 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2189 * @param bool $short Short circuit on first error
2190 *
2191 * @return array List of errors
2192 */
2193 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2194 # Protect css/js subpages of user pages
2195 # XXX: this might be better using restrictions
2196 if ( $action != 'patrol' ) {
2197 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2198 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2199 $errors[] = [ 'mycustomcssprotected', $action ];
2200 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2201 $errors[] = [ 'mycustomjsprotected', $action ];
2202 }
2203 } else {
2204 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2205 $errors[] = [ 'customcssprotected', $action ];
2206 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2207 $errors[] = [ 'customjsprotected', $action ];
2208 }
2209 }
2210 }
2211
2212 return $errors;
2213 }
2214
2215 /**
2216 * Check against page_restrictions table requirements on this
2217 * page. The user must possess all required rights for this
2218 * action.
2219 *
2220 * @param string $action The action to check
2221 * @param User $user User to check
2222 * @param array $errors List of current errors
2223 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2224 * @param bool $short Short circuit on first error
2225 *
2226 * @return array List of errors
2227 */
2228 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2229 foreach ( $this->getRestrictions( $action ) as $right ) {
2230 // Backwards compatibility, rewrite sysop -> editprotected
2231 if ( $right == 'sysop' ) {
2232 $right = 'editprotected';
2233 }
2234 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2235 if ( $right == 'autoconfirmed' ) {
2236 $right = 'editsemiprotected';
2237 }
2238 if ( $right == '' ) {
2239 continue;
2240 }
2241 if ( !$user->isAllowed( $right ) ) {
2242 $errors[] = [ 'protectedpagetext', $right, $action ];
2243 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2244 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2245 }
2246 }
2247
2248 return $errors;
2249 }
2250
2251 /**
2252 * Check restrictions on cascading pages.
2253 *
2254 * @param string $action The action to check
2255 * @param User $user User to check
2256 * @param array $errors List of current errors
2257 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2258 * @param bool $short Short circuit on first error
2259 *
2260 * @return array List of errors
2261 */
2262 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2263 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2264 # We /could/ use the protection level on the source page, but it's
2265 # fairly ugly as we have to establish a precedence hierarchy for pages
2266 # included by multiple cascade-protected pages. So just restrict
2267 # it to people with 'protect' permission, as they could remove the
2268 # protection anyway.
2269 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2270 # Cascading protection depends on more than this page...
2271 # Several cascading protected pages may include this page...
2272 # Check each cascading level
2273 # This is only for protection restrictions, not for all actions
2274 if ( isset( $restrictions[$action] ) ) {
2275 foreach ( $restrictions[$action] as $right ) {
2276 // Backwards compatibility, rewrite sysop -> editprotected
2277 if ( $right == 'sysop' ) {
2278 $right = 'editprotected';
2279 }
2280 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2281 if ( $right == 'autoconfirmed' ) {
2282 $right = 'editsemiprotected';
2283 }
2284 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2285 $pages = '';
2286 foreach ( $cascadingSources as $page ) {
2287 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2288 }
2289 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2290 }
2291 }
2292 }
2293 }
2294
2295 return $errors;
2296 }
2297
2298 /**
2299 * Check action permissions not already checked in checkQuickPermissions
2300 *
2301 * @param string $action The action to check
2302 * @param User $user User to check
2303 * @param array $errors List of current errors
2304 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2305 * @param bool $short Short circuit on first error
2306 *
2307 * @return array List of errors
2308 */
2309 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2310 global $wgDeleteRevisionsLimit, $wgLang;
2311
2312 if ( $action == 'protect' ) {
2313 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2314 // If they can't edit, they shouldn't protect.
2315 $errors[] = [ 'protect-cantedit' ];
2316 }
2317 } elseif ( $action == 'create' ) {
2318 $title_protection = $this->getTitleProtection();
2319 if ( $title_protection ) {
2320 if ( $title_protection['permission'] == ''
2321 || !$user->isAllowed( $title_protection['permission'] )
2322 ) {
2323 $errors[] = [
2324 'titleprotected',
2325 User::whoIs( $title_protection['user'] ),
2326 $title_protection['reason']
2327 ];
2328 }
2329 }
2330 } elseif ( $action == 'move' ) {
2331 // Check for immobile pages
2332 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2333 // Specific message for this case
2334 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2335 } elseif ( !$this->isMovable() ) {
2336 // Less specific message for rarer cases
2337 $errors[] = [ 'immobile-source-page' ];
2338 }
2339 } elseif ( $action == 'move-target' ) {
2340 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2341 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2342 } elseif ( !$this->isMovable() ) {
2343 $errors[] = [ 'immobile-target-page' ];
2344 }
2345 } elseif ( $action == 'delete' ) {
2346 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2347 if ( !$tempErrors ) {
2348 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2349 $user, $tempErrors, $rigor, true );
2350 }
2351 if ( $tempErrors ) {
2352 // If protection keeps them from editing, they shouldn't be able to delete.
2353 $errors[] = [ 'deleteprotected' ];
2354 }
2355 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2356 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2357 ) {
2358 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2359 }
2360 } elseif ( $action === 'undelete' ) {
2361 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2362 // Undeleting implies editing
2363 $errors[] = [ 'undelete-cantedit' ];
2364 }
2365 if ( !$this->exists()
2366 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2367 ) {
2368 // Undeleting where nothing currently exists implies creating
2369 $errors[] = [ 'undelete-cantcreate' ];
2370 }
2371 }
2372 return $errors;
2373 }
2374
2375 /**
2376 * Check that the user isn't blocked from editing.
2377 *
2378 * @param string $action The action to check
2379 * @param User $user User to check
2380 * @param array $errors List of current errors
2381 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2382 * @param bool $short Short circuit on first error
2383 *
2384 * @return array List of errors
2385 */
2386 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2387 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2388 // Account creation blocks handled at userlogin.
2389 // Unblocking handled in SpecialUnblock
2390 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2391 return $errors;
2392 }
2393
2394 // Optimize for a very common case
2395 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2396 return $errors;
2397 }
2398
2399 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2400 $errors[] = [ 'confirmedittext' ];
2401 }
2402
2403 $useSlave = ( $rigor !== 'secure' );
2404 if ( ( $action == 'edit' || $action == 'create' )
2405 && !$user->isBlockedFrom( $this, $useSlave )
2406 ) {
2407 // Don't block the user from editing their own talk page unless they've been
2408 // explicitly blocked from that too.
2409 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2410 // @todo FIXME: Pass the relevant context into this function.
2411 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2412 }
2413
2414 return $errors;
2415 }
2416
2417 /**
2418 * Check that the user is allowed to read this page.
2419 *
2420 * @param string $action The action to check
2421 * @param User $user User to check
2422 * @param array $errors List of current errors
2423 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2424 * @param bool $short Short circuit on first error
2425 *
2426 * @return array List of errors
2427 */
2428 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2429 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2430
2431 $whitelisted = false;
2432 if ( User::isEveryoneAllowed( 'read' ) ) {
2433 # Shortcut for public wikis, allows skipping quite a bit of code
2434 $whitelisted = true;
2435 } elseif ( $user->isAllowed( 'read' ) ) {
2436 # If the user is allowed to read pages, he is allowed to read all pages
2437 $whitelisted = true;
2438 } elseif ( $this->isSpecial( 'Userlogin' )
2439 || $this->isSpecial( 'PasswordReset' )
2440 || $this->isSpecial( 'Userlogout' )
2441 ) {
2442 # Always grant access to the login page.
2443 # Even anons need to be able to log in.
2444 $whitelisted = true;
2445 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2446 # Time to check the whitelist
2447 # Only do these checks is there's something to check against
2448 $name = $this->getPrefixedText();
2449 $dbName = $this->getPrefixedDBkey();
2450
2451 // Check for explicit whitelisting with and without underscores
2452 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2453 $whitelisted = true;
2454 } elseif ( $this->getNamespace() == NS_MAIN ) {
2455 # Old settings might have the title prefixed with
2456 # a colon for main-namespace pages
2457 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2458 $whitelisted = true;
2459 }
2460 } elseif ( $this->isSpecialPage() ) {
2461 # If it's a special page, ditch the subpage bit and check again
2462 $name = $this->getDBkey();
2463 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2464 if ( $name ) {
2465 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2466 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2467 $whitelisted = true;
2468 }
2469 }
2470 }
2471 }
2472
2473 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2474 $name = $this->getPrefixedText();
2475 // Check for regex whitelisting
2476 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2477 if ( preg_match( $listItem, $name ) ) {
2478 $whitelisted = true;
2479 break;
2480 }
2481 }
2482 }
2483
2484 if ( !$whitelisted ) {
2485 # If the title is not whitelisted, give extensions a chance to do so...
2486 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2487 if ( !$whitelisted ) {
2488 $errors[] = $this->missingPermissionError( $action, $short );
2489 }
2490 }
2491
2492 return $errors;
2493 }
2494
2495 /**
2496 * Get a description array when the user doesn't have the right to perform
2497 * $action (i.e. when User::isAllowed() returns false)
2498 *
2499 * @param string $action The action to check
2500 * @param bool $short Short circuit on first error
2501 * @return array Array containing an error message key and any parameters
2502 */
2503 private function missingPermissionError( $action, $short ) {
2504 // We avoid expensive display logic for quickUserCan's and such
2505 if ( $short ) {
2506 return [ 'badaccess-group0' ];
2507 }
2508
2509 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2510 }
2511
2512 /**
2513 * Can $user perform $action on this page? This is an internal function,
2514 * with multiple levels of checks depending on performance needs; see $rigor below.
2515 * It does not check wfReadOnly().
2516 *
2517 * @param string $action Action that permission needs to be checked for
2518 * @param User $user User to check
2519 * @param string $rigor One of (quick,full,secure)
2520 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2521 * - full : does cheap and expensive checks possibly from a replica DB
2522 * - secure : does cheap and expensive checks, using the master as needed
2523 * @param bool $short Set this to true to stop after the first permission error.
2524 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2525 */
2526 protected function getUserPermissionsErrorsInternal(
2527 $action, $user, $rigor = 'secure', $short = false
2528 ) {
2529 if ( $rigor === true ) {
2530 $rigor = 'secure'; // b/c
2531 } elseif ( $rigor === false ) {
2532 $rigor = 'quick'; // b/c
2533 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2534 throw new Exception( "Invalid rigor parameter '$rigor'." );
2535 }
2536
2537 # Read has special handling
2538 if ( $action == 'read' ) {
2539 $checks = [
2540 'checkPermissionHooks',
2541 'checkReadPermissions',
2542 'checkUserBlock', // for wgBlockDisablesLogin
2543 ];
2544 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2545 # here as it will lead to duplicate error messages. This is okay to do
2546 # since anywhere that checks for create will also check for edit, and
2547 # those checks are called for edit.
2548 } elseif ( $action == 'create' ) {
2549 $checks = [
2550 'checkQuickPermissions',
2551 'checkPermissionHooks',
2552 'checkPageRestrictions',
2553 'checkCascadingSourcesRestrictions',
2554 'checkActionPermissions',
2555 'checkUserBlock'
2556 ];
2557 } else {
2558 $checks = [
2559 'checkQuickPermissions',
2560 'checkPermissionHooks',
2561 'checkSpecialsAndNSPermissions',
2562 'checkCSSandJSPermissions',
2563 'checkPageRestrictions',
2564 'checkCascadingSourcesRestrictions',
2565 'checkActionPermissions',
2566 'checkUserBlock'
2567 ];
2568 }
2569
2570 $errors = [];
2571 while ( count( $checks ) > 0 &&
2572 !( $short && count( $errors ) > 0 ) ) {
2573 $method = array_shift( $checks );
2574 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2575 }
2576
2577 return $errors;
2578 }
2579
2580 /**
2581 * Get a filtered list of all restriction types supported by this wiki.
2582 * @param bool $exists True to get all restriction types that apply to
2583 * titles that do exist, False for all restriction types that apply to
2584 * titles that do not exist
2585 * @return array
2586 */
2587 public static function getFilteredRestrictionTypes( $exists = true ) {
2588 global $wgRestrictionTypes;
2589 $types = $wgRestrictionTypes;
2590 if ( $exists ) {
2591 # Remove the create restriction for existing titles
2592 $types = array_diff( $types, [ 'create' ] );
2593 } else {
2594 # Only the create and upload restrictions apply to non-existing titles
2595 $types = array_intersect( $types, [ 'create', 'upload' ] );
2596 }
2597 return $types;
2598 }
2599
2600 /**
2601 * Returns restriction types for the current Title
2602 *
2603 * @return array Applicable restriction types
2604 */
2605 public function getRestrictionTypes() {
2606 if ( $this->isSpecialPage() ) {
2607 return [];
2608 }
2609
2610 $types = self::getFilteredRestrictionTypes( $this->exists() );
2611
2612 if ( $this->getNamespace() != NS_FILE ) {
2613 # Remove the upload restriction for non-file titles
2614 $types = array_diff( $types, [ 'upload' ] );
2615 }
2616
2617 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2618
2619 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2620 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2621
2622 return $types;
2623 }
2624
2625 /**
2626 * Is this title subject to title protection?
2627 * Title protection is the one applied against creation of such title.
2628 *
2629 * @return array|bool An associative array representing any existent title
2630 * protection, or false if there's none.
2631 */
2632 public function getTitleProtection() {
2633 $protection = $this->getTitleProtectionInternal();
2634 if ( $protection ) {
2635 if ( $protection['permission'] == 'sysop' ) {
2636 $protection['permission'] = 'editprotected'; // B/C
2637 }
2638 if ( $protection['permission'] == 'autoconfirmed' ) {
2639 $protection['permission'] = 'editsemiprotected'; // B/C
2640 }
2641 }
2642 return $protection;
2643 }
2644
2645 /**
2646 * Fetch title protection settings
2647 *
2648 * To work correctly, $this->loadRestrictions() needs to have access to the
2649 * actual protections in the database without munging 'sysop' =>
2650 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2651 * callers probably want $this->getTitleProtection() instead.
2652 *
2653 * @return array|bool
2654 */
2655 protected function getTitleProtectionInternal() {
2656 // Can't protect pages in special namespaces
2657 if ( $this->getNamespace() < 0 ) {
2658 return false;
2659 }
2660
2661 // Can't protect pages that exist.
2662 if ( $this->exists() ) {
2663 return false;
2664 }
2665
2666 if ( $this->mTitleProtection === null ) {
2667 $dbr = wfGetDB( DB_REPLICA );
2668 $res = $dbr->select(
2669 'protected_titles',
2670 [
2671 'user' => 'pt_user',
2672 'reason' => 'pt_reason',
2673 'expiry' => 'pt_expiry',
2674 'permission' => 'pt_create_perm'
2675 ],
2676 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2677 __METHOD__
2678 );
2679
2680 // fetchRow returns false if there are no rows.
2681 $row = $dbr->fetchRow( $res );
2682 if ( $row ) {
2683 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2684 }
2685 $this->mTitleProtection = $row;
2686 }
2687 return $this->mTitleProtection;
2688 }
2689
2690 /**
2691 * Remove any title protection due to page existing
2692 */
2693 public function deleteTitleProtection() {
2694 $dbw = wfGetDB( DB_MASTER );
2695
2696 $dbw->delete(
2697 'protected_titles',
2698 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2699 __METHOD__
2700 );
2701 $this->mTitleProtection = false;
2702 }
2703
2704 /**
2705 * Is this page "semi-protected" - the *only* protection levels are listed
2706 * in $wgSemiprotectedRestrictionLevels?
2707 *
2708 * @param string $action Action to check (default: edit)
2709 * @return bool
2710 */
2711 public function isSemiProtected( $action = 'edit' ) {
2712 global $wgSemiprotectedRestrictionLevels;
2713
2714 $restrictions = $this->getRestrictions( $action );
2715 $semi = $wgSemiprotectedRestrictionLevels;
2716 if ( !$restrictions || !$semi ) {
2717 // Not protected, or all protection is full protection
2718 return false;
2719 }
2720
2721 // Remap autoconfirmed to editsemiprotected for BC
2722 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2723 $semi[$key] = 'editsemiprotected';
2724 }
2725 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2726 $restrictions[$key] = 'editsemiprotected';
2727 }
2728
2729 return !array_diff( $restrictions, $semi );
2730 }
2731
2732 /**
2733 * Does the title correspond to a protected article?
2734 *
2735 * @param string $action The action the page is protected from,
2736 * by default checks all actions.
2737 * @return bool
2738 */
2739 public function isProtected( $action = '' ) {
2740 global $wgRestrictionLevels;
2741
2742 $restrictionTypes = $this->getRestrictionTypes();
2743
2744 # Special pages have inherent protection
2745 if ( $this->isSpecialPage() ) {
2746 return true;
2747 }
2748
2749 # Check regular protection levels
2750 foreach ( $restrictionTypes as $type ) {
2751 if ( $action == $type || $action == '' ) {
2752 $r = $this->getRestrictions( $type );
2753 foreach ( $wgRestrictionLevels as $level ) {
2754 if ( in_array( $level, $r ) && $level != '' ) {
2755 return true;
2756 }
2757 }
2758 }
2759 }
2760
2761 return false;
2762 }
2763
2764 /**
2765 * Determines if $user is unable to edit this page because it has been protected
2766 * by $wgNamespaceProtection.
2767 *
2768 * @param User $user User object to check permissions
2769 * @return bool
2770 */
2771 public function isNamespaceProtected( User $user ) {
2772 global $wgNamespaceProtection;
2773
2774 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2775 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2776 if ( $right != '' && !$user->isAllowed( $right ) ) {
2777 return true;
2778 }
2779 }
2780 }
2781 return false;
2782 }
2783
2784 /**
2785 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2786 *
2787 * @return bool If the page is subject to cascading restrictions.
2788 */
2789 public function isCascadeProtected() {
2790 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2791 return ( $sources > 0 );
2792 }
2793
2794 /**
2795 * Determines whether cascading protection sources have already been loaded from
2796 * the database.
2797 *
2798 * @param bool $getPages True to check if the pages are loaded, or false to check
2799 * if the status is loaded.
2800 * @return bool Whether or not the specified information has been loaded
2801 * @since 1.23
2802 */
2803 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2804 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2805 }
2806
2807 /**
2808 * Cascading protection: Get the source of any cascading restrictions on this page.
2809 *
2810 * @param bool $getPages Whether or not to retrieve the actual pages
2811 * that the restrictions have come from and the actual restrictions
2812 * themselves.
2813 * @return array Two elements: First is an array of Title objects of the
2814 * pages from which cascading restrictions have come, false for
2815 * none, or true if such restrictions exist but $getPages was not
2816 * set. Second is an array like that returned by
2817 * Title::getAllRestrictions(), or an empty array if $getPages is
2818 * false.
2819 */
2820 public function getCascadeProtectionSources( $getPages = true ) {
2821 $pagerestrictions = [];
2822
2823 if ( $this->mCascadeSources !== null && $getPages ) {
2824 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2825 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2826 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2827 }
2828
2829 $dbr = wfGetDB( DB_REPLICA );
2830
2831 if ( $this->getNamespace() == NS_FILE ) {
2832 $tables = [ 'imagelinks', 'page_restrictions' ];
2833 $where_clauses = [
2834 'il_to' => $this->getDBkey(),
2835 'il_from=pr_page',
2836 'pr_cascade' => 1
2837 ];
2838 } else {
2839 $tables = [ 'templatelinks', 'page_restrictions' ];
2840 $where_clauses = [
2841 'tl_namespace' => $this->getNamespace(),
2842 'tl_title' => $this->getDBkey(),
2843 'tl_from=pr_page',
2844 'pr_cascade' => 1
2845 ];
2846 }
2847
2848 if ( $getPages ) {
2849 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2850 'pr_expiry', 'pr_type', 'pr_level' ];
2851 $where_clauses[] = 'page_id=pr_page';
2852 $tables[] = 'page';
2853 } else {
2854 $cols = [ 'pr_expiry' ];
2855 }
2856
2857 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2858
2859 $sources = $getPages ? [] : false;
2860 $now = wfTimestampNow();
2861
2862 foreach ( $res as $row ) {
2863 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2864 if ( $expiry > $now ) {
2865 if ( $getPages ) {
2866 $page_id = $row->pr_page;
2867 $page_ns = $row->page_namespace;
2868 $page_title = $row->page_title;
2869 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
2870 # Add groups needed for each restriction type if its not already there
2871 # Make sure this restriction type still exists
2872
2873 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2874 $pagerestrictions[$row->pr_type] = [];
2875 }
2876
2877 if (
2878 isset( $pagerestrictions[$row->pr_type] )
2879 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2880 ) {
2881 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2882 }
2883 } else {
2884 $sources = true;
2885 }
2886 }
2887 }
2888
2889 if ( $getPages ) {
2890 $this->mCascadeSources = $sources;
2891 $this->mCascadingRestrictions = $pagerestrictions;
2892 } else {
2893 $this->mHasCascadingRestrictions = $sources;
2894 }
2895
2896 return [ $sources, $pagerestrictions ];
2897 }
2898
2899 /**
2900 * Accessor for mRestrictionsLoaded
2901 *
2902 * @return bool Whether or not the page's restrictions have already been
2903 * loaded from the database
2904 * @since 1.23
2905 */
2906 public function areRestrictionsLoaded() {
2907 return $this->mRestrictionsLoaded;
2908 }
2909
2910 /**
2911 * Accessor/initialisation for mRestrictions
2912 *
2913 * @param string $action Action that permission needs to be checked for
2914 * @return array Restriction levels needed to take the action. All levels are
2915 * required. Note that restriction levels are normally user rights, but 'sysop'
2916 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2917 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2918 */
2919 public function getRestrictions( $action ) {
2920 if ( !$this->mRestrictionsLoaded ) {
2921 $this->loadRestrictions();
2922 }
2923 return isset( $this->mRestrictions[$action] )
2924 ? $this->mRestrictions[$action]
2925 : [];
2926 }
2927
2928 /**
2929 * Accessor/initialisation for mRestrictions
2930 *
2931 * @return array Keys are actions, values are arrays as returned by
2932 * Title::getRestrictions()
2933 * @since 1.23
2934 */
2935 public function getAllRestrictions() {
2936 if ( !$this->mRestrictionsLoaded ) {
2937 $this->loadRestrictions();
2938 }
2939 return $this->mRestrictions;
2940 }
2941
2942 /**
2943 * Get the expiry time for the restriction against a given action
2944 *
2945 * @param string $action
2946 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2947 * or not protected at all, or false if the action is not recognised.
2948 */
2949 public function getRestrictionExpiry( $action ) {
2950 if ( !$this->mRestrictionsLoaded ) {
2951 $this->loadRestrictions();
2952 }
2953 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2954 }
2955
2956 /**
2957 * Returns cascading restrictions for the current article
2958 *
2959 * @return bool
2960 */
2961 function areRestrictionsCascading() {
2962 if ( !$this->mRestrictionsLoaded ) {
2963 $this->loadRestrictions();
2964 }
2965
2966 return $this->mCascadeRestriction;
2967 }
2968
2969 /**
2970 * Compiles list of active page restrictions from both page table (pre 1.10)
2971 * and page_restrictions table for this existing page.
2972 * Public for usage by LiquidThreads.
2973 *
2974 * @param array $rows Array of db result objects
2975 * @param string $oldFashionedRestrictions Comma-separated list of page
2976 * restrictions from page table (pre 1.10)
2977 */
2978 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2979 $dbr = wfGetDB( DB_REPLICA );
2980
2981 $restrictionTypes = $this->getRestrictionTypes();
2982
2983 foreach ( $restrictionTypes as $type ) {
2984 $this->mRestrictions[$type] = [];
2985 $this->mRestrictionsExpiry[$type] = 'infinity';
2986 }
2987
2988 $this->mCascadeRestriction = false;
2989
2990 # Backwards-compatibility: also load the restrictions from the page record (old format).
2991 if ( $oldFashionedRestrictions !== null ) {
2992 $this->mOldRestrictions = $oldFashionedRestrictions;
2993 }
2994
2995 if ( $this->mOldRestrictions === false ) {
2996 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2997 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
2998 }
2999
3000 if ( $this->mOldRestrictions != '' ) {
3001 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
3002 $temp = explode( '=', trim( $restrict ) );
3003 if ( count( $temp ) == 1 ) {
3004 // old old format should be treated as edit/move restriction
3005 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
3006 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
3007 } else {
3008 $restriction = trim( $temp[1] );
3009 if ( $restriction != '' ) { // some old entries are empty
3010 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
3011 }
3012 }
3013 }
3014 }
3015
3016 if ( count( $rows ) ) {
3017 # Current system - load second to make them override.
3018 $now = wfTimestampNow();
3019
3020 # Cycle through all the restrictions.
3021 foreach ( $rows as $row ) {
3022 // Don't take care of restrictions types that aren't allowed
3023 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
3024 continue;
3025 }
3026
3027 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3028
3029 // Only apply the restrictions if they haven't expired!
3030 if ( !$expiry || $expiry > $now ) {
3031 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
3032 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
3033
3034 $this->mCascadeRestriction |= $row->pr_cascade;
3035 }
3036 }
3037 }
3038
3039 $this->mRestrictionsLoaded = true;
3040 }
3041
3042 /**
3043 * Load restrictions from the page_restrictions table
3044 *
3045 * @param string $oldFashionedRestrictions Comma-separated list of page
3046 * restrictions from page table (pre 1.10)
3047 */
3048 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3049 if ( $this->mRestrictionsLoaded ) {
3050 return;
3051 }
3052
3053 $id = $this->getArticleID();
3054 if ( $id ) {
3055 $cache = ObjectCache::getMainWANInstance();
3056 $rows = $cache->getWithSetCallback(
3057 // Page protections always leave a new null revision
3058 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3059 $cache::TTL_DAY,
3060 function ( $curValue, &$ttl, array &$setOpts ) {
3061 $dbr = wfGetDB( DB_REPLICA );
3062
3063 $setOpts += Database::getCacheSetOptions( $dbr );
3064
3065 return iterator_to_array(
3066 $dbr->select(
3067 'page_restrictions',
3068 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3069 [ 'pr_page' => $this->getArticleID() ],
3070 __METHOD__
3071 )
3072 );
3073 }
3074 );
3075
3076 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3077 } else {
3078 $title_protection = $this->getTitleProtectionInternal();
3079
3080 if ( $title_protection ) {
3081 $now = wfTimestampNow();
3082 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3083
3084 if ( !$expiry || $expiry > $now ) {
3085 // Apply the restrictions
3086 $this->mRestrictionsExpiry['create'] = $expiry;
3087 $this->mRestrictions['create'] =
3088 explode( ',', trim( $title_protection['permission'] ) );
3089 } else { // Get rid of the old restrictions
3090 $this->mTitleProtection = false;
3091 }
3092 } else {
3093 $this->mRestrictionsExpiry['create'] = 'infinity';
3094 }
3095 $this->mRestrictionsLoaded = true;
3096 }
3097 }
3098
3099 /**
3100 * Flush the protection cache in this object and force reload from the database.
3101 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3102 */
3103 public function flushRestrictions() {
3104 $this->mRestrictionsLoaded = false;
3105 $this->mTitleProtection = null;
3106 }
3107
3108 /**
3109 * Purge expired restrictions from the page_restrictions table
3110 *
3111 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3112 */
3113 static function purgeExpiredRestrictions() {
3114 if ( wfReadOnly() ) {
3115 return;
3116 }
3117
3118 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3119 wfGetDB( DB_MASTER ),
3120 __METHOD__,
3121 function ( IDatabase $dbw, $fname ) {
3122 $config = MediaWikiServices::getInstance()->getMainConfig();
3123 $ids = $dbw->selectFieldValues(
3124 'page_restrictions',
3125 'pr_id',
3126 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3127 $fname,
3128 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3129 );
3130 if ( $ids ) {
3131 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3132 }
3133 }
3134 ) );
3135
3136 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3137 wfGetDB( DB_MASTER ),
3138 __METHOD__,
3139 function ( IDatabase $dbw, $fname ) {
3140 $dbw->delete(
3141 'protected_titles',
3142 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3143 $fname
3144 );
3145 }
3146 ) );
3147 }
3148
3149 /**
3150 * Does this have subpages? (Warning, usually requires an extra DB query.)
3151 *
3152 * @return bool
3153 */
3154 public function hasSubpages() {
3155 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3156 # Duh
3157 return false;
3158 }
3159
3160 # We dynamically add a member variable for the purpose of this method
3161 # alone to cache the result. There's no point in having it hanging
3162 # around uninitialized in every Title object; therefore we only add it
3163 # if needed and don't declare it statically.
3164 if ( $this->mHasSubpages === null ) {
3165 $this->mHasSubpages = false;
3166 $subpages = $this->getSubpages( 1 );
3167 if ( $subpages instanceof TitleArray ) {
3168 $this->mHasSubpages = (bool)$subpages->count();
3169 }
3170 }
3171
3172 return $this->mHasSubpages;
3173 }
3174
3175 /**
3176 * Get all subpages of this page.
3177 *
3178 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3179 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3180 * doesn't allow subpages
3181 */
3182 public function getSubpages( $limit = -1 ) {
3183 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3184 return [];
3185 }
3186
3187 $dbr = wfGetDB( DB_REPLICA );
3188 $conds['page_namespace'] = $this->getNamespace();
3189 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3190 $options = [];
3191 if ( $limit > -1 ) {
3192 $options['LIMIT'] = $limit;
3193 }
3194 return TitleArray::newFromResult(
3195 $dbr->select( 'page',
3196 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3197 $conds,
3198 __METHOD__,
3199 $options
3200 )
3201 );
3202 }
3203
3204 /**
3205 * Is there a version of this page in the deletion archive?
3206 *
3207 * @return int The number of archived revisions
3208 */
3209 public function isDeleted() {
3210 if ( $this->getNamespace() < 0 ) {
3211 $n = 0;
3212 } else {
3213 $dbr = wfGetDB( DB_REPLICA );
3214
3215 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3216 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3217 __METHOD__
3218 );
3219 if ( $this->getNamespace() == NS_FILE ) {
3220 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3221 [ 'fa_name' => $this->getDBkey() ],
3222 __METHOD__
3223 );
3224 }
3225 }
3226 return (int)$n;
3227 }
3228
3229 /**
3230 * Is there a version of this page in the deletion archive?
3231 *
3232 * @return bool
3233 */
3234 public function isDeletedQuick() {
3235 if ( $this->getNamespace() < 0 ) {
3236 return false;
3237 }
3238 $dbr = wfGetDB( DB_REPLICA );
3239 $deleted = (bool)$dbr->selectField( 'archive', '1',
3240 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3241 __METHOD__
3242 );
3243 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3244 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3245 [ 'fa_name' => $this->getDBkey() ],
3246 __METHOD__
3247 );
3248 }
3249 return $deleted;
3250 }
3251
3252 /**
3253 * Get the article ID for this Title from the link cache,
3254 * adding it if necessary
3255 *
3256 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3257 * for update
3258 * @return int The ID
3259 */
3260 public function getArticleID( $flags = 0 ) {
3261 if ( $this->getNamespace() < 0 ) {
3262 $this->mArticleID = 0;
3263 return $this->mArticleID;
3264 }
3265 $linkCache = LinkCache::singleton();
3266 if ( $flags & self::GAID_FOR_UPDATE ) {
3267 $oldUpdate = $linkCache->forUpdate( true );
3268 $linkCache->clearLink( $this );
3269 $this->mArticleID = $linkCache->addLinkObj( $this );
3270 $linkCache->forUpdate( $oldUpdate );
3271 } else {
3272 if ( -1 == $this->mArticleID ) {
3273 $this->mArticleID = $linkCache->addLinkObj( $this );
3274 }
3275 }
3276 return $this->mArticleID;
3277 }
3278
3279 /**
3280 * Is this an article that is a redirect page?
3281 * Uses link cache, adding it if necessary
3282 *
3283 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3284 * @return bool
3285 */
3286 public function isRedirect( $flags = 0 ) {
3287 if ( !is_null( $this->mRedirect ) ) {
3288 return $this->mRedirect;
3289 }
3290 if ( !$this->getArticleID( $flags ) ) {
3291 $this->mRedirect = false;
3292 return $this->mRedirect;
3293 }
3294
3295 $linkCache = LinkCache::singleton();
3296 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3297 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3298 if ( $cached === null ) {
3299 # Trust LinkCache's state over our own
3300 # LinkCache is telling us that the page doesn't exist, despite there being cached
3301 # data relating to an existing page in $this->mArticleID. Updaters should clear
3302 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3303 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3304 # LinkCache to refresh its data from the master.
3305 $this->mRedirect = false;
3306 return $this->mRedirect;
3307 }
3308
3309 $this->mRedirect = (bool)$cached;
3310
3311 return $this->mRedirect;
3312 }
3313
3314 /**
3315 * What is the length of this page?
3316 * Uses link cache, adding it if necessary
3317 *
3318 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3319 * @return int
3320 */
3321 public function getLength( $flags = 0 ) {
3322 if ( $this->mLength != -1 ) {
3323 return $this->mLength;
3324 }
3325 if ( !$this->getArticleID( $flags ) ) {
3326 $this->mLength = 0;
3327 return $this->mLength;
3328 }
3329 $linkCache = LinkCache::singleton();
3330 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3331 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3332 if ( $cached === null ) {
3333 # Trust LinkCache's state over our own, as for isRedirect()
3334 $this->mLength = 0;
3335 return $this->mLength;
3336 }
3337
3338 $this->mLength = intval( $cached );
3339
3340 return $this->mLength;
3341 }
3342
3343 /**
3344 * What is the page_latest field for this page?
3345 *
3346 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3347 * @return int Int or 0 if the page doesn't exist
3348 */
3349 public function getLatestRevID( $flags = 0 ) {
3350 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3351 return intval( $this->mLatestID );
3352 }
3353 if ( !$this->getArticleID( $flags ) ) {
3354 $this->mLatestID = 0;
3355 return $this->mLatestID;
3356 }
3357 $linkCache = LinkCache::singleton();
3358 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3359 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3360 if ( $cached === null ) {
3361 # Trust LinkCache's state over our own, as for isRedirect()
3362 $this->mLatestID = 0;
3363 return $this->mLatestID;
3364 }
3365
3366 $this->mLatestID = intval( $cached );
3367
3368 return $this->mLatestID;
3369 }
3370
3371 /**
3372 * This clears some fields in this object, and clears any associated
3373 * keys in the "bad links" section of the link cache.
3374 *
3375 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3376 * loading of the new page_id. It's also called from
3377 * WikiPage::doDeleteArticleReal()
3378 *
3379 * @param int $newid The new Article ID
3380 */
3381 public function resetArticleID( $newid ) {
3382 $linkCache = LinkCache::singleton();
3383 $linkCache->clearLink( $this );
3384
3385 if ( $newid === false ) {
3386 $this->mArticleID = -1;
3387 } else {
3388 $this->mArticleID = intval( $newid );
3389 }
3390 $this->mRestrictionsLoaded = false;
3391 $this->mRestrictions = [];
3392 $this->mOldRestrictions = false;
3393 $this->mRedirect = null;
3394 $this->mLength = -1;
3395 $this->mLatestID = false;
3396 $this->mContentModel = false;
3397 $this->mEstimateRevisions = null;
3398 $this->mPageLanguage = false;
3399 $this->mDbPageLanguage = false;
3400 $this->mIsBigDeletion = null;
3401 }
3402
3403 public static function clearCaches() {
3404 $linkCache = LinkCache::singleton();
3405 $linkCache->clear();
3406
3407 $titleCache = self::getTitleCache();
3408 $titleCache->clear();
3409 }
3410
3411 /**
3412 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3413 *
3414 * @param string $text Containing title to capitalize
3415 * @param int $ns Namespace index, defaults to NS_MAIN
3416 * @return string Containing capitalized title
3417 */
3418 public static function capitalize( $text, $ns = NS_MAIN ) {
3419 global $wgContLang;
3420
3421 if ( MWNamespace::isCapitalized( $ns ) ) {
3422 return $wgContLang->ucfirst( $text );
3423 } else {
3424 return $text;
3425 }
3426 }
3427
3428 /**
3429 * Secure and split - main initialisation function for this object
3430 *
3431 * Assumes that mDbkeyform has been set, and is urldecoded
3432 * and uses underscores, but not otherwise munged. This function
3433 * removes illegal characters, splits off the interwiki and
3434 * namespace prefixes, sets the other forms, and canonicalizes
3435 * everything.
3436 *
3437 * @throws MalformedTitleException On invalid titles
3438 * @return bool True on success
3439 */
3440 private function secureAndSplit() {
3441 # Initialisation
3442 $this->mInterwiki = '';
3443 $this->mFragment = '';
3444 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3445
3446 $dbkey = $this->mDbkeyform;
3447
3448 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3449 // the parsing code with Title, while avoiding massive refactoring.
3450 // @todo: get rid of secureAndSplit, refactor parsing code.
3451 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3452 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3453 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3454 // MalformedTitleException can be thrown here
3455 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3456
3457 # Fill fields
3458 $this->setFragment( '#' . $parts['fragment'] );
3459 $this->mInterwiki = $parts['interwiki'];
3460 $this->mLocalInterwiki = $parts['local_interwiki'];
3461 $this->mNamespace = $parts['namespace'];
3462 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3463
3464 $this->mDbkeyform = $parts['dbkey'];
3465 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3466 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3467
3468 # We already know that some pages won't be in the database!
3469 if ( $this->isExternal() || $this->isSpecialPage() ) {
3470 $this->mArticleID = 0;
3471 }
3472
3473 return true;
3474 }
3475
3476 /**
3477 * Get an array of Title objects linking to this Title
3478 * Also stores the IDs in the link cache.
3479 *
3480 * WARNING: do not use this function on arbitrary user-supplied titles!
3481 * On heavily-used templates it will max out the memory.
3482 *
3483 * @param array $options May be FOR UPDATE
3484 * @param string $table Table name
3485 * @param string $prefix Fields prefix
3486 * @return Title[] Array of Title objects linking here
3487 */
3488 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3489 if ( count( $options ) > 0 ) {
3490 $db = wfGetDB( DB_MASTER );
3491 } else {
3492 $db = wfGetDB( DB_REPLICA );
3493 }
3494
3495 $res = $db->select(
3496 [ 'page', $table ],
3497 self::getSelectFields(),
3498 [
3499 "{$prefix}_from=page_id",
3500 "{$prefix}_namespace" => $this->getNamespace(),
3501 "{$prefix}_title" => $this->getDBkey() ],
3502 __METHOD__,
3503 $options
3504 );
3505
3506 $retVal = [];
3507 if ( $res->numRows() ) {
3508 $linkCache = LinkCache::singleton();
3509 foreach ( $res as $row ) {
3510 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3511 if ( $titleObj ) {
3512 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3513 $retVal[] = $titleObj;
3514 }
3515 }
3516 }
3517 return $retVal;
3518 }
3519
3520 /**
3521 * Get an array of Title objects using this Title as a template
3522 * Also stores the IDs in the link cache.
3523 *
3524 * WARNING: do not use this function on arbitrary user-supplied titles!
3525 * On heavily-used templates it will max out the memory.
3526 *
3527 * @param array $options Query option to Database::select()
3528 * @return Title[] Array of Title the Title objects linking here
3529 */
3530 public function getTemplateLinksTo( $options = [] ) {
3531 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3532 }
3533
3534 /**
3535 * Get an array of Title objects linked from this Title
3536 * Also stores the IDs in the link cache.
3537 *
3538 * WARNING: do not use this function on arbitrary user-supplied titles!
3539 * On heavily-used templates it will max out the memory.
3540 *
3541 * @param array $options Query option to Database::select()
3542 * @param string $table Table name
3543 * @param string $prefix Fields prefix
3544 * @return array Array of Title objects linking here
3545 */
3546 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3547 $id = $this->getArticleID();
3548
3549 # If the page doesn't exist; there can't be any link from this page
3550 if ( !$id ) {
3551 return [];
3552 }
3553
3554 $db = wfGetDB( DB_REPLICA );
3555
3556 $blNamespace = "{$prefix}_namespace";
3557 $blTitle = "{$prefix}_title";
3558
3559 $res = $db->select(
3560 [ $table, 'page' ],
3561 array_merge(
3562 [ $blNamespace, $blTitle ],
3563 WikiPage::selectFields()
3564 ),
3565 [ "{$prefix}_from" => $id ],
3566 __METHOD__,
3567 $options,
3568 [ 'page' => [
3569 'LEFT JOIN',
3570 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3571 ] ]
3572 );
3573
3574 $retVal = [];
3575 $linkCache = LinkCache::singleton();
3576 foreach ( $res as $row ) {
3577 if ( $row->page_id ) {
3578 $titleObj = self::newFromRow( $row );
3579 } else {
3580 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3581 $linkCache->addBadLinkObj( $titleObj );
3582 }
3583 $retVal[] = $titleObj;
3584 }
3585
3586 return $retVal;
3587 }
3588
3589 /**
3590 * Get an array of Title objects used on this Title as a template
3591 * Also stores the IDs in the link cache.
3592 *
3593 * WARNING: do not use this function on arbitrary user-supplied titles!
3594 * On heavily-used templates it will max out the memory.
3595 *
3596 * @param array $options May be FOR UPDATE
3597 * @return Title[] Array of Title the Title objects used here
3598 */
3599 public function getTemplateLinksFrom( $options = [] ) {
3600 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3601 }
3602
3603 /**
3604 * Get an array of Title objects referring to non-existent articles linked
3605 * from this page.
3606 *
3607 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3608 * should use redirect table in this case).
3609 * @return Title[] Array of Title the Title objects
3610 */
3611 public function getBrokenLinksFrom() {
3612 if ( $this->getArticleID() == 0 ) {
3613 # All links from article ID 0 are false positives
3614 return [];
3615 }
3616
3617 $dbr = wfGetDB( DB_REPLICA );
3618 $res = $dbr->select(
3619 [ 'page', 'pagelinks' ],
3620 [ 'pl_namespace', 'pl_title' ],
3621 [
3622 'pl_from' => $this->getArticleID(),
3623 'page_namespace IS NULL'
3624 ],
3625 __METHOD__, [],
3626 [
3627 'page' => [
3628 'LEFT JOIN',
3629 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3630 ]
3631 ]
3632 );
3633
3634 $retVal = [];
3635 foreach ( $res as $row ) {
3636 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3637 }
3638 return $retVal;
3639 }
3640
3641 /**
3642 * Get a list of URLs to purge from the CDN cache when this
3643 * page changes
3644 *
3645 * @return string[] Array of String the URLs
3646 */
3647 public function getCdnUrls() {
3648 $urls = [
3649 $this->getInternalURL(),
3650 $this->getInternalURL( 'action=history' )
3651 ];
3652
3653 $pageLang = $this->getPageLanguage();
3654 if ( $pageLang->hasVariants() ) {
3655 $variants = $pageLang->getVariants();
3656 foreach ( $variants as $vCode ) {
3657 $urls[] = $this->getInternalURL( $vCode );
3658 }
3659 }
3660
3661 // If we are looking at a css/js user subpage, purge the action=raw.
3662 if ( $this->isJsSubpage() ) {
3663 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3664 } elseif ( $this->isCssSubpage() ) {
3665 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3666 }
3667
3668 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3669 return $urls;
3670 }
3671
3672 /**
3673 * @deprecated since 1.27 use getCdnUrls()
3674 */
3675 public function getSquidURLs() {
3676 return $this->getCdnUrls();
3677 }
3678
3679 /**
3680 * Purge all applicable CDN URLs
3681 */
3682 public function purgeSquid() {
3683 DeferredUpdates::addUpdate(
3684 new CdnCacheUpdate( $this->getCdnUrls() ),
3685 DeferredUpdates::PRESEND
3686 );
3687 }
3688
3689 /**
3690 * Check whether a given move operation would be valid.
3691 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3692 *
3693 * @deprecated since 1.25, use MovePage's methods instead
3694 * @param Title $nt The new title
3695 * @param bool $auth Whether to check user permissions (uses $wgUser)
3696 * @param string $reason Is the log summary of the move, used for spam checking
3697 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3698 */
3699 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3700 global $wgUser;
3701
3702 if ( !( $nt instanceof Title ) ) {
3703 // Normally we'd add this to $errors, but we'll get
3704 // lots of syntax errors if $nt is not an object
3705 return [ [ 'badtitletext' ] ];
3706 }
3707
3708 $mp = new MovePage( $this, $nt );
3709 $errors = $mp->isValidMove()->getErrorsArray();
3710 if ( $auth ) {
3711 $errors = wfMergeErrorArrays(
3712 $errors,
3713 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3714 );
3715 }
3716
3717 return $errors ?: true;
3718 }
3719
3720 /**
3721 * Check if the requested move target is a valid file move target
3722 * @todo move this to MovePage
3723 * @param Title $nt Target title
3724 * @return array List of errors
3725 */
3726 protected function validateFileMoveOperation( $nt ) {
3727 global $wgUser;
3728
3729 $errors = [];
3730
3731 $destFile = wfLocalFile( $nt );
3732 $destFile->load( File::READ_LATEST );
3733 if ( !$wgUser->isAllowed( 'reupload-shared' )
3734 && !$destFile->exists() && wfFindFile( $nt )
3735 ) {
3736 $errors[] = [ 'file-exists-sharedrepo' ];
3737 }
3738
3739 return $errors;
3740 }
3741
3742 /**
3743 * Move a title to a new location
3744 *
3745 * @deprecated since 1.25, use the MovePage class instead
3746 * @param Title $nt The new title
3747 * @param bool $auth Indicates whether $wgUser's permissions
3748 * should be checked
3749 * @param string $reason The reason for the move
3750 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3751 * Ignored if the user doesn't have the suppressredirect right.
3752 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3753 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3754 */
3755 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3756 array $changeTags = []
3757 ) {
3758 global $wgUser;
3759 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3760 if ( is_array( $err ) ) {
3761 // Auto-block user's IP if the account was "hard" blocked
3762 $wgUser->spreadAnyEditBlock();
3763 return $err;
3764 }
3765 // Check suppressredirect permission
3766 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3767 $createRedirect = true;
3768 }
3769
3770 $mp = new MovePage( $this, $nt );
3771 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3772 if ( $status->isOK() ) {
3773 return true;
3774 } else {
3775 return $status->getErrorsArray();
3776 }
3777 }
3778
3779 /**
3780 * Move this page's subpages to be subpages of $nt
3781 *
3782 * @param Title $nt Move target
3783 * @param bool $auth Whether $wgUser's permissions should be checked
3784 * @param string $reason The reason for the move
3785 * @param bool $createRedirect Whether to create redirects from the old subpages to
3786 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3787 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3788 * @return array Array with old page titles as keys, and strings (new page titles) or
3789 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3790 * getUserPermissionsErrors()-like error array with numeric indices if
3791 * no pages were moved
3792 */
3793 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3794 array $changeTags = []
3795 ) {
3796 global $wgMaximumMovedPages;
3797 // Check permissions
3798 if ( !$this->userCan( 'move-subpages' ) ) {
3799 return [
3800 [ 'cant-move-subpages' ],
3801 ];
3802 }
3803 // Do the source and target namespaces support subpages?
3804 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3805 return [
3806 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->getNamespace() ) ],
3807 ];
3808 }
3809 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3810 return [
3811 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
3812 ];
3813 }
3814
3815 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3816 $retval = [];
3817 $count = 0;
3818 foreach ( $subpages as $oldSubpage ) {
3819 $count++;
3820 if ( $count > $wgMaximumMovedPages ) {
3821 $retval[$oldSubpage->getPrefixedText()] = [
3822 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3823 ];
3824 break;
3825 }
3826
3827 // We don't know whether this function was called before
3828 // or after moving the root page, so check both
3829 // $this and $nt
3830 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3831 || $oldSubpage->getArticleID() == $nt->getArticleID()
3832 ) {
3833 // When moving a page to a subpage of itself,
3834 // don't move it twice
3835 continue;
3836 }
3837 $newPageName = preg_replace(
3838 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3839 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3840 $oldSubpage->getDBkey() );
3841 if ( $oldSubpage->isTalkPage() ) {
3842 $newNs = $nt->getTalkPage()->getNamespace();
3843 } else {
3844 $newNs = $nt->getSubjectPage()->getNamespace();
3845 }
3846 # T16385: we need makeTitleSafe because the new page names may
3847 # be longer than 255 characters.
3848 $newSubpage = self::makeTitleSafe( $newNs, $newPageName );
3849
3850 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3851 if ( $success === true ) {
3852 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3853 } else {
3854 $retval[$oldSubpage->getPrefixedText()] = $success;
3855 }
3856 }
3857 return $retval;
3858 }
3859
3860 /**
3861 * Checks if this page is just a one-rev redirect.
3862 * Adds lock, so don't use just for light purposes.
3863 *
3864 * @return bool
3865 */
3866 public function isSingleRevRedirect() {
3867 global $wgContentHandlerUseDB;
3868
3869 $dbw = wfGetDB( DB_MASTER );
3870
3871 # Is it a redirect?
3872 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3873 if ( $wgContentHandlerUseDB ) {
3874 $fields[] = 'page_content_model';
3875 }
3876
3877 $row = $dbw->selectRow( 'page',
3878 $fields,
3879 $this->pageCond(),
3880 __METHOD__,
3881 [ 'FOR UPDATE' ]
3882 );
3883 # Cache some fields we may want
3884 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3885 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3886 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3887 $this->mContentModel = $row && isset( $row->page_content_model )
3888 ? strval( $row->page_content_model )
3889 : false;
3890
3891 if ( !$this->mRedirect ) {
3892 return false;
3893 }
3894 # Does the article have a history?
3895 $row = $dbw->selectField( [ 'page', 'revision' ],
3896 'rev_id',
3897 [ 'page_namespace' => $this->getNamespace(),
3898 'page_title' => $this->getDBkey(),
3899 'page_id=rev_page',
3900 'page_latest != rev_id'
3901 ],
3902 __METHOD__,
3903 [ 'FOR UPDATE' ]
3904 );
3905 # Return true if there was no history
3906 return ( $row === false );
3907 }
3908
3909 /**
3910 * Checks if $this can be moved to a given Title
3911 * - Selects for update, so don't call it unless you mean business
3912 *
3913 * @deprecated since 1.25, use MovePage's methods instead
3914 * @param Title $nt The new title to check
3915 * @return bool
3916 */
3917 public function isValidMoveTarget( $nt ) {
3918 # Is it an existing file?
3919 if ( $nt->getNamespace() == NS_FILE ) {
3920 $file = wfLocalFile( $nt );
3921 $file->load( File::READ_LATEST );
3922 if ( $file->exists() ) {
3923 wfDebug( __METHOD__ . ": file exists\n" );
3924 return false;
3925 }
3926 }
3927 # Is it a redirect with no history?
3928 if ( !$nt->isSingleRevRedirect() ) {
3929 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3930 return false;
3931 }
3932 # Get the article text
3933 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3934 if ( !is_object( $rev ) ) {
3935 return false;
3936 }
3937 $content = $rev->getContent();
3938 # Does the redirect point to the source?
3939 # Or is it a broken self-redirect, usually caused by namespace collisions?
3940 $redirTitle = $content ? $content->getRedirectTarget() : null;
3941
3942 if ( $redirTitle ) {
3943 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3944 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3945 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3946 return false;
3947 } else {
3948 return true;
3949 }
3950 } else {
3951 # Fail safe (not a redirect after all. strange.)
3952 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3953 " is a redirect, but it doesn't contain a valid redirect.\n" );
3954 return false;
3955 }
3956 }
3957
3958 /**
3959 * Get categories to which this Title belongs and return an array of
3960 * categories' names.
3961 *
3962 * @return array Array of parents in the form:
3963 * $parent => $currentarticle
3964 */
3965 public function getParentCategories() {
3966 global $wgContLang;
3967
3968 $data = [];
3969
3970 $titleKey = $this->getArticleID();
3971
3972 if ( $titleKey === 0 ) {
3973 return $data;
3974 }
3975
3976 $dbr = wfGetDB( DB_REPLICA );
3977
3978 $res = $dbr->select(
3979 'categorylinks',
3980 'cl_to',
3981 [ 'cl_from' => $titleKey ],
3982 __METHOD__
3983 );
3984
3985 if ( $res->numRows() > 0 ) {
3986 foreach ( $res as $row ) {
3987 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3988 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3989 }
3990 }
3991 return $data;
3992 }
3993
3994 /**
3995 * Get a tree of parent categories
3996 *
3997 * @param array $children Array with the children in the keys, to check for circular refs
3998 * @return array Tree of parent categories
3999 */
4000 public function getParentCategoryTree( $children = [] ) {
4001 $stack = [];
4002 $parents = $this->getParentCategories();
4003
4004 if ( $parents ) {
4005 foreach ( $parents as $parent => $current ) {
4006 if ( array_key_exists( $parent, $children ) ) {
4007 # Circular reference
4008 $stack[$parent] = [];
4009 } else {
4010 $nt = self::newFromText( $parent );
4011 if ( $nt ) {
4012 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
4013 }
4014 }
4015 }
4016 }
4017
4018 return $stack;
4019 }
4020
4021 /**
4022 * Get an associative array for selecting this title from
4023 * the "page" table
4024 *
4025 * @return array Array suitable for the $where parameter of DB::select()
4026 */
4027 public function pageCond() {
4028 if ( $this->mArticleID > 0 ) {
4029 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4030 return [ 'page_id' => $this->mArticleID ];
4031 } else {
4032 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
4033 }
4034 }
4035
4036 /**
4037 * Get next/previous revision ID relative to another revision ID
4038 * @param int $revId Revision ID. Get the revision that was before this one.
4039 * @param int $flags Title::GAID_FOR_UPDATE
4040 * @param string $dir 'next' or 'prev'
4041 * @return int|bool New revision ID, or false if none exists
4042 */
4043 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4044 $revId = (int)$revId;
4045 if ( $dir === 'next' ) {
4046 $op = '>';
4047 $sort = 'ASC';
4048 } elseif ( $dir === 'prev' ) {
4049 $op = '<';
4050 $sort = 'DESC';
4051 } else {
4052 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4053 }
4054
4055 if ( $flags & self::GAID_FOR_UPDATE ) {
4056 $db = wfGetDB( DB_MASTER );
4057 } else {
4058 $db = wfGetDB( DB_REPLICA, 'contributions' );
4059 }
4060
4061 // Intentionally not caring if the specified revision belongs to this
4062 // page. We only care about the timestamp.
4063 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ );
4064 if ( $ts === false ) {
4065 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ );
4066 if ( $ts === false ) {
4067 // Or should this throw an InvalidArgumentException or something?
4068 return false;
4069 }
4070 }
4071 $ts = $db->addQuotes( $ts );
4072
4073 $revId = $db->selectField( 'revision', 'rev_id',
4074 [
4075 'rev_page' => $this->getArticleID( $flags ),
4076 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4077 ],
4078 __METHOD__,
4079 [
4080 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4081 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4082 ]
4083 );
4084
4085 if ( $revId === false ) {
4086 return false;
4087 } else {
4088 return intval( $revId );
4089 }
4090 }
4091
4092 /**
4093 * Get the revision ID of the previous revision
4094 *
4095 * @param int $revId Revision ID. Get the revision that was before this one.
4096 * @param int $flags Title::GAID_FOR_UPDATE
4097 * @return int|bool Old revision ID, or false if none exists
4098 */
4099 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4100 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4101 }
4102
4103 /**
4104 * Get the revision ID of the next revision
4105 *
4106 * @param int $revId Revision ID. Get the revision that was after this one.
4107 * @param int $flags Title::GAID_FOR_UPDATE
4108 * @return int|bool Next revision ID, or false if none exists
4109 */
4110 public function getNextRevisionID( $revId, $flags = 0 ) {
4111 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4112 }
4113
4114 /**
4115 * Get the first revision of the page
4116 *
4117 * @param int $flags Title::GAID_FOR_UPDATE
4118 * @return Revision|null If page doesn't exist
4119 */
4120 public function getFirstRevision( $flags = 0 ) {
4121 $pageId = $this->getArticleID( $flags );
4122 if ( $pageId ) {
4123 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4124 $row = $db->selectRow( 'revision', Revision::selectFields(),
4125 [ 'rev_page' => $pageId ],
4126 __METHOD__,
4127 [
4128 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4129 'IGNORE INDEX' => 'rev_timestamp', // See T159319
4130 ]
4131 );
4132 if ( $row ) {
4133 return new Revision( $row );
4134 }
4135 }
4136 return null;
4137 }
4138
4139 /**
4140 * Get the oldest revision timestamp of this page
4141 *
4142 * @param int $flags Title::GAID_FOR_UPDATE
4143 * @return string MW timestamp
4144 */
4145 public function getEarliestRevTime( $flags = 0 ) {
4146 $rev = $this->getFirstRevision( $flags );
4147 return $rev ? $rev->getTimestamp() : null;
4148 }
4149
4150 /**
4151 * Check if this is a new page
4152 *
4153 * @return bool
4154 */
4155 public function isNewPage() {
4156 $dbr = wfGetDB( DB_REPLICA );
4157 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4158 }
4159
4160 /**
4161 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4162 *
4163 * @return bool
4164 */
4165 public function isBigDeletion() {
4166 global $wgDeleteRevisionsLimit;
4167
4168 if ( !$wgDeleteRevisionsLimit ) {
4169 return false;
4170 }
4171
4172 if ( $this->mIsBigDeletion === null ) {
4173 $dbr = wfGetDB( DB_REPLICA );
4174
4175 $revCount = $dbr->selectRowCount(
4176 'revision',
4177 '1',
4178 [ 'rev_page' => $this->getArticleID() ],
4179 __METHOD__,
4180 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4181 );
4182
4183 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4184 }
4185
4186 return $this->mIsBigDeletion;
4187 }
4188
4189 /**
4190 * Get the approximate revision count of this page.
4191 *
4192 * @return int
4193 */
4194 public function estimateRevisionCount() {
4195 if ( !$this->exists() ) {
4196 return 0;
4197 }
4198
4199 if ( $this->mEstimateRevisions === null ) {
4200 $dbr = wfGetDB( DB_REPLICA );
4201 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4202 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4203 }
4204
4205 return $this->mEstimateRevisions;
4206 }
4207
4208 /**
4209 * Get the number of revisions between the given revision.
4210 * Used for diffs and other things that really need it.
4211 *
4212 * @param int|Revision $old Old revision or rev ID (first before range)
4213 * @param int|Revision $new New revision or rev ID (first after range)
4214 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4215 * @return int Number of revisions between these revisions.
4216 */
4217 public function countRevisionsBetween( $old, $new, $max = null ) {
4218 if ( !( $old instanceof Revision ) ) {
4219 $old = Revision::newFromTitle( $this, (int)$old );
4220 }
4221 if ( !( $new instanceof Revision ) ) {
4222 $new = Revision::newFromTitle( $this, (int)$new );
4223 }
4224 if ( !$old || !$new ) {
4225 return 0; // nothing to compare
4226 }
4227 $dbr = wfGetDB( DB_REPLICA );
4228 $conds = [
4229 'rev_page' => $this->getArticleID(),
4230 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4231 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4232 ];
4233 if ( $max !== null ) {
4234 return $dbr->selectRowCount( 'revision', '1',
4235 $conds,
4236 __METHOD__,
4237 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4238 );
4239 } else {
4240 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4241 }
4242 }
4243
4244 /**
4245 * Get the authors between the given revisions or revision IDs.
4246 * Used for diffs and other things that really need it.
4247 *
4248 * @since 1.23
4249 *
4250 * @param int|Revision $old Old revision or rev ID (first before range by default)
4251 * @param int|Revision $new New revision or rev ID (first after range by default)
4252 * @param int $limit Maximum number of authors
4253 * @param string|array $options (Optional): Single option, or an array of options:
4254 * 'include_old' Include $old in the range; $new is excluded.
4255 * 'include_new' Include $new in the range; $old is excluded.
4256 * 'include_both' Include both $old and $new in the range.
4257 * Unknown option values are ignored.
4258 * @return array|null Names of revision authors in the range; null if not both revisions exist
4259 */
4260 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4261 if ( !( $old instanceof Revision ) ) {
4262 $old = Revision::newFromTitle( $this, (int)$old );
4263 }
4264 if ( !( $new instanceof Revision ) ) {
4265 $new = Revision::newFromTitle( $this, (int)$new );
4266 }
4267 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4268 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4269 // in the sanity check below?
4270 if ( !$old || !$new ) {
4271 return null; // nothing to compare
4272 }
4273 $authors = [];
4274 $old_cmp = '>';
4275 $new_cmp = '<';
4276 $options = (array)$options;
4277 if ( in_array( 'include_old', $options ) ) {
4278 $old_cmp = '>=';
4279 }
4280 if ( in_array( 'include_new', $options ) ) {
4281 $new_cmp = '<=';
4282 }
4283 if ( in_array( 'include_both', $options ) ) {
4284 $old_cmp = '>=';
4285 $new_cmp = '<=';
4286 }
4287 // No DB query needed if $old and $new are the same or successive revisions:
4288 if ( $old->getId() === $new->getId() ) {
4289 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4290 [] :
4291 [ $old->getUserText( Revision::RAW ) ];
4292 } elseif ( $old->getId() === $new->getParentId() ) {
4293 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4294 $authors[] = $old->getUserText( Revision::RAW );
4295 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4296 $authors[] = $new->getUserText( Revision::RAW );
4297 }
4298 } elseif ( $old_cmp === '>=' ) {
4299 $authors[] = $old->getUserText( Revision::RAW );
4300 } elseif ( $new_cmp === '<=' ) {
4301 $authors[] = $new->getUserText( Revision::RAW );
4302 }
4303 return $authors;
4304 }
4305 $dbr = wfGetDB( DB_REPLICA );
4306 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4307 [
4308 'rev_page' => $this->getArticleID(),
4309 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4310 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4311 ], __METHOD__,
4312 [ 'LIMIT' => $limit + 1 ] // add one so caller knows it was truncated
4313 );
4314 foreach ( $res as $row ) {
4315 $authors[] = $row->rev_user_text;
4316 }
4317 return $authors;
4318 }
4319
4320 /**
4321 * Get the number of authors between the given revisions or revision IDs.
4322 * Used for diffs and other things that really need it.
4323 *
4324 * @param int|Revision $old Old revision or rev ID (first before range by default)
4325 * @param int|Revision $new New revision or rev ID (first after range by default)
4326 * @param int $limit Maximum number of authors
4327 * @param string|array $options (Optional): Single option, or an array of options:
4328 * 'include_old' Include $old in the range; $new is excluded.
4329 * 'include_new' Include $new in the range; $old is excluded.
4330 * 'include_both' Include both $old and $new in the range.
4331 * Unknown option values are ignored.
4332 * @return int Number of revision authors in the range; zero if not both revisions exist
4333 */
4334 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4335 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4336 return $authors ? count( $authors ) : 0;
4337 }
4338
4339 /**
4340 * Compare with another title.
4341 *
4342 * @param Title $title
4343 * @return bool
4344 */
4345 public function equals( Title $title ) {
4346 // Note: === is necessary for proper matching of number-like titles.
4347 return $this->getInterwiki() === $title->getInterwiki()
4348 && $this->getNamespace() == $title->getNamespace()
4349 && $this->getDBkey() === $title->getDBkey();
4350 }
4351
4352 /**
4353 * Check if this title is a subpage of another title
4354 *
4355 * @param Title $title
4356 * @return bool
4357 */
4358 public function isSubpageOf( Title $title ) {
4359 return $this->getInterwiki() === $title->getInterwiki()
4360 && $this->getNamespace() == $title->getNamespace()
4361 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4362 }
4363
4364 /**
4365 * Check if page exists. For historical reasons, this function simply
4366 * checks for the existence of the title in the page table, and will
4367 * thus return false for interwiki links, special pages and the like.
4368 * If you want to know if a title can be meaningfully viewed, you should
4369 * probably call the isKnown() method instead.
4370 *
4371 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4372 * from master/for update
4373 * @return bool
4374 */
4375 public function exists( $flags = 0 ) {
4376 $exists = $this->getArticleID( $flags ) != 0;
4377 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4378 return $exists;
4379 }
4380
4381 /**
4382 * Should links to this title be shown as potentially viewable (i.e. as
4383 * "bluelinks"), even if there's no record by this title in the page
4384 * table?
4385 *
4386 * This function is semi-deprecated for public use, as well as somewhat
4387 * misleadingly named. You probably just want to call isKnown(), which
4388 * calls this function internally.
4389 *
4390 * (ISSUE: Most of these checks are cheap, but the file existence check
4391 * can potentially be quite expensive. Including it here fixes a lot of
4392 * existing code, but we might want to add an optional parameter to skip
4393 * it and any other expensive checks.)
4394 *
4395 * @return bool
4396 */
4397 public function isAlwaysKnown() {
4398 $isKnown = null;
4399
4400 /**
4401 * Allows overriding default behavior for determining if a page exists.
4402 * If $isKnown is kept as null, regular checks happen. If it's
4403 * a boolean, this value is returned by the isKnown method.
4404 *
4405 * @since 1.20
4406 *
4407 * @param Title $title
4408 * @param bool|null $isKnown
4409 */
4410 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4411
4412 if ( !is_null( $isKnown ) ) {
4413 return $isKnown;
4414 }
4415
4416 if ( $this->isExternal() ) {
4417 return true; // any interwiki link might be viewable, for all we know
4418 }
4419
4420 switch ( $this->mNamespace ) {
4421 case NS_MEDIA:
4422 case NS_FILE:
4423 // file exists, possibly in a foreign repo
4424 return (bool)wfFindFile( $this );
4425 case NS_SPECIAL:
4426 // valid special page
4427 return SpecialPageFactory::exists( $this->getDBkey() );
4428 case NS_MAIN:
4429 // selflink, possibly with fragment
4430 return $this->mDbkeyform == '';
4431 case NS_MEDIAWIKI:
4432 // known system message
4433 return $this->hasSourceText() !== false;
4434 default:
4435 return false;
4436 }
4437 }
4438
4439 /**
4440 * Does this title refer to a page that can (or might) be meaningfully
4441 * viewed? In particular, this function may be used to determine if
4442 * links to the title should be rendered as "bluelinks" (as opposed to
4443 * "redlinks" to non-existent pages).
4444 * Adding something else to this function will cause inconsistency
4445 * since LinkHolderArray calls isAlwaysKnown() and does its own
4446 * page existence check.
4447 *
4448 * @return bool
4449 */
4450 public function isKnown() {
4451 return $this->isAlwaysKnown() || $this->exists();
4452 }
4453
4454 /**
4455 * Does this page have source text?
4456 *
4457 * @return bool
4458 */
4459 public function hasSourceText() {
4460 if ( $this->exists() ) {
4461 return true;
4462 }
4463
4464 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4465 // If the page doesn't exist but is a known system message, default
4466 // message content will be displayed, same for language subpages-
4467 // Use always content language to avoid loading hundreds of languages
4468 // to get the link color.
4469 global $wgContLang;
4470 list( $name, ) = MessageCache::singleton()->figureMessage(
4471 $wgContLang->lcfirst( $this->getText() )
4472 );
4473 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4474 return $message->exists();
4475 }
4476
4477 return false;
4478 }
4479
4480 /**
4481 * Get the default message text or false if the message doesn't exist
4482 *
4483 * @return string|bool
4484 */
4485 public function getDefaultMessageText() {
4486 global $wgContLang;
4487
4488 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4489 return false;
4490 }
4491
4492 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4493 $wgContLang->lcfirst( $this->getText() )
4494 );
4495 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4496
4497 if ( $message->exists() ) {
4498 return $message->plain();
4499 } else {
4500 return false;
4501 }
4502 }
4503
4504 /**
4505 * Updates page_touched for this page; called from LinksUpdate.php
4506 *
4507 * @param string $purgeTime [optional] TS_MW timestamp
4508 * @return bool True if the update succeeded
4509 */
4510 public function invalidateCache( $purgeTime = null ) {
4511 if ( wfReadOnly() ) {
4512 return false;
4513 } elseif ( $this->mArticleID === 0 ) {
4514 return true; // avoid gap locking if we know it's not there
4515 }
4516
4517 $dbw = wfGetDB( DB_MASTER );
4518 $dbw->onTransactionPreCommitOrIdle( function () {
4519 ResourceLoaderWikiModule::invalidateModuleCache( $this, null, null, wfWikiID() );
4520 } );
4521
4522 $conds = $this->pageCond();
4523 DeferredUpdates::addUpdate(
4524 new AutoCommitUpdate(
4525 $dbw,
4526 __METHOD__,
4527 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4528 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4529 $dbw->update(
4530 'page',
4531 [ 'page_touched' => $dbTimestamp ],
4532 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4533 $fname
4534 );
4535 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4536 }
4537 ),
4538 DeferredUpdates::PRESEND
4539 );
4540
4541 return true;
4542 }
4543
4544 /**
4545 * Update page_touched timestamps and send CDN purge messages for
4546 * pages linking to this title. May be sent to the job queue depending
4547 * on the number of links. Typically called on create and delete.
4548 */
4549 public function touchLinks() {
4550 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4551 if ( $this->getNamespace() == NS_CATEGORY ) {
4552 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4553 }
4554 }
4555
4556 /**
4557 * Get the last touched timestamp
4558 *
4559 * @param IDatabase $db Optional db
4560 * @return string|false Last-touched timestamp
4561 */
4562 public function getTouched( $db = null ) {
4563 if ( $db === null ) {
4564 $db = wfGetDB( DB_REPLICA );
4565 }
4566 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4567 return $touched;
4568 }
4569
4570 /**
4571 * Get the timestamp when this page was updated since the user last saw it.
4572 *
4573 * @param User $user
4574 * @return string|null
4575 */
4576 public function getNotificationTimestamp( $user = null ) {
4577 global $wgUser;
4578
4579 // Assume current user if none given
4580 if ( !$user ) {
4581 $user = $wgUser;
4582 }
4583 // Check cache first
4584 $uid = $user->getId();
4585 if ( !$uid ) {
4586 return false;
4587 }
4588 // avoid isset here, as it'll return false for null entries
4589 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4590 return $this->mNotificationTimestamp[$uid];
4591 }
4592 // Don't cache too much!
4593 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4594 $this->mNotificationTimestamp = [];
4595 }
4596
4597 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4598 $watchedItem = $store->getWatchedItem( $user, $this );
4599 if ( $watchedItem ) {
4600 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4601 } else {
4602 $this->mNotificationTimestamp[$uid] = false;
4603 }
4604
4605 return $this->mNotificationTimestamp[$uid];
4606 }
4607
4608 /**
4609 * Generate strings used for xml 'id' names in monobook tabs
4610 *
4611 * @param string $prepend Defaults to 'nstab-'
4612 * @return string XML 'id' name
4613 */
4614 public function getNamespaceKey( $prepend = 'nstab-' ) {
4615 global $wgContLang;
4616 // Gets the subject namespace if this title
4617 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4618 // Checks if canonical namespace name exists for namespace
4619 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4620 // Uses canonical namespace name
4621 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4622 } else {
4623 // Uses text of namespace
4624 $namespaceKey = $this->getSubjectNsText();
4625 }
4626 // Makes namespace key lowercase
4627 $namespaceKey = $wgContLang->lc( $namespaceKey );
4628 // Uses main
4629 if ( $namespaceKey == '' ) {
4630 $namespaceKey = 'main';
4631 }
4632 // Changes file to image for backwards compatibility
4633 if ( $namespaceKey == 'file' ) {
4634 $namespaceKey = 'image';
4635 }
4636 return $prepend . $namespaceKey;
4637 }
4638
4639 /**
4640 * Get all extant redirects to this Title
4641 *
4642 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4643 * @return Title[] Array of Title redirects to this title
4644 */
4645 public function getRedirectsHere( $ns = null ) {
4646 $redirs = [];
4647
4648 $dbr = wfGetDB( DB_REPLICA );
4649 $where = [
4650 'rd_namespace' => $this->getNamespace(),
4651 'rd_title' => $this->getDBkey(),
4652 'rd_from = page_id'
4653 ];
4654 if ( $this->isExternal() ) {
4655 $where['rd_interwiki'] = $this->getInterwiki();
4656 } else {
4657 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4658 }
4659 if ( !is_null( $ns ) ) {
4660 $where['page_namespace'] = $ns;
4661 }
4662
4663 $res = $dbr->select(
4664 [ 'redirect', 'page' ],
4665 [ 'page_namespace', 'page_title' ],
4666 $where,
4667 __METHOD__
4668 );
4669
4670 foreach ( $res as $row ) {
4671 $redirs[] = self::newFromRow( $row );
4672 }
4673 return $redirs;
4674 }
4675
4676 /**
4677 * Check if this Title is a valid redirect target
4678 *
4679 * @return bool
4680 */
4681 public function isValidRedirectTarget() {
4682 global $wgInvalidRedirectTargets;
4683
4684 if ( $this->isSpecialPage() ) {
4685 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4686 if ( $this->isSpecial( 'Userlogout' ) ) {
4687 return false;
4688 }
4689
4690 foreach ( $wgInvalidRedirectTargets as $target ) {
4691 if ( $this->isSpecial( $target ) ) {
4692 return false;
4693 }
4694 }
4695 }
4696
4697 return true;
4698 }
4699
4700 /**
4701 * Get a backlink cache object
4702 *
4703 * @return BacklinkCache
4704 */
4705 public function getBacklinkCache() {
4706 return BacklinkCache::get( $this );
4707 }
4708
4709 /**
4710 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4711 *
4712 * @return bool
4713 */
4714 public function canUseNoindex() {
4715 global $wgExemptFromUserRobotsControl;
4716
4717 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4718 ? MWNamespace::getContentNamespaces()
4719 : $wgExemptFromUserRobotsControl;
4720
4721 return !in_array( $this->mNamespace, $bannedNamespaces );
4722 }
4723
4724 /**
4725 * Returns the raw sort key to be used for categories, with the specified
4726 * prefix. This will be fed to Collation::getSortKey() to get a
4727 * binary sortkey that can be used for actual sorting.
4728 *
4729 * @param string $prefix The prefix to be used, specified using
4730 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4731 * prefix.
4732 * @return string
4733 */
4734 public function getCategorySortkey( $prefix = '' ) {
4735 $unprefixed = $this->getText();
4736
4737 // Anything that uses this hook should only depend
4738 // on the Title object passed in, and should probably
4739 // tell the users to run updateCollations.php --force
4740 // in order to re-sort existing category relations.
4741 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4742 if ( $prefix !== '' ) {
4743 # Separate with a line feed, so the unprefixed part is only used as
4744 # a tiebreaker when two pages have the exact same prefix.
4745 # In UCA, tab is the only character that can sort above LF
4746 # so we strip both of them from the original prefix.
4747 $prefix = strtr( $prefix, "\n\t", ' ' );
4748 return "$prefix\n$unprefixed";
4749 }
4750 return $unprefixed;
4751 }
4752
4753 /**
4754 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4755 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4756 * the db, it will return NULL.
4757 *
4758 * @return string|null|bool
4759 */
4760 private function getDbPageLanguageCode() {
4761 global $wgPageLanguageUseDB;
4762
4763 // check, if the page language could be saved in the database, and if so and
4764 // the value is not requested already, lookup the page language using LinkCache
4765 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4766 $linkCache = LinkCache::singleton();
4767 $linkCache->addLinkObj( $this );
4768 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4769 }
4770
4771 return $this->mDbPageLanguage;
4772 }
4773
4774 /**
4775 * Get the language in which the content of this page is written in
4776 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4777 * e.g. $wgLang (such as special pages, which are in the user language).
4778 *
4779 * @since 1.18
4780 * @return Language
4781 */
4782 public function getPageLanguage() {
4783 global $wgLang, $wgLanguageCode;
4784 if ( $this->isSpecialPage() ) {
4785 // special pages are in the user language
4786 return $wgLang;
4787 }
4788
4789 // Checking if DB language is set
4790 $dbPageLanguage = $this->getDbPageLanguageCode();
4791 if ( $dbPageLanguage ) {
4792 return wfGetLangObj( $dbPageLanguage );
4793 }
4794
4795 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4796 // Note that this may depend on user settings, so the cache should
4797 // be only per-request.
4798 // NOTE: ContentHandler::getPageLanguage() may need to load the
4799 // content to determine the page language!
4800 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4801 // tests.
4802 $contentHandler = ContentHandler::getForTitle( $this );
4803 $langObj = $contentHandler->getPageLanguage( $this );
4804 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4805 } else {
4806 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4807 }
4808
4809 return $langObj;
4810 }
4811
4812 /**
4813 * Get the language in which the content of this page is written when
4814 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4815 * e.g. $wgLang (such as special pages, which are in the user language).
4816 *
4817 * @since 1.20
4818 * @return Language
4819 */
4820 public function getPageViewLanguage() {
4821 global $wgLang;
4822
4823 if ( $this->isSpecialPage() ) {
4824 // If the user chooses a variant, the content is actually
4825 // in a language whose code is the variant code.
4826 $variant = $wgLang->getPreferredVariant();
4827 if ( $wgLang->getCode() !== $variant ) {
4828 return Language::factory( $variant );
4829 }
4830
4831 return $wgLang;
4832 }
4833
4834 // Checking if DB language is set
4835 $dbPageLanguage = $this->getDbPageLanguageCode();
4836 if ( $dbPageLanguage ) {
4837 $pageLang = wfGetLangObj( $dbPageLanguage );
4838 $variant = $pageLang->getPreferredVariant();
4839 if ( $pageLang->getCode() !== $variant ) {
4840 $pageLang = Language::factory( $variant );
4841 }
4842
4843 return $pageLang;
4844 }
4845
4846 // @note Can't be cached persistently, depends on user settings.
4847 // @note ContentHandler::getPageViewLanguage() may need to load the
4848 // content to determine the page language!
4849 $contentHandler = ContentHandler::getForTitle( $this );
4850 $pageLang = $contentHandler->getPageViewLanguage( $this );
4851 return $pageLang;
4852 }
4853
4854 /**
4855 * Get a list of rendered edit notices for this page.
4856 *
4857 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4858 * they will already be wrapped in paragraphs.
4859 *
4860 * @since 1.21
4861 * @param int $oldid Revision ID that's being edited
4862 * @return array
4863 */
4864 public function getEditNotices( $oldid = 0 ) {
4865 $notices = [];
4866
4867 // Optional notice for the entire namespace
4868 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4869 $msg = wfMessage( $editnotice_ns );
4870 if ( $msg->exists() ) {
4871 $html = $msg->parseAsBlock();
4872 // Edit notices may have complex logic, but output nothing (T91715)
4873 if ( trim( $html ) !== '' ) {
4874 $notices[$editnotice_ns] = Html::rawElement(
4875 'div',
4876 [ 'class' => [
4877 'mw-editnotice',
4878 'mw-editnotice-namespace',
4879 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4880 ] ],
4881 $html
4882 );
4883 }
4884 }
4885
4886 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4887 // Optional notice for page itself and any parent page
4888 $parts = explode( '/', $this->getDBkey() );
4889 $editnotice_base = $editnotice_ns;
4890 while ( count( $parts ) > 0 ) {
4891 $editnotice_base .= '-' . array_shift( $parts );
4892 $msg = wfMessage( $editnotice_base );
4893 if ( $msg->exists() ) {
4894 $html = $msg->parseAsBlock();
4895 if ( trim( $html ) !== '' ) {
4896 $notices[$editnotice_base] = Html::rawElement(
4897 'div',
4898 [ 'class' => [
4899 'mw-editnotice',
4900 'mw-editnotice-base',
4901 Sanitizer::escapeClass( "mw-$editnotice_base" )
4902 ] ],
4903 $html
4904 );
4905 }
4906 }
4907 }
4908 } else {
4909 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4910 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4911 $msg = wfMessage( $editnoticeText );
4912 if ( $msg->exists() ) {
4913 $html = $msg->parseAsBlock();
4914 if ( trim( $html ) !== '' ) {
4915 $notices[$editnoticeText] = Html::rawElement(
4916 'div',
4917 [ 'class' => [
4918 'mw-editnotice',
4919 'mw-editnotice-page',
4920 Sanitizer::escapeClass( "mw-$editnoticeText" )
4921 ] ],
4922 $html
4923 );
4924 }
4925 }
4926 }
4927
4928 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4929 return $notices;
4930 }
4931
4932 /**
4933 * @return array
4934 */
4935 public function __sleep() {
4936 return [
4937 'mNamespace',
4938 'mDbkeyform',
4939 'mFragment',
4940 'mInterwiki',
4941 'mLocalInterwiki',
4942 'mUserCaseDBKey',
4943 'mDefaultNamespace',
4944 ];
4945 }
4946
4947 public function __wakeup() {
4948 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4949 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4950 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4951 }
4952
4953 }