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