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