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