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