Debian Codegraph @

includes/title/Title.php

raw symbols SCIP
1 <?php
2 /**
3 * Representation of a title within MediaWiki.
4 *
5 * See Title.md
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 namespace MediaWiki\Title;
26
27 use HTMLCacheUpdateJob;
28 use InvalidArgumentException;
29 use MapCacheLRU;
30 use MediaWiki\Cache\LinkCache;
31 use MediaWiki\Context\RequestContext;
32 use MediaWiki\DAO\WikiAwareEntityTrait;
33 use MediaWiki\Deferred\AutoCommitUpdate;
34 use MediaWiki\Deferred\DeferredUpdates;
35 use MediaWiki\HookContainer\HookRunner;
36 use MediaWiki\Html\Html;
37 use MediaWiki\Interwiki\InterwikiLookup;
38 use MediaWiki\Language\ILanguageConverter;
39 use MediaWiki\Language\Language;
40 use MediaWiki\Linker\LinkTarget;
41 use MediaWiki\MainConfigNames;
42 use MediaWiki\MediaWikiServices;
43 use MediaWiki\Message\Message;
44 use MediaWiki\Page\ExistingPageRecord;
45 use MediaWiki\Page\PageIdentity;
46 use MediaWiki\Page\PageIdentityValue;
47 use MediaWiki\Page\PageReference;
48 use MediaWiki\Page\PageStoreRecord;
49 use MediaWiki\Page\ProperPageIdentity;
50 use MediaWiki\Parser\Sanitizer;
51 use MediaWiki\Request\PathRouter;
52 use MediaWiki\ResourceLoader\WikiModule;
53 use MediaWiki\SpecialPage\SpecialPage;
54 use MediaWiki\Utils\MWTimestamp;
55 use MessageLocalizer;
56 use MWException;
57 use RuntimeException;
58 use stdClass;
59 use Stringable;
60 use Wikimedia\Assert\Assert;
61 use Wikimedia\Assert\PreconditionException;
62 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
63 use Wikimedia\Parsoid\Core\LinkTargetTrait;
64 use Wikimedia\Rdbms\DBAccessObjectUtils;
65 use Wikimedia\Rdbms\IConnectionProvider;
66 use Wikimedia\Rdbms\IDatabase;
67 use Wikimedia\Rdbms\IDBAccessObject;
68 use WikiPage;
69
70 /**
71 * Represents a title within MediaWiki.
72 * Optionally may contain an interwiki designation or namespace.
73 * @note This class can fetch various kinds of data from the database;
74 * however, it does so inefficiently.
75 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
76 * and does not rely on global state or the database.
77 */
78 class Title implements Stringable, LinkTarget, PageIdentity {
79 use WikiAwareEntityTrait;
80 use LinkTargetTrait;
81
82 /** @var MapCacheLRU|null */
83 private static $titleCache = null;
84
85 /**
86 * Cached instance of the main page title, to speed up isMainPage() checks.
87 * @var Title|null
88 */
89 private static ?Title $cachedMainPage = null;
90
91 /**
92 * Title::newFromText maintains a cache to avoid expensive re-normalization of
93 * commonly used titles. On a batch operation this can become a memory leak
94 * if not bounded.
95 */
96 private const CACHE_MAX = 1000;
97
98 /**
99 * Flag for use with factory methods like newFromLinkTarget() that have
100 * a $forceClone parameter. If set, the method must return a new instance.
101 * Without this flag, some factory methods may return existing instances.as
102 *
103 * @since 1.33
104 */
105 public const NEW_CLONE = 'clone';
106
107 /** @var string Text form (spaces not underscores) of the main part */
108 private $mTextform = '';
109
110 /** @var string URL-encoded form of the main part */
111 private $mUrlform = '';
112
113 /** @var string Main part with underscores */
114 private $mDbkeyform = '';
115
116 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
117 private $mNamespace = NS_MAIN;
118
119 /** @var string Interwiki prefix */
120 private $mInterwiki = '';
121
122 /** @var bool Was this Title created from a string with a local interwiki prefix? */
123 private $mLocalInterwiki = false;
124
125 /** @var string Title fragment (i.e. the bit after the #) */
126 private $mFragment = '';
127
128 /***************************************************************************/
129 // region Private member variables
130 /** @name Private member variables
131 * Please use the accessor functions instead.
132 * @internal
133 * @{
134 */
135
136 /** @var int Article ID, fetched from the link cache on demand */
137 public $mArticleID = -1;
138
139 /** @var int|false ID of most recent revision */
140 protected $mLatestID = false;
141
142 /**
143 * @var string|false ID of the page's content model, i.e. one of the
144 * CONTENT_MODEL_XXX constants
145 */
146 private $mContentModel = false;
147
148 /**
149 * @var bool If a content model was forced via setContentModel()
150 * this will be true to avoid having other code paths reset it
151 */
152 private $mForcedContentModel = false;
153
154 /** @var int|null Estimated number of revisions; null of not loaded */
155 private $mEstimateRevisions;
156
157 /**
158 * Text form including namespace/interwiki, initialised on demand
159 *
160 * Only public to share cache with TitleFormatter
161 *
162 * @internal
163 * @var string|null
164 */
165 public $prefixedText = null;
166
167 /**
168 * Namespace to assume when no namespace was passed to factory methods.
169 * This must be NS_MAIN, as it's hardcoded in several places. See T2696.
170 * Used primarily for {{transclusion}} tags.
171 */
172 private const DEFAULT_NAMESPACE = NS_MAIN;
173
174 /** @var int The page length, 0 for special pages */
175 protected $mLength = -1;
176
177 /** @var null|bool Is the article at this title a redirect? */
178 public $mRedirect = null;
179
180 /** @var bool Whether a page has any subpages */
181 private $mHasSubpages;
182
183 /** @var array|null The (string) language code of the page's language and content code. */
184 private $mPageLanguage;
185
186 /** @var string|false|null The page language code from the database, null if not saved in
187 * the database or false if not loaded, yet.
188 */
189 private $mDbPageLanguage = false;
190
191 /** @var TitleValue|null */
192 private $mTitleValue = null;
193
194 /** @var bool|null Would deleting this page be a big deletion? */
195 private $mIsBigDeletion = null;
196
197 /** @var bool|null Is the title known to be valid? */
198 private $mIsValid = null;
199
200 /** @var string|null The key of this instance in the internal Title instance cache */
201 private $mInstanceCacheKey = null;
202
203 // endregion -- end of private member variables
204 /** @} */
205 /***************************************************************************/
206
207 /**
208 * Shorthand for getting a Language Converter for specific language
209 * @param Language $language Language of converter
210 * @return ILanguageConverter
211 */
212 private function getLanguageConverter( $language ): ILanguageConverter {
213 return MediaWikiServices::getInstance()->getLanguageConverterFactory()
214 ->getLanguageConverter( $language );
215 }
216
217 /**
218 * Shorthand for getting a Language Converter for page's language
219 * @return ILanguageConverter
220 */
221 private function getPageLanguageConverter(): ILanguageConverter {
222 return $this->getLanguageConverter( $this->getPageLanguage() );
223 }
224
225 /**
226 * Shorthand for getting a database connection provider
227 * @return IConnectionProvider
228 */
229 private function getDbProvider(): IConnectionProvider {
230 return MediaWikiServices::getInstance()->getConnectionProvider();
231 }
232
233 /**
234 * B/C kludge: provide a TitleParser for use by Title.
235 * Ideally, Title would have no methods that need this.
236 * Avoid usage of this singleton by using TitleValue
237 * and the associated services when possible.
238 *
239 * @return TitleFormatter
240 */
241 private static function getTitleFormatter() {
242 return MediaWikiServices::getInstance()->getTitleFormatter();
243 }
244
245 /**
246 * B/C kludge: provide an InterwikiLookup for use by Title.
247 * Ideally, Title would have no methods that need this.
248 * Avoid usage of this singleton by using TitleValue
249 * and the associated services when possible.
250 *
251 * @return InterwikiLookup
252 */
253 private static function getInterwikiLookup() {
254 return MediaWikiServices::getInstance()->getInterwikiLookup();
255 }
256
257 private function __construct() {
258 }
259
260 /**
261 * Create a new Title from a prefixed DB key
262 *
263 * @param string $key The database key, which has underscores
264 * instead of spaces, possibly including namespace and
265 * interwiki prefixes
266 * @return Title|null Title, or null on an error
267 */
268 public static function newFromDBkey( $key ) {
269 $t = new self();
270
271 try {
272 $t->secureAndSplit( $key );
273 return $t;
274 } catch ( MalformedTitleException $ex ) {
275 return null;
276 }
277 }
278
279 /**
280 * Returns a Title given a LinkTarget.
281 * If the given LinkTarget is already a Title instance, that instance is returned,
282 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
283 * is already a Title instance, that instance is copied using the clone operator.
284 *
285 * @since 1.27
286 * @param ParsoidLinkTarget $linkTarget Assumed to be safe.
287 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
288 * @return Title
289 */
290 public static function newFromLinkTarget( ParsoidLinkTarget $linkTarget, $forceClone = '' ) {
291 if ( $linkTarget instanceof Title ) {
292 // Special case if it's already a Title object
293 if ( $forceClone === self::NEW_CLONE ) {
294 return clone $linkTarget;
295 } else {
296 return $linkTarget;
297 }
298 }
299 return self::makeTitle(
300 $linkTarget->getNamespace(),
301 $linkTarget->getText(),
302 $linkTarget->getFragment(),
303 $linkTarget->getInterwiki()
304 );
305 }
306
307 /**
308 * Same as newFromLinkTarget(), but if passed null, returns null.
309 *
310 * @since 1.34
311 * @param ParsoidLinkTarget|null $linkTarget Assumed to be safe (if not null).
312 * @return Title|null
313 */
314 public static function castFromLinkTarget( ?ParsoidLinkTarget $linkTarget ) {
315 if ( !$linkTarget ) {
316 return null;
317 }
318 return self::newFromLinkTarget( $linkTarget );
319 }
320
321 /**
322 * Return a Title for a given PageIdentity. If $pageIdentity is a Title,
323 * that Title is returned unchanged.
324 *
325 * @since 1.41
326 * @param PageIdentity $pageIdentity
327 * @return Title
328 */
329 public static function newFromPageIdentity( PageIdentity $pageIdentity ): Title {
330 return self::newFromPageReference( $pageIdentity );
331 }
332
333 /**
334 * Same as newFromPageIdentity(), but if passed null, returns null.
335 *
336 * @since 1.36
337 * @param PageIdentity|null $pageIdentity
338 * @return Title|null
339 */
340 public static function castFromPageIdentity( ?PageIdentity $pageIdentity ): ?Title {
341 return self::castFromPageReference( $pageIdentity );
342 }
343
344 /**
345 * Return a Title for a given Reference. If $pageReference is a Title,
346 * that Title is returned unchanged.
347 *
348 * @since 1.41
349 * @param PageReference $pageReference
350 * @return Title
351 */
352 public static function newFromPageReference( PageReference $pageReference ): Title {
353 if ( $pageReference instanceof Title ) {
354 return $pageReference;
355 }
356
357 $pageReference->assertWiki( self::LOCAL );
358 $title = self::makeTitle( $pageReference->getNamespace(), $pageReference->getDBkey() );
359
360 if ( $pageReference instanceof PageIdentity ) {
361 $title->mArticleID = $pageReference->getId();
362 }
363 return $title;
364 }
365
366 /**
367 * Same as newFromPageReference(), but if passed null, returns null.
368 *
369 * @since 1.37
370 * @param PageReference|null $pageReference
371 * @return Title|null
372 */
373 public static function castFromPageReference( ?PageReference $pageReference ): ?Title {
374 if ( !$pageReference ) {
375 return null;
376 }
377 return self::newFromPageReference( $pageReference );
378 }
379
380 /**
381 * Create a new Title from text, such as what one would find in a link.
382 * Decodes any HTML entities in the text.
383 * Titles returned by this method are guaranteed to be valid.
384 * Call canExist() to check if the Title represents an editable page.
385 *
386 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
387 * It may instead be a cached instance created previously, with references to it remaining
388 * elsewhere.
389 *
390 * @param string|int|null $text The link text; spaces, prefixes, and an
391 * initial ':' indicating the main namespace are accepted.
392 * @param int $defaultNamespace The namespace to use if none is specified
393 * by a prefix. If you want to force a specific namespace even if
394 * $text might begin with a namespace prefix, use makeTitle() or
395 * makeTitleSafe().
396 * @return Title|null Title or null if the Title could not be parsed because
397 * it is invalid.
398 */
399 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
400 // DWIM: Integers can be passed in here when page titles are used as array keys.
401 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
402 throw new InvalidArgumentException( '$text must be a string.' );
403 }
404 if ( $text === null || $text === '' ) {
405 return null;
406 }
407
408 try {
409 return self::newFromTextThrow( (string)$text, (int)$defaultNamespace );
410 } catch ( MalformedTitleException $ex ) {
411 return null;
412 }
413 }
414
415 /**
416 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
417 * rather than returning null.
418 *
419 * Titles returned by this method are guaranteed to be valid.
420 * Call canExist() to check if the Title represents an editable page.
421 *
422 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
423 * It may instead be a cached instance created previously, with references to it remaining
424 * elsewhere.
425 *
426 * @see Title::newFromText
427 *
428 * @since 1.25
429 * @param string $text Title text to check
430 * @param int $defaultNamespace
431 * @throws MalformedTitleException If the title is invalid.
432 * @return Title
433 */
434 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
435 if ( is_object( $text ) ) {
436 throw new InvalidArgumentException( '$text must be a string, given an object' );
437 } elseif ( $text === null ) {
438 // Legacy code relies on MalformedTitleException being thrown in this case
439 // TODO: fix(happens when URL with no title in it is parsed).
440 throw new MalformedTitleException( 'title-invalid-empty' );
441 }
442
443 $titleCache = self::getTitleCache();
444
445 // Wiki pages often contain multiple links to the same page.
446 // Title normalization and parsing can become expensive on pages with many
447 // links, so we can save a little time by caching them.
448 if ( $defaultNamespace === NS_MAIN ) {
449 $t = $titleCache->get( $text );
450 if ( $t ) {
451 return $t;
452 }
453 }
454
455 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
456 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
457
458 $t = new Title();
459 $dbKeyForm = strtr( $filteredText, ' ', '_' );
460
461 $t->secureAndSplit( $dbKeyForm, (int)$defaultNamespace );
462 if ( $defaultNamespace === NS_MAIN ) {
463 $t->mInstanceCacheKey = $text;
464 $titleCache->set( $text, $t );
465 }
466 return $t;
467 }
468
469 /**
470 * Removes this instance from the internal title cache, so it can be modified in-place
471 * without polluting the cache (see T281337).
472 */
473 private function uncache() {
474 if ( $this->mInstanceCacheKey !== null ) {
475 $titleCache = self::getTitleCache();
476 $titleCache->clear( $this->mInstanceCacheKey );
477 $this->mInstanceCacheKey = null;
478 }
479 }
480
481 /**
482 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
483 *
484 * Example of wrong and broken code:
485 * $title = Title::newFromURL( $request->getText( 'title' ) );
486 *
487 * Example of right code:
488 * $title = Title::newFromText( $request->getText( 'title' ) );
489 *
490 * Create a new Title from URL-encoded text. Ensures that
491 * the given title's length does not exceed the maximum.
492 *
493 * @param string $url The title, as might be taken from a URL
494 * @return Title|null The new object, or null on an error
495 */
496 public static function newFromURL( $url ) {
497 $t = new Title();
498
499 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
500 # but some URLs used it as a space replacement and they still come
501 # from some external search tools.
502 if ( !str_contains( self::legalChars(), '+' ) ) {
503 $url = strtr( $url, '+', ' ' );
504 }
505
506 $dbKeyForm = strtr( $url, ' ', '_' );
507
508 try {
509 $t->secureAndSplit( $dbKeyForm );
510 return $t;
511 } catch ( MalformedTitleException $ex ) {
512 return null;
513 }
514 }
515
516 /**
517 * @return MapCacheLRU
518 */
519 private static function getTitleCache() {
520 if ( self::$titleCache === null ) {
521 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
522 }
523 return self::$titleCache;
524 }
525
526 /**
527 * Create a new Title from an article ID
528 *
529 * @param int $id The page_id corresponding to the Title to create
530 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
531 * @return Title|null The new object, or null on an error
532 */
533 public static function newFromID( $id, $flags = 0 ) {
534 $pageStore = MediaWikiServices::getInstance()->getPageStore();
535 $dbr = DBAccessObjectUtils::getDBFromRecency(
536 MediaWikiServices::getInstance()->getConnectionProvider(),
537 $flags
538 );
539 $row = $dbr->newSelectQueryBuilder()
540 ->select( $pageStore->getSelectFields() )
541 ->from( 'page' )
542 ->where( [ 'page_id' => $id ] )
543 ->recency( $flags )
544 ->caller( __METHOD__ )->fetchRow();
545 if ( $row !== false ) {
546 $title = self::newFromRow( $row );
547 } else {
548 $title = null;
549 }
550
551 return $title;
552 }
553
554 /**
555 * Make a Title object from a DB row
556 *
557 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
558 * @return Title
559 */
560 public static function newFromRow( $row ) {
561 $t = self::makeTitle( $row->page_namespace, $row->page_title );
562 $t->loadFromRow( $row );
563 return $t;
564 }
565
566 /**
567 * Load Title object fields from a DB row.
568 * If false is given, the title will be treated as non-existing.
569 *
570 * @param stdClass|false $row Database row
571 */
572 public function loadFromRow( $row ) {
573 if ( $row ) { // page found
574 if ( isset( $row->page_id ) ) {
575 $this->mArticleID = (int)$row->page_id;
576 }
577 if ( isset( $row->page_len ) ) {
578 $this->mLength = (int)$row->page_len;
579 }
580 if ( isset( $row->page_is_redirect ) ) {
581 $this->mRedirect = (bool)$row->page_is_redirect;
582 }
583 if ( isset( $row->page_latest ) ) {
584 $this->mLatestID = (int)$row->page_latest;
585 }
586 if ( isset( $row->page_content_model ) ) {
587 $this->lazyFillContentModel( $row->page_content_model );
588 } else {
589 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
590 }
591 if ( isset( $row->page_lang ) ) {
592 $this->mDbPageLanguage = (string)$row->page_lang;
593 }
594 } else { // page not found
595 $this->mArticleID = 0;
596 $this->mLength = 0;
597 $this->mRedirect = false;
598 $this->mLatestID = 0;
599 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
600 }
601 }
602
603 /**
604 * Create a new Title from a namespace index and a DB key.
605 *
606 * It's assumed that $ns and $title are safe, for instance when
607 * they came directly from the database or a special page name,
608 * not from user input.
609 *
610 * No validation is applied. For convenience, spaces are normalized
611 * to underscores, so that e.g. user_text fields can be used directly.
612 *
613 * @note This method may return Title objects that are "invalid"
614 * according to the isValid() method. This is usually caused by
615 * configuration changes: e.g. a namespace that was once defined is
616 * no longer configured, or a character that was once allowed in
617 * titles is now forbidden.
618 *
619 * @param int $ns The namespace of the article
620 * @param string $title The unprefixed database key form
621 * @param string $fragment The link fragment (after the "#")
622 * @param string $interwiki The interwiki prefix
623 * @return Title The new object
624 */
625 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
626 $t = new Title();
627 $t->mInterwiki = $interwiki;
628 $t->mFragment = self::normalizeFragment( $fragment );
629 $t->mNamespace = $ns = (int)$ns;
630 $t->mDbkeyform = strtr( $title, ' ', '_' );
631 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
632 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
633 $t->mTextform = strtr( $title, '_', ' ' );
634 return $t;
635 }
636
637 /**
638 * Create a new Title from a namespace index and a DB key.
639 * The parameters will be checked for validity, which is a bit slower
640 * than makeTitle() but safer for user-provided data.
641 *
642 * The Title object returned by this method is guaranteed to be valid.
643 * Call canExist() to check if the Title represents an editable page.
644 *
645 * @param int $ns The namespace of the article
646 * @param string $title Database key form
647 * @param string $fragment The link fragment (after the "#")
648 * @param string $interwiki Interwiki prefix
649 * @return Title|null The new object, or null on an error
650 */
651 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
652 // NOTE: ideally, this would just call makeTitle() and then isValid(),
653 // but presently, that means more overhead on a potential performance hotspot.
654
655 if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
656 return null;
657 }
658
659 $t = new Title();
660 $dbKeyForm = self::makeName( $ns, $title, $fragment, $interwiki, true );
661
662 try {
663 $t->secureAndSplit( $dbKeyForm );
664 return $t;
665 } catch ( MalformedTitleException $ex ) {
666 return null;
667 }
668 }
669
670 /**
671 * Create a new Title for the Main Page
672 *
673 * This uses the 'mainpage' interface message, which could be specified in
674 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
675 * will use the user language, which would involve initialising the session
676 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
677 * be sure to pass in a MessageLocalizer (such as your own RequestContext or
678 * ResourceLoader Context) to prevent an error.
679 *
680 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
681 * It may instead be a cached instance created previously, with references to it remaining
682 * elsewhere.
683 *
684 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
685 * @return Title
686 */
687 public static function newMainPage( ?MessageLocalizer $localizer = null ) {
688 static $recursionGuard = false;
689
690 $title = null;
691
692 if ( !$recursionGuard ) {
693 $msg = $localizer ? $localizer->msg( 'mainpage' ) : wfMessage( 'mainpage' );
694
695 $recursionGuard = true;
696 $title = self::newFromText( $msg->inContentLanguage()->text() );
697 $recursionGuard = false;
698 }
699
700 // Every page renders at least one link to the Main Page (e.g. sidebar).
701 // Don't produce fatal errors that would make the wiki inaccessible, and hard to fix the
702 // invalid message.
703 //
704 // Fallback scenarios:
705 // * Recursion guard
706 // If the message contains a bare local interwiki (T297571), then
707 // Title::newFromText via MediaWikiTitleCodec::splitTitleString can get back here.
708 // * Invalid title
709 // If the 'mainpage' message contains something that is invalid, Title::newFromText
710 // will return null.
711
712 return $title ?? self::makeTitle( NS_MAIN, 'Main Page' );
713 }
714
715 /**
716 * Get a regex character class describing the legal characters in a link
717 *
718 * @return string The list of characters, not delimited
719 */
720 public static function legalChars() {
721 global $wgLegalTitleChars;
722 return $wgLegalTitleChars;
723 }
724
725 /**
726 * Utility method for converting a character sequence from bytes to Unicode.
727 *
728 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
729 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
730 *
731 * @param string $byteClass
732 * @return string
733 */
734 public static function convertByteClassToUnicodeClass( $byteClass ) {
735 $length = strlen( $byteClass );
736 // Input token queue
737 $x0 = $x1 = $x2 = '';
738 // Decoded queue
739 $d0 = $d1 = '';
740 // Decoded integer codepoints
741 $ord0 = $ord1 = $ord2 = 0;
742 // Re-encoded queue
743 $r0 = $r1 = $r2 = '';
744 // Output
745 $out = '';
746 // Flags
747 $allowUnicode = false;
748 for ( $pos = 0; $pos < $length; $pos++ ) {
749 // Shift the queues down
750 $x2 = $x1;
751 $x1 = $x0;
752 $d1 = $d0;
753 $ord2 = $ord1;
754 $ord1 = $ord0;
755 $r2 = $r1;
756 $r1 = $r0;
757 // Load the current input token and decoded values
758 $inChar = $byteClass[$pos];
759 if ( $inChar === '\\' ) {
760 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
761 $x0 = $inChar . $m[0];
762 $d0 = chr( hexdec( $m[1] ) );
763 $pos += strlen( $m[0] );
764 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
765 $x0 = $inChar . $m[0];
766 $d0 = chr( octdec( $m[0] ) );
767 $pos += strlen( $m[0] );
768 } elseif ( $pos + 1 >= $length ) {
769 $x0 = $d0 = '\\';
770 } else {
771 $d0 = $byteClass[$pos + 1];
772 $x0 = $inChar . $d0;
773 $pos++;
774 }
775 } else {
776 $x0 = $d0 = $inChar;
777 }
778 $ord0 = ord( $d0 );
779 // Load the current re-encoded value
780 if ( $ord0 < 32 || $ord0 == 0x7f ) {
781 $r0 = sprintf( '\x%02x', $ord0 );
782 } elseif ( $ord0 >= 0x80 ) {
783 // Allow unicode if a single high-bit character appears
784 $r0 = sprintf( '\x%02x', $ord0 );
785 $allowUnicode = true;
786 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
787 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
788 $r0 = '\\' . $d0;
789 } else {
790 $r0 = $d0;
791 }
792 // Do the output
793 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
794 // Range
795 if ( $ord2 > $ord0 ) {
796 // Empty range
797 } elseif ( $ord0 >= 0x80 ) {
798 // Unicode range
799 $allowUnicode = true;
800 if ( $ord2 < 0x80 ) {
801 // Keep the non-unicode section of the range
802 $out .= "$r2-\\x7F";
803 }
804 } else {
805 // Normal range
806 $out .= "$r2-$r0";
807 }
808 // Reset state to the initial value
809 // @phan-suppress-next-line PhanPluginRedundantAssignmentInLoop
810 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
811 } elseif ( $ord2 < 0x80 ) {
812 // ASCII character
813 $out .= $r2;
814 }
815 }
816 // @phan-suppress-next-line PhanSuspiciousValueComparison
817 if ( $ord1 < 0x80 ) {
818 $out .= $r1;
819 }
820 if ( $ord0 < 0x80 ) {
821 $out .= $r0;
822 }
823 if ( $allowUnicode ) {
824 $out .= '\u0080-\uFFFF';
825 }
826 return $out;
827 }
828
829 /**
830 * Make a prefixed DB key from a DB key and a namespace index
831 *
832 * @param int $ns Numerical representation of the namespace
833 * @param string $title The DB key form the title
834 * @param string $fragment The link fragment (after the "#")
835 * @param string $interwiki The interwiki prefix
836 * @param bool $canonicalNamespace If true, use the canonical name for
837 * $ns instead of the localized version.
838 * @return string The prefixed form of the title
839 */
840 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
841 $canonicalNamespace = false
842 ) {
843 if ( $canonicalNamespace ) {
844 $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
845 getCanonicalName( $ns );
846 } else {
847 $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
848 }
849 if ( $namespace === false ) {
850 // See T165149. Awkward, but better than erroneously linking to the main namespace.
851 $namespace = self::makeName( NS_SPECIAL, "Badtitle/NS$ns", '', '', $canonicalNamespace );
852 }
853 $name = $namespace === '' ? $title : "$namespace:$title";
854 if ( strval( $interwiki ) != '' ) {
855 $name = "$interwiki:$name";
856 }
857 if ( strval( $fragment ) != '' ) {
858 $name .= '#' . $fragment;
859 }
860 return $name;
861 }
862
863 /**
864 * Callback for usort() to do title sorts by (namespace, title)
865 *
866 * @param LinkTarget|PageReference $a
867 * @param LinkTarget|PageReference $b
868 *
869 * @return int Result of string comparison, or namespace comparison
870 */
871 public static function compare( $a, $b ) {
872 return $a->getNamespace() <=> $b->getNamespace()
873 ?: strcmp( $a->getDBkey(), $b->getDBkey() );
874 }
875
876 /**
877 * Returns true if the title is a valid link target, and that it has been
878 * properly normalized. This method checks that the title is syntactically valid,
879 * and that the namespace it refers to exists.
880 *
881 * Titles constructed using newFromText() or makeTitleSafe() are always valid.
882 *
883 * @note Code that wants to check whether the title can represent a page that can
884 * be created and edited should use canExist() instead. Examples of valid titles
885 * that cannot "exist" are Special pages, interwiki links, and on-page section links
886 * that only have the fragment part set.
887 *
888 * @see canExist()
889 *
890 * @return bool
891 */
892 public function isValid() {
893 if ( $this->mIsValid !== null ) {
894 return $this->mIsValid;
895 }
896
897 try {
898 // Optimization: Avoid Title::getFullText because that involves GenderCache
899 // and (unbatched) database queries. For validation, canonical namespace suffices.
900 $text = self::makeName( $this->mNamespace, $this->mDbkeyform, $this->mFragment, $this->mInterwiki, true );
901 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
902
903 '@phan-var MediaWikiTitleCodec $titleCodec';
904 $parts = $titleCodec->splitTitleString( $text, $this->mNamespace );
905
906 // Check that nothing changed!
907 // This ensures that $text was already properly normalized.
908 if ( $parts['fragment'] !== $this->mFragment
909 || $parts['interwiki'] !== $this->mInterwiki
910 || $parts['local_interwiki'] !== $this->mLocalInterwiki
911 || $parts['namespace'] !== $this->mNamespace
912 || $parts['dbkey'] !== $this->mDbkeyform
913 ) {
914 $this->mIsValid = false;
915 return $this->mIsValid;
916 }
917 } catch ( MalformedTitleException $ex ) {
918 $this->mIsValid = false;
919 return $this->mIsValid;
920 }
921
922 $this->mIsValid = true;
923 return $this->mIsValid;
924 }
925
926 /**
927 * Determine whether the object refers to a page within
928 * this project (either this wiki or a wiki with a local
929 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
930 *
931 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
932 */
933 public function isLocal() {
934 if ( $this->isExternal() ) {
935 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
936 if ( $iw ) {
937 return $iw->isLocal();
938 }
939 }
940 return true;
941 }
942
943 /**
944 * Get the interwiki prefix
945 *
946 * Use Title::isExternal to check if a interwiki is set
947 *
948 * @return string Interwiki prefix
949 */
950 public function getInterwiki(): string {
951 return $this->mInterwiki;
952 }
953
954 /**
955 * Was this a local interwiki link?
956 *
957 * @return bool
958 */
959 public function wasLocalInterwiki() {
960 return $this->mLocalInterwiki;
961 }
962
963 /**
964 * Determine whether the object refers to a page within
965 * this project and is transcludable.
966 *
967 * @return bool True if this is transcludable
968 */
969 public function isTrans() {
970 if ( !$this->isExternal() ) {
971 return false;
972 }
973
974 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
975 }
976
977 /**
978 * Returns the DB name of the distant wiki which owns the object.
979 *
980 * @return string|false The DB name
981 */
982 public function getTransWikiID() {
983 if ( !$this->isExternal() ) {
984 return false;
985 }
986
987 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
988 }
989
990 /**
991 * Get a TitleValue object representing this Title.
992 *
993 * @note Not all valid Titles have a corresponding valid TitleValue
994 * (e.g. TitleValues cannot represent page-local links that have a
995 * fragment but no title text).
996 *
997 * @return TitleValue|null
998 */
999 public function getTitleValue() {
1000 if ( $this->mTitleValue === null ) {
1001 try {
1002 $this->mTitleValue = new TitleValue(
1003 $this->mNamespace,
1004 $this->mDbkeyform,
1005 $this->mFragment,
1006 $this->mInterwiki
1007 );
1008 } catch ( InvalidArgumentException $ex ) {
1009 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
1010 $this->getPrefixedText() . ']]: ' . $ex->getMessage() );
1011 }
1012 }
1013
1014 return $this->mTitleValue;
1015 }
1016
1017 /**
1018 * Get the text form (spaces not underscores) of the main part
1019 *
1020 * @return string Main part of the title
1021 */
1022 public function getText(): string {
1023 return $this->mTextform;
1024 }
1025
1026 /**
1027 * Get the URL-encoded form of the main part
1028 *
1029 * @return string Main part of the title, URL-encoded
1030 */
1031 public function getPartialURL() {
1032 return $this->mUrlform;
1033 }
1034
1035 /**
1036 * Get the main part with underscores
1037 *
1038 * @return string Main part of the title, with underscores
1039 */
1040 public function getDBkey(): string {
1041 return $this->mDbkeyform;
1042 }
1043
1044 /**
1045 * Get the namespace index, i.e. one of the NS_xxxx constants.
1046 *
1047 * @return int Namespace index
1048 */
1049 public function getNamespace(): int {
1050 return $this->mNamespace;
1051 }
1052
1053 /**
1054 * @param int $flags
1055 *
1056 * @return bool Whether $flags indicates that the latest information should be
1057 * read from the primary database, bypassing caches.
1058 */
1059 private function shouldReadLatest( int $flags ) {
1060 return ( $flags & ( IDBAccessObject::READ_LATEST ) ) > 0;
1061 }
1062
1063 /**
1064 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1065 *
1066 * @todo Deprecate this in favor of SlotRecord::getModel()
1067 *
1068 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
1069 * @return string Content model id
1070 */
1071 public function getContentModel( $flags = 0 ) {
1072 if ( $this->mForcedContentModel ) {
1073 if ( !$this->mContentModel ) {
1074 throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
1075 }
1076 // Content model is locked to the currently loaded one
1077 return $this->mContentModel;
1078 }
1079
1080 if ( $this->shouldReadLatest( $flags ) || !$this->mContentModel ) {
1081 $this->lazyFillContentModel( $this->getFieldFromPageStore( 'page_content_model', $flags ) );
1082 }
1083
1084 if ( !$this->mContentModel ) {
1085 $slotRoleregistry = MediaWikiServices::getInstance()->getSlotRoleRegistry();
1086 $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
1087 $this->lazyFillContentModel( $mainSlotHandler->getDefaultModel( $this ) );
1088 }
1089
1090 return $this->mContentModel;
1091 }
1092
1093 /**
1094 * Convenience method for checking a title's content model name
1095 *
1096 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1097 * @return bool True if $this->getContentModel() == $id
1098 */
1099 public function hasContentModel( $id ) {
1100 return $this->getContentModel() == $id;
1101 }
1102
1103 /**
1104 * Set a proposed content model for the page for permissions checking
1105 *
1106 * This does not actually change the content model of a title in the DB.
1107 * It only affects this particular Title instance. The content model is
1108 * forced to remain this value until another setContentModel() call.
1109 *
1110 * ContentHandler::canBeUsedOn() should be checked before calling this
1111 * if there is any doubt regarding the applicability of the content model
1112 *
1113 * @warning This must only be used if the caller controls the further use of
1114 * this Title object, to avoid other code unexpectedly using the new value.
1115 *
1116 * @since 1.28
1117 * @param string $model CONTENT_MODEL_XXX constant
1118 */
1119 public function setContentModel( $model ) {
1120 if ( (string)$model === '' ) {
1121 throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
1122 }
1123
1124 $this->uncache();
1125 $this->mContentModel = $model;
1126 $this->mForcedContentModel = true;
1127 }
1128
1129 /**
1130 * If the content model field is not frozen then update it with a retrieved value
1131 *
1132 * @param string|bool $model CONTENT_MODEL_XXX constant or false
1133 */
1134 private function lazyFillContentModel( $model ) {
1135 if ( !$this->mForcedContentModel ) {
1136 $this->mContentModel = ( $model === false ) ? false : (string)$model;
1137 }
1138 }
1139
1140 /**
1141 * Get the namespace text
1142 *
1143 * @return string|false Namespace name with underscores (not spaces), e.g. 'User_talk'
1144 */
1145 public function getNsText() {
1146 if ( $this->isExternal() ) {
1147 // This probably shouldn't even happen, except for interwiki transclusion.
1148 // If possible, use the canonical name for the foreign namespace.
1149 if ( $this->mNamespace === NS_MAIN ) {
1150 // Optimisation
1151 return '';
1152 } else {
1153 $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
1154 getCanonicalName( $this->mNamespace );
1155 if ( $nsText !== false ) {
1156 return $nsText;
1157 }
1158 }
1159 }
1160
1161 try {
1162 $formatter = self::getTitleFormatter();
1163 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1164 } catch ( InvalidArgumentException $ex ) {
1165 wfDebug( __METHOD__ . ': ' . $ex->getMessage() );
1166 return false;
1167 }
1168 }
1169
1170 /**
1171 * Get the namespace text of the subject (rather than talk) page
1172 *
1173 * @return string Namespace name with underscores (not spaces)
1174 */
1175 public function getSubjectNsText() {
1176 $services = MediaWikiServices::getInstance();
1177 return $services->getContentLanguage()->
1178 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
1179 }
1180
1181 /**
1182 * Get the namespace text of the talk page
1183 *
1184 * @return string Namespace name with underscores (not spaces)
1185 */
1186 public function getTalkNsText() {
1187 $services = MediaWikiServices::getInstance();
1188 return $services->getContentLanguage()->
1189 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
1190 }
1191
1192 /**
1193 * Can this title have a corresponding talk page?
1194 *
1195 * False for relative section links (with getText() === ''),
1196 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1197 *
1198 * @see NamespaceInfo::canHaveTalkPage
1199 * @since 1.30
1200 *
1201 * @return bool True if this title either is a talk page or can have a talk page associated.
1202 */
1203 public function canHaveTalkPage() {
1204 return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1205 }
1206
1207 /**
1208 * Can this title represent a page in the wiki's database?
1209 *
1210 * Titles can exist as pages in the database if they are valid, and they
1211 * are not Special pages, interwiki links, or fragment-only links.
1212 *
1213 * @see isValid()
1214 *
1215 * @return bool true if and only if this title can be used to perform an edit.
1216 */
1217 public function canExist(): bool {
1218 // NOTE: Don't use getArticleID(), we don't want to
1219 // trigger a database query here. This check is supposed to
1220 // act as an optimization, not add extra cost.
1221 if ( $this->mArticleID > 0 ) {
1222 // It exists, so it can exist.
1223 return true;
1224 }
1225
1226 // NOTE: we call the relatively expensive isValid() method further down,
1227 // but we can bail out early if we already know the title is invalid.
1228 if ( $this->mIsValid === false ) {
1229 // It's invalid, so it can't exist.
1230 return false;
1231 }
1232
1233 if ( $this->getNamespace() < NS_MAIN ) {
1234 // It's a special page, so it can't exist in the database.
1235 return false;
1236 }
1237
1238 if ( $this->isExternal() ) {
1239 // If it's external, it's not local, so it can't exist.
1240 return false;
1241 }
1242
1243 if ( $this->getText() === '' ) {
1244 // The title has no text, so it can't exist in the database.
1245 // It's probably an on-page section link, like "#something".
1246 return false;
1247 }
1248
1249 // Double check that the title is valid.
1250 return $this->isValid();
1251 }
1252
1253 /**
1254 * Returns true if this is a special page.
1255 *
1256 * @return bool
1257 */
1258 public function isSpecialPage() {
1259 return $this->mNamespace === NS_SPECIAL;
1260 }
1261
1262 /**
1263 * Returns true if this title resolves to the named special page
1264 *
1265 * @param string $name The special page name
1266 * @return bool
1267 */
1268 public function isSpecial( $name ) {
1269 if ( $this->isSpecialPage() ) {
1270 [ $thisName, /* $subpage */ ] =
1271 MediaWikiServices::getInstance()->getSpecialPageFactory()->
1272 resolveAlias( $this->mDbkeyform );
1273 if ( $name == $thisName ) {
1274 return true;
1275 }
1276 }
1277 return false;
1278 }
1279
1280 /**
1281 * If the Title refers to a special page alias which is not the local default, resolve
1282 * the alias, and localise the name as necessary. Otherwise, return $this
1283 *
1284 * @return Title
1285 */
1286 public function fixSpecialName() {
1287 if ( $this->isSpecialPage() ) {
1288 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1289 [ $canonicalName, $par ] = $spFactory->resolveAlias( $this->mDbkeyform );
1290 if ( $canonicalName ) {
1291 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1292 if ( $localName != $this->mDbkeyform ) {
1293 return self::makeTitle( NS_SPECIAL, $localName );
1294 }
1295 }
1296 }
1297 return $this;
1298 }
1299
1300 /**
1301 * Returns true if the title is inside the specified namespace.
1302 *
1303 * @param int $ns The namespace
1304 * @return bool
1305 * @since 1.19
1306 */
1307 public function inNamespace( int $ns ): bool {
1308 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1309 equals( $this->mNamespace, $ns );
1310 }
1311
1312 /**
1313 * Returns true if the title is inside one of the specified namespaces.
1314 *
1315 * @param int|int[] ...$namespaces The namespaces to check for
1316 * @return bool
1317 * @since 1.19
1318 */
1319 public function inNamespaces( ...$namespaces ) {
1320 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1321 $namespaces = $namespaces[0];
1322 }
1323
1324 foreach ( $namespaces as $ns ) {
1325 if ( $this->inNamespace( $ns ) ) {
1326 return true;
1327 }
1328 }
1329
1330 return false;
1331 }
1332
1333 /**
1334 * Returns true if the title has the same subject namespace as the
1335 * namespace specified.
1336 * For example this method will take NS_USER and return true if namespace
1337 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1338 * as their subject namespace.
1339 *
1340 * This is MUCH simpler than individually testing for equivalence
1341 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1342 * @since 1.19
1343 * @param int $ns
1344 * @return bool
1345 */
1346 public function hasSubjectNamespace( $ns ) {
1347 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1348 subjectEquals( $this->mNamespace, $ns );
1349 }
1350
1351 /**
1352 * Is this Title in a namespace which contains content?
1353 * In other words, is this a content page, for the purposes of calculating
1354 * statistics, etc?
1355 *
1356 * @return bool
1357 */
1358 public function isContentPage() {
1359 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1360 isContent( $this->mNamespace );
1361 }
1362
1363 /**
1364 * Would anybody with sufficient privileges be able to move this page?
1365 * Some pages just aren't movable.
1366 *
1367 * @return bool
1368 */
1369 public function isMovable() {
1370 $services = MediaWikiServices::getInstance();
1371 if (
1372 !$services->getNamespaceInfo()->
1373 isMovable( $this->mNamespace ) || $this->isExternal()
1374 ) {
1375 // Interwiki title or immovable namespace. Hooks don't get to override here
1376 return false;
1377 }
1378
1379 $result = true;
1380 ( new HookRunner( $services->getHookContainer() ) )->onTitleIsMovable( $this, $result );
1381 return $result;
1382 }
1383
1384 /**
1385 * Is this the mainpage?
1386 * @see T302186
1387 *
1388 * @since 1.18
1389 * @return bool
1390 */
1391 public function isMainPage() {
1392 self::$cachedMainPage ??= self::newMainPage();
1393 return $this->equals( self::$cachedMainPage );
1394 }
1395
1396 /**
1397 * Is this a subpage?
1398 *
1399 * @return bool
1400 */
1401 public function isSubpage() {
1402 return MediaWikiServices::getInstance()
1403 ->getNamespaceInfo()
1404 ->hasSubpages( $this->mNamespace )
1405 && str_contains( $this->getText(), '/' );
1406 }
1407
1408 /**
1409 * Is this a conversion table for the LanguageConverter?
1410 *
1411 * @return bool
1412 */
1413 public function isConversionTable() {
1414 // @todo ConversionTable should become a separate content model.
1415 // @todo And the prefix should be localized, too!
1416
1417 return $this->mNamespace === NS_MEDIAWIKI &&
1418 str_starts_with( $this->getText(), 'Conversiontable/' );
1419 }
1420
1421 /**
1422 * Does that page contain wikitext, or it is JS, CSS or whatever?
1423 *
1424 * @return bool
1425 */
1426 public function isWikitextPage() {
1427 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1428 }
1429
1430 /**
1431 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1432 * global UI. This is generally true for pages in the MediaWiki namespace having
1433 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1434 *
1435 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1436 * for that!
1437 *
1438 * Note that this method should not return true for pages that contain and show
1439 * "inactive" CSS, JSON, or JS.
1440 *
1441 * @return bool
1442 * @since 1.31
1443 */
1444 public function isSiteConfigPage() {
1445 return (
1446 $this->isSiteCssConfigPage()
1447 || $this->isSiteJsonConfigPage()
1448 || $this->isSiteJsConfigPage()
1449 );
1450 }
1451
1452 /**
1453 * Is this a "config" (.css, .json, or .js) subpage of a user page?
1454 *
1455 * @return bool
1456 * @since 1.31
1457 */
1458 public function isUserConfigPage() {
1459 return (
1460 $this->isUserCssConfigPage()
1461 || $this->isUserJsonConfigPage()
1462 || $this->isUserJsConfigPage()
1463 );
1464 }
1465
1466 /**
1467 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1468 *
1469 * @return string Containing skin name from .css, .json, or .js subpage title
1470 * @since 1.31
1471 */
1472 public function getSkinFromConfigSubpage() {
1473 $text = $this->getText();
1474 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
1475 if ( $lastSlashPos === false ) {
1476 return '';
1477 }
1478
1479 $lastDot = strrpos( $text, '.', $lastSlashPos );
1480 if ( $lastDot === false ) {
1481 return '';
1482 }
1483
1484 return substr( $text, $lastSlashPos + 1, $lastDot - $lastSlashPos - 1 );
1485 }
1486
1487 /**
1488 * Is this a CSS "config" subpage of a user page?
1489 *
1490 * @return bool
1491 * @since 1.31
1492 */
1493 public function isUserCssConfigPage() {
1494 return (
1495 $this->mNamespace === NS_USER
1496 && $this->isSubpage()
1497 && $this->hasContentModel( CONTENT_MODEL_CSS )
1498 );
1499 }
1500
1501 /**
1502 * Is this a JSON "config" subpage of a user page?
1503 *
1504 * @return bool
1505 * @since 1.31
1506 */
1507 public function isUserJsonConfigPage() {
1508 return (
1509 $this->mNamespace === NS_USER
1510 && $this->isSubpage()
1511 && $this->hasContentModel( CONTENT_MODEL_JSON )
1512 );
1513 }
1514
1515 /**
1516 * Is this a JS "config" subpage of a user page?
1517 *
1518 * @return bool
1519 * @since 1.31
1520 */
1521 public function isUserJsConfigPage() {
1522 return (
1523 $this->mNamespace === NS_USER
1524 && $this->isSubpage()
1525 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1526 );
1527 }
1528
1529 /**
1530 * Is this a sitewide CSS "config" page?
1531 *
1532 * @return bool
1533 * @since 1.32
1534 */
1535 public function isSiteCssConfigPage() {
1536 return (
1537 $this->mNamespace === NS_MEDIAWIKI
1538 && (
1539 $this->hasContentModel( CONTENT_MODEL_CSS )
1540 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1541 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1542 || str_ends_with( $this->mDbkeyform, '.css' )
1543 )
1544 );
1545 }
1546
1547 /**
1548 * Is this a sitewide JSON "config" page?
1549 *
1550 * @return bool
1551 * @since 1.32
1552 */
1553 public function isSiteJsonConfigPage() {
1554 return (
1555 $this->mNamespace === NS_MEDIAWIKI
1556 && (
1557 $this->hasContentModel( CONTENT_MODEL_JSON )
1558 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1559 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1560 || str_ends_with( $this->mDbkeyform, '.json' )
1561 )
1562 );
1563 }
1564
1565 /**
1566 * Is this a sitewide JS "config" page?
1567 *
1568 * @return bool
1569 * @since 1.31
1570 */
1571 public function isSiteJsConfigPage() {
1572 return (
1573 $this->mNamespace === NS_MEDIAWIKI
1574 && (
1575 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1576 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1577 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1578 || str_ends_with( $this->mDbkeyform, '.js' )
1579 )
1580 );
1581 }
1582
1583 /**
1584 * Is this a message which can contain raw HTML?
1585 *
1586 * @return bool
1587 * @since 1.32
1588 */
1589 public function isRawHtmlMessage() {
1590 global $wgRawHtmlMessages;
1591
1592 if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1593 return false;
1594 }
1595 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1596 return in_array( $message, $wgRawHtmlMessages, true );
1597 }
1598
1599 /**
1600 * Is this a talk page of some sort?
1601 *
1602 * @return bool
1603 */
1604 public function isTalkPage() {
1605 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1606 isTalk( $this->mNamespace );
1607 }
1608
1609 /**
1610 * Get a Title object associated with the talk page of this article
1611 *
1612 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1613 * with NamespaceInfo::canHaveTalkPage(). Note that the new method will
1614 * throw if asked for the talk page of a section-only link, or of an interwiki
1615 * link.
1616 * @return Title The object for the talk page
1617 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1618 * or because it's a relative link, or an interwiki link.
1619 */
1620 public function getTalkPage() {
1621 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1622 // Instead of failing on invalid titles, let's just log the issue for now.
1623 // See the discussion on T227817.
1624
1625 // Is this the same title?
1626 $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
1627 if ( $this->mNamespace == $talkNS ) {
1628 return $this;
1629 }
1630
1631 $title = self::makeTitle( $talkNS, $this->mDbkeyform );
1632
1633 $this->warnIfPageCannotExist( $title, __METHOD__ );
1634
1635 return $title;
1636 // TODO: replace the above with the code below:
1637 // return self::castFromLinkTarget(
1638 // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1639 }
1640
1641 /**
1642 * Get a Title object associated with the talk page of this article,
1643 * if such a talk page can exist.
1644 *
1645 * @since 1.30
1646 *
1647 * @return Title|null The object for the talk page,
1648 * or null if no associated talk page can exist, according to canHaveTalkPage().
1649 */
1650 public function getTalkPageIfDefined() {
1651 if ( !$this->canHaveTalkPage() ) {
1652 return null;
1653 }
1654
1655 return $this->getTalkPage();
1656 }
1657
1658 /**
1659 * Get a title object associated with the subject page of this
1660 * talk page
1661 *
1662 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1663 * @return Title The object for the subject page
1664 */
1665 public function getSubjectPage() {
1666 // Is this the same title?
1667 $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
1668 ->getSubject( $this->mNamespace );
1669 if ( $this->mNamespace == $subjectNS ) {
1670 return $this;
1671 }
1672 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1673 // Instead of failing on invalid titles, let's just log the issue for now.
1674 // See the discussion on T227817.
1675 $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
1676
1677 $this->warnIfPageCannotExist( $title, __METHOD__ );
1678
1679 return $title;
1680 // TODO: replace the above with the code below:
1681 // return self::castFromLinkTarget(
1682 // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1683 }
1684
1685 /**
1686 * @param Title $title
1687 * @param string $method
1688 *
1689 * @return bool whether a warning was issued
1690 */
1691 private function warnIfPageCannotExist( Title $title, $method ) {
1692 if ( $this->getText() == '' ) {
1693 wfLogWarning(
1694 $method . ': called on empty title ' . $this->getFullText() . ', returning '
1695 . $title->getFullText()
1696 );
1697
1698 return true;
1699 }
1700
1701 if ( $this->getInterwiki() !== '' ) {
1702 wfLogWarning(
1703 $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1704 . $title->getFullText()
1705 );
1706
1707 return true;
1708 }
1709
1710 return false;
1711 }
1712
1713 /**
1714 * Get the other title for this page, if this is a subject page
1715 * get the talk page, if it is a subject page get the talk page
1716 *
1717 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1718 * @since 1.25
1719 * @throws MWException If the page doesn't have an other page
1720 * @return Title
1721 */
1722 public function getOtherPage() {
1723 // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1724 // until their semantics has become exactly the same.
1725 // See the discussion on T227817.
1726 if ( $this->isSpecialPage() ) {
1727 throw new MWException( 'Special pages cannot have other pages' );
1728 }
1729 if ( $this->isTalkPage() ) {
1730 return $this->getSubjectPage();
1731 } else {
1732 if ( !$this->canHaveTalkPage() ) {
1733 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1734 }
1735 return $this->getTalkPage();
1736 }
1737 // TODO: replace the above with the code below:
1738 // return self::castFromLinkTarget(
1739 // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1740 }
1741
1742 /**
1743 * Get the Title fragment (i.e.\ the bit after the #) in text form
1744 *
1745 * Use Title::hasFragment to check for a fragment
1746 *
1747 * @return string Title fragment
1748 */
1749 public function getFragment(): string {
1750 return $this->mFragment;
1751 }
1752
1753 /**
1754 * Get the fragment in URL form, including the "#" character if there is one
1755 *
1756 * @return string Fragment in URL form
1757 */
1758 public function getFragmentForURL() {
1759 if ( !$this->hasFragment() ) {
1760 return '';
1761 } elseif ( $this->isExternal() ) {
1762 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1763 // so we treat it like a local interwiki.
1764 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1765 if ( $interwiki && !$interwiki->isLocal() ) {
1766 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1767 }
1768 }
1769
1770 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1771 }
1772
1773 /**
1774 * Set the fragment for this title. Removes the first character from the
1775 * specified fragment before setting, so it assumes you're passing it with
1776 * an initial "#".
1777 *
1778 * @warning This must only be used if the caller controls the further use of
1779 * this Title object, to avoid other code unexpectedly using the new value.
1780 *
1781 * @param string $fragment Text
1782 */
1783 public function setFragment( $fragment ) {
1784 $this->uncache();
1785 $this->mFragment = self::normalizeFragment( $fragment );
1786 }
1787
1788 /**
1789 * Creates a new Title for a different fragment of the same page.
1790 *
1791 * @since 1.27
1792 * @param string $fragment
1793 * @return Title
1794 */
1795 public function createFragmentTarget( string $fragment ): self {
1796 return self::makeTitle(
1797 $this->mNamespace,
1798 $this->getText(),
1799 $fragment,
1800 $this->mInterwiki
1801 );
1802 }
1803
1804 /**
1805 * Normalizes fragment part of the title.
1806 *
1807 * @param string $fragment
1808 * @return string
1809 */
1810 private static function normalizeFragment( $fragment ) {
1811 if ( str_starts_with( $fragment, '#' ) ) {
1812 $fragment = substr( $fragment, 1 );
1813 }
1814 return strtr( $fragment, '_', ' ' );
1815 }
1816
1817 /**
1818 * Prefix some arbitrary text with the namespace or interwiki prefix
1819 * of this object
1820 *
1821 * @param string $name The text
1822 * @return string The prefixed text
1823 */
1824 private function prefix( $name ) {
1825 $p = '';
1826 if ( $this->isExternal() ) {
1827 $p = $this->mInterwiki . ':';
1828 }
1829
1830 if ( $this->mNamespace != 0 ) {
1831 $nsText = $this->getNsText();
1832
1833 if ( $nsText === false ) {
1834 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1835 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1836 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1837 }
1838
1839 $p .= $nsText . ':';
1840 }
1841 return $p . $name;
1842 }
1843
1844 /**
1845 * Get the prefixed database key form
1846 *
1847 * @return string The prefixed title, with underscores and
1848 * any interwiki and namespace prefixes
1849 */
1850 public function getPrefixedDBkey() {
1851 $s = $this->prefix( $this->mDbkeyform );
1852 $s = strtr( $s, ' ', '_' );
1853 return $s;
1854 }
1855
1856 /**
1857 * Get the prefixed title with spaces.
1858 * This is the form usually used for display
1859 *
1860 * @return string The prefixed title, with spaces
1861 */
1862 public function getPrefixedText() {
1863 if ( $this->prefixedText === null ) {
1864 $s = $this->prefix( $this->mTextform );
1865 $s = strtr( $s, '_', ' ' );
1866 $this->prefixedText = $s;
1867 }
1868 return $this->prefixedText;
1869 }
1870
1871 /**
1872 * Return a string representation of this title
1873 *
1874 * @return string Representation of this title
1875 */
1876 public function __toString(): string {
1877 return $this->getPrefixedText();
1878 }
1879
1880 /**
1881 * Get the prefixed title with spaces, plus any fragment
1882 * (part beginning with '#')
1883 *
1884 * @return string The prefixed title, with spaces and the fragment, including '#'
1885 */
1886 public function getFullText() {
1887 $text = $this->getPrefixedText();
1888 if ( $this->hasFragment() ) {
1889 $text .= '#' . $this->mFragment;
1890 }
1891 return $text;
1892 }
1893
1894 /**
1895 * Finds the first or last subpage divider (slash) in the string.
1896 * Any leading sequence of slashes is ignored, since it does not divide
1897 * two parts of the string. Considering leading slashes dividers would
1898 * result in empty root title or base title (T229443).
1899 *
1900 * Note that trailing slashes are considered dividers, and empty subpage
1901 * names are allowed.
1902 *
1903 * @param string $text
1904 * @param int $dir -1 for the last or +1 for the first divider.
1905 *
1906 * @return false|int
1907 */
1908 private function findSubpageDivider( $text, $dir ) {
1909 if ( $dir > 0 ) {
1910 // Skip leading slashes, but keep the last one when there is nothing but slashes
1911 $bottom = strspn( $text, '/', 0, -1 );
1912 $idx = strpos( $text, '/', $bottom );
1913 } else {
1914 // Any slash from the end can be a divider, as subpage names can be empty
1915 $idx = strrpos( $text, '/' );
1916 }
1917
1918 // The first character can never be a divider, as that would result in an empty base
1919 return $idx === 0 ? false : $idx;
1920 }
1921
1922 /**
1923 * Whether this Title's namespace has subpages enabled.
1924 * @return bool
1925 */
1926 private function hasSubpagesEnabled() {
1927 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1928 hasSubpages( $this->mNamespace );
1929 }
1930
1931 /**
1932 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1933 *
1934 * @note the return value may contain trailing whitespace and is thus
1935 * not safe for use with makeTitle or TitleValue.
1936 *
1937 * @par Example:
1938 * @code
1939 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1940 * # returns: 'Foo'
1941 * @endcode
1942 *
1943 * @return string Root name
1944 * @since 1.20
1945 */
1946 public function getRootText() {
1947 $text = $this->getText();
1948 if ( !$this->hasSubpagesEnabled() ) {
1949 return $text;
1950 }
1951
1952 $firstSlashPos = $this->findSubpageDivider( $text, +1 );
1953 // Don't discard the real title if there's no subpage involved
1954 if ( $firstSlashPos === false ) {
1955 return $text;
1956 }
1957
1958 return substr( $text, 0, $firstSlashPos );
1959 }
1960
1961 /**
1962 * Get the root page name title, i.e. the leftmost part before any slashes
1963 *
1964 * @par Example:
1965 * @code
1966 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1967 * # returns: Title{User:Foo}
1968 * @endcode
1969 *
1970 * @return Title
1971 * @since 1.20
1972 */
1973 public function getRootTitle() {
1974 $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1975
1976 if ( !$title ) {
1977 if ( !$this->isValid() ) {
1978 // If the title wasn't valid in the first place, we can't expect
1979 // to successfully parse it. T290194
1980 return $this;
1981 }
1982
1983 Assert::postcondition(
1984 $title !== null,
1985 'makeTitleSafe() should always return a Title for the text ' .
1986 'returned by getRootText().'
1987 );
1988 }
1989
1990 return $title;
1991 }
1992
1993 /**
1994 * Get the base page name without a namespace, i.e. the part before the subpage name
1995 *
1996 * @note the return value may contain trailing whitespace and is thus
1997 * not safe for use with makeTitle or TitleValue.
1998 *
1999 * @par Example:
2000 * @code
2001 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
2002 * # returns: 'Foo/Bar'
2003 * @endcode
2004 *
2005 * @return string Base name
2006 */
2007 public function getBaseText() {
2008 $text = $this->getText();
2009 if ( !$this->hasSubpagesEnabled() ) {
2010 return $text;
2011 }
2012
2013 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2014 // Don't discard the real title if there's no subpage involved
2015 if ( $lastSlashPos === false ) {
2016 return $text;
2017 }
2018
2019 return substr( $text, 0, $lastSlashPos );
2020 }
2021
2022 /**
2023 * Get the base page name title, i.e. the part before the subpage name.
2024 *
2025 * @par Example:
2026 * @code
2027 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
2028 * # returns: Title{User:Foo/Bar}
2029 * @endcode
2030 *
2031 * @return Title
2032 * @since 1.20
2033 */
2034 public function getBaseTitle() {
2035 $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
2036
2037 if ( !$title ) {
2038 if ( !$this->isValid() ) {
2039 // If the title wasn't valid in the first place, we can't expect
2040 // to successfully parse it. T290194
2041 return $this;
2042 }
2043
2044 Assert::postcondition(
2045 $title !== null,
2046 'makeTitleSafe() should always return a Title for the text ' .
2047 'returned by getBaseText().'
2048 );
2049 }
2050
2051 return $title;
2052 }
2053
2054 /**
2055 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
2056 *
2057 * @par Example:
2058 * @code
2059 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
2060 * # returns: "Baz"
2061 * @endcode
2062 *
2063 * @return string Subpage name
2064 */
2065 public function getSubpageText() {
2066 $text = $this->getText();
2067 if ( !$this->hasSubpagesEnabled() ) {
2068 return $text;
2069 }
2070
2071 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2072 if ( $lastSlashPos === false ) {
2073 // T256922 - Return the title text if no subpages
2074 return $text;
2075 }
2076 return substr( $text, $lastSlashPos + 1 );
2077 }
2078
2079 /**
2080 * Get the title for a subpage of the current page
2081 *
2082 * @par Example:
2083 * @code
2084 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
2085 * # returns: Title{User:Foo/Bar/Baz/Asdf}
2086 * @endcode
2087 *
2088 * @param string $text The subpage name to add to the title
2089 * @return Title|null Subpage title, or null on an error
2090 * @since 1.20
2091 */
2092 public function getSubpage( $text ) {
2093 return self::makeTitleSafe(
2094 $this->mNamespace,
2095 $this->getText() . '/' . $text,
2096 '',
2097 $this->mInterwiki
2098 );
2099 }
2100
2101 /**
2102 * Get a URL-encoded form of the subpage text
2103 *
2104 * @return string URL-encoded subpage name
2105 */
2106 public function getSubpageUrlForm() {
2107 $text = $this->getSubpageText();
2108 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
2109 return $text;
2110 }
2111
2112 /**
2113 * Get a URL-encoded title (not an actual URL) including interwiki
2114 *
2115 * @return string The URL-encoded form
2116 */
2117 public function getPrefixedURL() {
2118 $s = $this->prefix( $this->mDbkeyform );
2119 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2120 return $s;
2121 }
2122
2123 /**
2124 * Get a real URL referring to this title, with interwiki link and
2125 * fragment
2126 *
2127 * @see self::getLocalURL for the arguments.
2128 * @see \MediaWiki\Utils\UrlUtils::expand()
2129 * @param string|array $query
2130 * @param false $query2 deprecated since MW 1.19; ignored since MW 1.41
2131 * @param string|int|null $proto Protocol type to use in URL
2132 * @return string The URL
2133 */
2134 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
2135 $services = MediaWikiServices::getInstance();
2136
2137 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2138
2139 # Hand off all the decisions on urls to getLocalURL
2140 $url = $this->getLocalURL( $query );
2141
2142 # Expand the url to make it a full url. Note that getLocalURL has the
2143 # potential to output full urls for a variety of reasons, so we use
2144 # UrlUtils::expand() instead of simply prepending $wgServer
2145 $url = (string)$services->getUrlUtils()->expand( $url, $proto );
2146
2147 # Finally, add the fragment.
2148 $url .= $this->getFragmentForURL();
2149 ( new HookRunner( $services->getHookContainer() ) )->onGetFullURL( $this, $url, $query );
2150 return $url;
2151 }
2152
2153 /**
2154 * Get a url appropriate for making redirects based on an untrusted url arg
2155 *
2156 * This is basically the same as getFullUrl(), but in the case of external
2157 * interwikis, we send the user to a landing page, to prevent possible
2158 * phishing attacks and the like.
2159 *
2160 * @note Uses current protocol by default, since technically relative urls
2161 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2162 * places where the url gets cached, as might pollute between
2163 * https and non-https users.
2164 * @see self::getLocalURL for the arguments.
2165 * @param array|string $query
2166 * @param string $proto Protocol type to use in URL
2167 * @return string A url suitable to use in an HTTP location header.
2168 */
2169 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2170 $target = $this;
2171 if ( $this->isExternal() ) {
2172 $target = SpecialPage::getTitleFor(
2173 'GoToInterwiki',
2174 $this->getPrefixedDBkey()
2175 );
2176 }
2177 return $target->getFullURL( $query, false, $proto );
2178 }
2179
2180 /**
2181 * Get a URL with no fragment or server name (relative URL) from a Title object.
2182 * If this page is generated with action=render, however,
2183 * $wgServer is prepended to make an absolute URL.
2184 *
2185 * @see self::getFullURL to always get an absolute URL.
2186 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2187 * valid to link, locally, to the current Title.
2188 * @see self::newFromText to produce a Title object.
2189 *
2190 * @param string|array $query An optional query string,
2191 * not used for interwiki links. Can be specified as an associative array as well,
2192 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2193 * Some query patterns will trigger various shorturl path replacements.
2194 *
2195 * @return string
2196 */
2197 public function getLocalURL( $query = '' ) {
2198 global $wgArticlePath, $wgScript, $wgMainPageIsDomainRoot;
2199
2200 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2201
2202 $services = MediaWikiServices::getInstance();
2203 $hookRunner = new HookRunner( $services->getHookContainer() );
2204 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2205 if ( $interwiki ) {
2206 $namespace = $this->getNsText();
2207 if ( $namespace != '' ) {
2208 # Can this actually happen? Interwikis shouldn't be parsed.
2209 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2210 $namespace .= ':';
2211 }
2212 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2213 $url = wfAppendQuery( $url, $query );
2214 } else {
2215 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2216 if ( $query == '' ) {
2217 if ( $wgMainPageIsDomainRoot && $this->isMainPage() ) {
2218 $url = '/';
2219 } else {
2220 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2221 }
2222 $hookRunner->onGetLocalURL__Article( $this, $url );
2223 } else {
2224 global $wgVariantArticlePath, $wgActionPaths;
2225 $url = false;
2226 $matches = [];
2227
2228 $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
2229
2230 if ( $articlePaths
2231 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2232 ) {
2233 $action = urldecode( $matches[2] );
2234 if ( isset( $articlePaths[$action] ) ) {
2235 $query = $matches[1];
2236 if ( isset( $matches[4] ) ) {
2237 $query .= $matches[4];
2238 }
2239 $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2240 if ( $query != '' ) {
2241 $url = wfAppendQuery( $url, $query );
2242 }
2243 }
2244 }
2245
2246 if ( $url === false
2247 && $wgVariantArticlePath
2248 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2249 && $this->getPageLanguage()->equals( $services->getContentLanguage() )
2250 && $this->getPageLanguageConverter()->hasVariants()
2251 ) {
2252 $variant = urldecode( $matches[1] );
2253 if ( $this->getPageLanguageConverter()->hasVariant( $variant ) ) {
2254 // Only do the variant replacement if the given variant is a valid
2255 // variant for the page's language.
2256 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2257 $url = str_replace( '$1', $dbkey, $url );
2258 }
2259 }
2260
2261 if ( $url === false ) {
2262 if ( $query == '-' ) {
2263 $query = '';
2264 }
2265 $url = "{$wgScript}?title={$dbkey}&{$query}";
2266 }
2267 }
2268 $hookRunner->onGetLocalURL__Internal( $this, $url, $query );
2269 }
2270
2271 $hookRunner->onGetLocalURL( $this, $url, $query );
2272 return $url;
2273 }
2274
2275 /**
2276 * Get a URL that's the simplest URL that will be valid to link, locally,
2277 * to the current Title. It includes the fragment, but does not include
2278 * the server unless action=render is used (or the link is external). If
2279 * there's a fragment but the prefixed text is empty, we just return a link
2280 * to the fragment.
2281 *
2282 * The result obviously should not be URL-escaped, but does need to be
2283 * HTML-escaped if it's being output in HTML.
2284 *
2285 * @param string|array $query
2286 * @param string|string[]|false $query2 deprecated since MW 1.19; ignored since MW 1.41
2287 * @param string|int|false $proto A PROTO_* constant on how the URL should be expanded,
2288 * or false (default) for no expansion
2289 * @see self::getLocalURL for the arguments.
2290 * @return string The URL
2291 */
2292 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2293 if ( $this->isExternal() || $proto !== false ) {
2294 $ret = $this->getFullURL( $query, false, $proto );
2295 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2296 $ret = $this->getFragmentForURL();
2297 } else {
2298 $ret = $this->getLocalURL( $query ) . $this->getFragmentForURL();
2299 }
2300 return $ret;
2301 }
2302
2303 /**
2304 * Get the URL form for an internal link.
2305 * - Used in various CDN-related code, in case we have a different
2306 * internal hostname for the server from the exposed one.
2307 *
2308 * This uses $wgInternalServer to qualify the path, or $wgServer
2309 * if $wgInternalServer is not set. If the server variable used is
2310 * protocol-relative, the URL will be expanded to http://
2311 *
2312 * @see self::getLocalURL for the arguments.
2313 * @param string|array $query
2314 * @return string The URL
2315 */
2316 public function getInternalURL( $query = '' ) {
2317 global $wgInternalServer, $wgServer;
2318 $services = MediaWikiServices::getInstance();
2319
2320 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2321
2322 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2323 $url = (string)$services->getUrlUtils()->expand( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2324 ( new HookRunner( $services->getHookContainer() ) )
2325 ->onGetInternalURL( $this, $url, $query );
2326 return $url;
2327 }
2328
2329 /**
2330 * Get the URL for a canonical link, for use in things like IRC and
2331 * e-mail notifications. Uses $wgCanonicalServer and the
2332 * GetCanonicalURL hook.
2333 *
2334 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2335 *
2336 * @see self::getLocalURL for the arguments.
2337 * @param string|array $query
2338 * @return string The URL
2339 * @since 1.18
2340 */
2341 public function getCanonicalURL( $query = '' ) {
2342 $services = MediaWikiServices::getInstance();
2343
2344 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2345
2346 $url = (string)$services->getUrlUtils()->expand(
2347 $this->getLocalURL( $query ) . $this->getFragmentForURL(),
2348 PROTO_CANONICAL
2349 );
2350 ( new HookRunner( $services->getHookContainer() ) )
2351 ->onGetCanonicalURL( $this, $url, $query );
2352 return $url;
2353 }
2354
2355 /**
2356 * Get the edit URL for this Title
2357 *
2358 * @return string The URL, or a null string if this is an interwiki link
2359 */
2360 public function getEditURL() {
2361 if ( $this->isExternal() ) {
2362 return '';
2363 }
2364 $s = $this->getLocalURL( 'action=edit' );
2365
2366 return $s;
2367 }
2368
2369 /**
2370 * Is this title subject to title protection?
2371 * Title protection is the one applied against creation of such title.
2372 *
2373 * @deprecated since 1.37, use RestrictionStore::getCreateProtection() instead;
2374 * hard-deprecated since 1.43
2375 *
2376 * @return array|bool An associative array representing any existent title
2377 * protection, or false if there's none.
2378 */
2379 public function getTitleProtection() {
2380 wfDeprecated( __METHOD__, '1.37' );
2381 return MediaWikiServices::getInstance()->getRestrictionStore()->getCreateProtection( $this )
2382 ?: false;
2383 }
2384
2385 /**
2386 * Remove any title protection due to page existing
2387 *
2388 * @deprecated since 1.37, do not use (this is only for WikiPage::onArticleCreate)
2389 */
2390 public function deleteTitleProtection() {
2391 MediaWikiServices::getInstance()->getRestrictionStore()->deleteCreateProtection( $this );
2392 }
2393
2394 /**
2395 * Load restrictions from the page_restrictions table
2396 *
2397 * @deprecated since 1.37, no public replacement; hard-deprecated since 1.43
2398 *
2399 * @param int $flags A bit field. If IDBAccessObject::READ_LATEST is set, skip replicas and read
2400 * from the primary DB.
2401 */
2402 public function loadRestrictions( $flags = 0 ) {
2403 wfDeprecated( __METHOD__, '1.37' );
2404 MediaWikiServices::getInstance()->getRestrictionStore()->loadRestrictions( $this, $flags );
2405 }
2406
2407 /**
2408 * Flush the protection cache in this object and force reload from the database.
2409 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2410 *
2411 * @deprecated since 1.37, now internal; hard-deprecated since 1.43
2412 */
2413 public function flushRestrictions() {
2414 wfDeprecated( __METHOD__, '1.37' );
2415 MediaWikiServices::getInstance()->getRestrictionStore()->flushRestrictions( $this );
2416 }
2417
2418 /**
2419 * Purge expired restrictions from the page_restrictions table
2420 *
2421 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2422 */
2423 public static function purgeExpiredRestrictions() {
2424 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2425 return;
2426 }
2427
2428 DeferredUpdates::addUpdate( new AutoCommitUpdate(
2429 MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase(),
2430 __METHOD__,
2431 static function ( IDatabase $dbw, $fname ) {
2432 $config = MediaWikiServices::getInstance()->getMainConfig();
2433 $ids = $dbw->newSelectQueryBuilder()
2434 ->select( 'pr_id' )
2435 ->from( 'page_restrictions' )
2436 ->where( $dbw->expr( 'pr_expiry', '<', $dbw->timestamp() ) )
2437 ->limit( $config->get( MainConfigNames::UpdateRowsPerQuery ) ) // T135470
2438 ->caller( $fname )->fetchFieldValues();
2439 if ( $ids ) {
2440 $dbw->newDeleteQueryBuilder()
2441 ->deleteFrom( 'page_restrictions' )
2442 ->where( [ 'pr_id' => $ids ] )
2443 ->caller( $fname )->execute();
2444 }
2445
2446 $dbw->newDeleteQueryBuilder()
2447 ->deleteFrom( 'protected_titles' )
2448 ->where( $dbw->expr( 'pt_expiry', '<', $dbw->timestamp() ) )
2449 ->caller( $fname )->execute();
2450 }
2451 ) );
2452 }
2453
2454 /**
2455 * Does this have subpages? (Warning, usually requires an extra DB query.)
2456 *
2457 * @return bool
2458 */
2459 public function hasSubpages() {
2460 if (
2461 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2462 hasSubpages( $this->mNamespace )
2463 ) {
2464 # Duh
2465 return false;
2466 }
2467
2468 # We dynamically add a member variable for the purpose of this method
2469 # alone to cache the result. There's no point in having it hanging
2470 # around uninitialized in every Title object; therefore we only add it
2471 # if needed and don't declare it statically.
2472 if ( $this->mHasSubpages === null ) {
2473 $subpages = $this->getSubpages( 1 );
2474 $this->mHasSubpages = $subpages instanceof TitleArrayFromResult && $subpages->count();
2475 }
2476
2477 return $this->mHasSubpages;
2478 }
2479
2480 /**
2481 * Get all subpages of this page.
2482 *
2483 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2484 * @return TitleArrayFromResult|array TitleArrayFromResult, or empty array if this page's namespace
2485 * doesn't allow subpages
2486 */
2487 public function getSubpages( $limit = -1 ) {
2488 if (
2489 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2490 hasSubpages( $this->mNamespace )
2491 ) {
2492 return [];
2493 }
2494
2495 $services = MediaWikiServices::getInstance();
2496 $pageStore = $services->getPageStore();
2497 $titleFactory = $services->getTitleFactory();
2498 $query = $pageStore->newSelectQueryBuilder()
2499 ->fields( $pageStore->getSelectFields() )
2500 ->whereTitlePrefix( $this->getNamespace(), $this->getDBkey() . '/' )
2501 ->caller( __METHOD__ );
2502 if ( $limit > -1 ) {
2503 $query->limit( $limit );
2504 }
2505
2506 return $titleFactory->newTitleArrayFromResult( $query->fetchResultSet() );
2507 }
2508
2509 /**
2510 * Is there a version of this page in the deletion archive?
2511 *
2512 * @deprecated since 1.36. Use self::getDeletedEditsCount()
2513 * @return int The number of archived revisions
2514 */
2515 public function isDeleted() {
2516 return $this->getDeletedEditsCount();
2517 }
2518
2519 /**
2520 * Is there a version of this page in the deletion archive?
2521 *
2522 * @since 1.36
2523 * @return int The number of archived revisions
2524 */
2525 public function getDeletedEditsCount() {
2526 if ( $this->mNamespace < 0 ) {
2527 return 0;
2528 }
2529
2530 $dbr = $this->getDbProvider()->getReplicaDatabase();
2531 $n = (int)$dbr->newSelectQueryBuilder()
2532 ->select( 'COUNT(*)' )
2533 ->from( 'archive' )
2534 ->where( [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ] )
2535 ->caller( __METHOD__ )->fetchField();
2536 if ( $this->mNamespace === NS_FILE ) {
2537 $n += $dbr->newSelectQueryBuilder()
2538 ->select( 'COUNT(*)' )
2539 ->from( 'filearchive' )
2540 ->where( [ 'fa_name' => $this->mDbkeyform ] )
2541 ->caller( __METHOD__ )->fetchField();
2542 }
2543 return $n;
2544 }
2545
2546 /**
2547 * Is there a version of this page in the deletion archive?
2548 *
2549 * @deprecated since 1.36, Use self::hasDeletedEdits()
2550 * @return bool
2551 */
2552 public function isDeletedQuick() {
2553 return $this->hasDeletedEdits();
2554 }
2555
2556 /**
2557 * Is there a version of this page in the deletion archive?
2558 *
2559 * @since 1.36
2560 * @return bool
2561 */
2562 public function hasDeletedEdits() {
2563 if ( $this->mNamespace < 0 ) {
2564 return false;
2565 }
2566 $dbr = $this->getDbProvider()->getReplicaDatabase();
2567 $deleted = (bool)$dbr->newSelectQueryBuilder()
2568 ->select( '1' )
2569 ->from( 'archive' )
2570 ->where( [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ] )
2571 ->caller( __METHOD__ )->fetchField();
2572 if ( !$deleted && $this->mNamespace === NS_FILE ) {
2573 $deleted = (bool)$dbr->newSelectQueryBuilder()
2574 ->select( '1' )
2575 ->from( 'filearchive' )
2576 ->where( [ 'fa_name' => $this->mDbkeyform ] )
2577 ->caller( __METHOD__ )->fetchField();
2578 }
2579 return $deleted;
2580 }
2581
2582 /**
2583 * Get the article ID for this Title from the link cache,
2584 * adding it if necessary
2585 *
2586 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2587 * @return int The ID
2588 */
2589 public function getArticleID( $flags = 0 ) {
2590 if ( $this->mArticleID === -1 && !$this->canExist() ) {
2591 $this->mArticleID = 0;
2592
2593 return $this->mArticleID;
2594 }
2595
2596 if ( $this->mArticleID === -1 || $this->shouldReadLatest( $flags ) ) {
2597 $this->mArticleID = (int)$this->getFieldFromPageStore( 'page_id', $flags );
2598 }
2599
2600 return $this->mArticleID;
2601 }
2602
2603 /**
2604 * Is this an article that is a redirect page?
2605 * Uses link cache, adding it if necessary.
2606 *
2607 * This is intended to provide fast access to page_is_redirect for linking.
2608 * In rare cases, there might not be a valid target in the redirect table
2609 * even though this function returns true.
2610 *
2611 * To find a redirect target, just call WikiPage::getRedirectTarget() and
2612 * check if it returns null, there's no need to call this first.
2613 *
2614 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2615 * @return bool
2616 */
2617 public function isRedirect( $flags = 0 ) {
2618 if ( $this->shouldReadLatest( $flags ) || $this->mRedirect === null ) {
2619 $this->mRedirect = (bool)$this->getFieldFromPageStore( 'page_is_redirect', $flags );
2620 }
2621
2622 return $this->mRedirect;
2623 }
2624
2625 /**
2626 * What is the length of this page?
2627 * Uses link cache, adding it if necessary
2628 *
2629 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2630 * @return int
2631 */
2632 public function getLength( $flags = 0 ) {
2633 if ( $this->shouldReadLatest( $flags ) || $this->mLength < 0 ) {
2634 $this->mLength = (int)$this->getFieldFromPageStore( 'page_len', $flags );
2635 }
2636
2637 if ( $this->mLength < 0 ) {
2638 $this->mLength = 0;
2639 }
2640
2641 return $this->mLength;
2642 }
2643
2644 /**
2645 * What is the page_latest field for this page?
2646 *
2647 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2648 * @return int Int or 0 if the page doesn't exist
2649 */
2650 public function getLatestRevID( $flags = 0 ) {
2651 if ( $this->shouldReadLatest( $flags ) || $this->mLatestID === false ) {
2652 $this->mLatestID = (int)$this->getFieldFromPageStore( 'page_latest', $flags );
2653 }
2654
2655 if ( !$this->mLatestID ) {
2656 $this->mLatestID = 0;
2657 }
2658
2659 return $this->mLatestID;
2660 }
2661
2662 /**
2663 * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
2664 *
2665 * This can be called on page insertion to allow loading of the new page_id without
2666 * having to create a new Title instance. Likewise with deletion.
2667 *
2668 * This is also used during page moves, to reflect the change in the relationship
2669 * between article ID and title text.
2670 *
2671 * @note This overrides Title::setContentModel()
2672 *
2673 * @param int|bool $id Page ID, 0 for non-existent, or false for "unknown" (lazy-load)
2674 */
2675 public function resetArticleID( $id ) {
2676 if ( $id === false ) {
2677 $this->mArticleID = -1;
2678 } else {
2679 $this->mArticleID = (int)$id;
2680 }
2681 $this->mRedirect = null;
2682 $this->mLength = -1;
2683 $this->mLatestID = false;
2684 $this->mContentModel = false;
2685 $this->mForcedContentModel = false;
2686 $this->mEstimateRevisions = null;
2687 $this->mPageLanguage = null;
2688 $this->mDbPageLanguage = false;
2689 $this->mIsBigDeletion = null;
2690
2691 $this->uncache();
2692 MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
2693 MediaWikiServices::getInstance()->getRestrictionStore()->flushRestrictions( $this );
2694 }
2695
2696 public static function clearCaches() {
2697 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2698 $linkCache->clear();
2699
2700 // Reset cached main page instance (T395214).
2701 self::$cachedMainPage = null;
2702
2703 $titleCache = self::getTitleCache();
2704 $titleCache->clear();
2705 }
2706
2707 /**
2708 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2709 *
2710 * @param string $text Containing title to capitalize
2711 * @param int $ns Namespace index, defaults to NS_MAIN
2712 * @return string Containing capitalized title
2713 */
2714 public static function capitalize( $text, $ns = NS_MAIN ) {
2715 $services = MediaWikiServices::getInstance();
2716 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
2717 return $services->getContentLanguage()->ucfirst( $text );
2718 } else {
2719 return $text;
2720 }
2721 }
2722
2723 /**
2724 * Secure and split - main initialisation function for this object
2725 *
2726 * Assumes that $text is urldecoded
2727 * and uses underscores, but not otherwise munged. This function
2728 * removes illegal characters, splits off the interwiki and
2729 * namespace prefixes, sets the other forms, and canonicalizes
2730 * everything.
2731 *
2732 * If this method returns normally, the Title is valid.
2733 *
2734 * @param string $text
2735 * @param int|null $defaultNamespace
2736 *
2737 * @throws MalformedTitleException On malformed titles
2738 */
2739 private function secureAndSplit( $text, $defaultNamespace = null ) {
2740 $defaultNamespace ??= self::DEFAULT_NAMESPACE;
2741
2742 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
2743 // the parsing code with Title, while avoiding massive refactoring.
2744 // @todo: get rid of secureAndSplit, refactor parsing code.
2745 // @note: getTitleParser() returns a TitleParser implementation which does not have a
2746 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
2747 /** @var MediaWikiTitleCodec $titleCodec */
2748 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
2749 '@phan-var MediaWikiTitleCodec $titleCodec';
2750 // MalformedTitleException can be thrown here
2751 $parts = $titleCodec->splitTitleString( $text, $defaultNamespace );
2752
2753 # Fill fields
2754 $this->setFragment( '#' . $parts['fragment'] );
2755 $this->mInterwiki = $parts['interwiki'];
2756 $this->mLocalInterwiki = $parts['local_interwiki'];
2757 $this->mNamespace = $parts['namespace'];
2758
2759 $this->mDbkeyform = $parts['dbkey'];
2760 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
2761 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
2762
2763 // splitTitleString() guarantees that this title is valid.
2764 $this->mIsValid = true;
2765
2766 # We already know that some pages won't be in the database!
2767 if ( $this->isExternal() || $this->isSpecialPage() || $this->mTextform === '' ) {
2768 $this->mArticleID = 0;
2769 }
2770 }
2771
2772 /**
2773 * Get an array of Title objects linking to this Title
2774 * Also stores the IDs in the link cache.
2775 *
2776 * WARNING: do not use this function on arbitrary user-supplied titles!
2777 * On heavily-used templates it will max out the memory.
2778 *
2779 * @param array $options May be FOR UPDATE
2780 * @param string $table Table name
2781 * @param string $prefix Fields prefix
2782 * @return Title[]
2783 */
2784 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
2785 if ( count( $options ) > 0 ) {
2786 $db = $this->getDbProvider()->getPrimaryDatabase();
2787 } else {
2788 $db = $this->getDbProvider()->getReplicaDatabase();
2789 }
2790
2791 $linksMigration = MediaWikiServices::getInstance()->getLinksMigration();
2792 if ( isset( $linksMigration::$mapping[$table] ) ) {
2793 $titleConds = $linksMigration->getLinksConditions( $table, $this );
2794 } else {
2795 $titleConds = [
2796 "{$prefix}_namespace" => $this->mNamespace,
2797 "{$prefix}_title" => $this->mDbkeyform
2798 ];
2799 }
2800
2801 $res = $db->newSelectQueryBuilder()
2802 ->select( LinkCache::getSelectFields() )
2803 ->from( $table )
2804 ->join( 'page', null, "{$prefix}_from=page_id" )
2805 ->where( $titleConds )
2806 ->options( $options )
2807 ->caller( __METHOD__ )
2808 ->fetchResultSet();
2809
2810 $retVal = [];
2811 if ( $res->numRows() ) {
2812 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2813 foreach ( $res as $row ) {
2814 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
2815 if ( $titleObj ) {
2816 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2817 $retVal[] = $titleObj;
2818 }
2819 }
2820 }
2821 return $retVal;
2822 }
2823
2824 /**
2825 * Get an array of Title objects using this Title as a template
2826 * Also stores the IDs in the link cache.
2827 *
2828 * WARNING: do not use this function on arbitrary user-supplied titles!
2829 * On heavily-used templates it will max out the memory.
2830 *
2831 * @param array $options Query option to Database::select()
2832 * @return Title[]
2833 */
2834 public function getTemplateLinksTo( $options = [] ) {
2835 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2836 }
2837
2838 /**
2839 * Get an array of Title objects linked from this Title
2840 * Also stores the IDs in the link cache.
2841 *
2842 * WARNING: do not use this function on arbitrary user-supplied titles!
2843 * On heavily-used templates it will max out the memory.
2844 *
2845 * @param array $options Query option to Database::select()
2846 * @param string $table Table name
2847 * @param string $prefix Fields prefix
2848 * @return Title[] List of Titles linking here
2849 */
2850 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
2851 $id = $this->getArticleID();
2852
2853 # If the page doesn't exist; there can't be any link from this page
2854 if ( !$id ) {
2855 return [];
2856 }
2857
2858 $db = $this->getDbProvider()->getReplicaDatabase();
2859 $linksMigration = MediaWikiServices::getInstance()->getLinksMigration();
2860
2861 $queryBuilder = $db->newSelectQueryBuilder();
2862 if ( isset( $linksMigration::$mapping[$table] ) ) {
2863 [ $blNamespace, $blTitle ] = $linksMigration->getTitleFields( $table );
2864 $linktargetQueryInfo = $linksMigration->getQueryInfo( $table );
2865 $queryBuilder->queryInfo( $linktargetQueryInfo );
2866 } else {
2867 $blNamespace = "{$prefix}_namespace";
2868 $blTitle = "{$prefix}_title";
2869 $queryBuilder->select( [ $blNamespace, $blTitle ] )
2870 ->from( $table );
2871 }
2872
2873 $pageQuery = WikiPage::getQueryInfo();
2874 $res = $queryBuilder
2875 ->where( [ "{$prefix}_from" => $id ] )
2876 ->leftJoin( 'page', null, [ "page_namespace=$blNamespace", "page_title=$blTitle" ] )
2877 ->fields( $pageQuery['fields'] )
2878 ->options( $options )
2879 ->caller( __METHOD__ )
2880 ->fetchResultSet();
2881
2882 $retVal = [];
2883 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2884 foreach ( $res as $row ) {
2885 if ( $row->page_id ) {
2886 $titleObj = self::newFromRow( $row );
2887 } else {
2888 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
2889 $linkCache->addBadLinkObj( $titleObj );
2890 }
2891 $retVal[] = $titleObj;
2892 }
2893
2894 return $retVal;
2895 }
2896
2897 /**
2898 * Get an array of Title objects used on this Title as a template
2899 * Also stores the IDs in the link cache.
2900 *
2901 * WARNING: do not use this function on arbitrary user-supplied titles!
2902 * On heavily-used templates it will max out the memory.
2903 *
2904 * @param array $options May be FOR UPDATE
2905 * @return Title[]
2906 */
2907 public function getTemplateLinksFrom( $options = [] ) {
2908 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
2909 }
2910
2911 /**
2912 * Locks the page row and check if this page is single revision redirect
2913 *
2914 * This updates the cached fields of this instance via Title::loadFromRow()
2915 *
2916 * @return bool
2917 */
2918 public function isSingleRevRedirect() {
2919 $dbw = $this->getDbProvider()->getPrimaryDatabase();
2920 $dbw->startAtomic( __METHOD__ );
2921 $pageStore = MediaWikiServices::getInstance()->getPageStore();
2922
2923 $row = $dbw->newSelectQueryBuilder()
2924 ->select( $pageStore->getSelectFields() )
2925 ->from( 'page' )
2926 ->where( $this->pageCond() )
2927 ->caller( __METHOD__ )->fetchRow();
2928 // Update the cached fields
2929 $this->loadFromRow( $row );
2930
2931 if ( $this->mRedirect && $this->mLatestID ) {
2932 $isSingleRevRedirect = !$dbw->newSelectQueryBuilder()
2933 ->select( '1' )
2934 ->forUpdate()
2935 ->from( 'revision' )
2936 ->where( [ 'rev_page' => $this->mArticleID, $dbw->expr( 'rev_id', '!=', (int)$this->mLatestID ) ] )
2937 ->caller( __METHOD__ )->fetchField();
2938 } else {
2939 $isSingleRevRedirect = false;
2940 }
2941
2942 $dbw->endAtomic( __METHOD__ );
2943
2944 return $isSingleRevRedirect;
2945 }
2946
2947 /**
2948 * Get categories to which this Title belongs and return an array of
2949 * categories' names.
2950 *
2951 * @return string[] Array of parents in the form:
2952 * $parent => $currentarticle
2953 */
2954 public function getParentCategories() {
2955 $data = [];
2956
2957 $titleKey = $this->getArticleID();
2958
2959 if ( $titleKey === 0 ) {
2960 return $data;
2961 }
2962
2963 $dbr = $this->getDbProvider()->getReplicaDatabase();
2964
2965 $res = $dbr->newSelectQueryBuilder()
2966 ->select( 'cl_to' )
2967 ->from( 'categorylinks' )
2968 ->where( [ 'cl_from' => $titleKey ] )
2969 ->caller( __METHOD__ )->fetchResultSet();
2970
2971 if ( $res->numRows() > 0 ) {
2972 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2973 foreach ( $res as $row ) {
2974 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
2975 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
2976 $this->getFullText();
2977 }
2978 }
2979 return $data;
2980 }
2981
2982 /**
2983 * Get a tree of parent categories
2984 *
2985 * @param array $children Array with the children in the keys, to check for circular refs
2986 * @return array Tree of parent categories
2987 */
2988 public function getParentCategoryTree( $children = [] ) {
2989 $stack = [];
2990 $parents = $this->getParentCategories();
2991
2992 if ( $parents ) {
2993 foreach ( $parents as $parent => $current ) {
2994 if ( array_key_exists( $parent, $children ) ) {
2995 # Circular reference
2996 $stack[$parent] = [];
2997 } else {
2998 $nt = self::newFromText( $parent );
2999 if ( $nt ) {
3000 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3001 }
3002 }
3003 }
3004 }
3005
3006 return $stack;
3007 }
3008
3009 /**
3010 * Get an associative array for selecting this title from
3011 * the "page" table
3012 *
3013 * @return array Array suitable for the $where parameter of DB::select()
3014 */
3015 public function pageCond() {
3016 if ( $this->mArticleID > 0 ) {
3017 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3018 return [ 'page_id' => $this->mArticleID ];
3019 } else {
3020 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3021 }
3022 }
3023
3024 /**
3025 * Check if this is a new page.
3026 *
3027 * @note This returns false if the page does not exist.
3028 * @param int $flags one of the READ_XXX constants.
3029 *
3030 * @return bool
3031 */
3032 public function isNewPage( $flags = IDBAccessObject::READ_NORMAL ) {
3033 // NOTE: we rely on PHP casting "0" to false here.
3034 return (bool)$this->getFieldFromPageStore( 'page_is_new', $flags );
3035 }
3036
3037 /**
3038 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3039 * @deprecated since 1.37 External callers shouldn't need to know about this.
3040 *
3041 * @return bool
3042 */
3043 public function isBigDeletion() {
3044 global $wgDeleteRevisionsLimit;
3045
3046 if ( !$wgDeleteRevisionsLimit ) {
3047 return false;
3048 }
3049
3050 if ( $this->mIsBigDeletion === null ) {
3051 $dbr = $this->getDbProvider()->getReplicaDatabase();
3052 $revCount = $dbr->newSelectQueryBuilder()
3053 ->select( '1' )
3054 ->from( 'revision' )
3055 ->where( [ 'rev_page' => $this->getArticleID() ] )
3056 ->limit( $wgDeleteRevisionsLimit + 1 )
3057 ->caller( __METHOD__ )->fetchRowCount();
3058
3059 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
3060 }
3061
3062 return $this->mIsBigDeletion;
3063 }
3064
3065 /**
3066 * Get the approximate revision count of this page.
3067 *
3068 * @return int
3069 */
3070 public function estimateRevisionCount() {
3071 if ( !$this->exists() ) {
3072 return 0;
3073 }
3074
3075 if ( $this->mEstimateRevisions === null ) {
3076 $dbr = $this->getDbProvider()->getReplicaDatabase();
3077 $this->mEstimateRevisions = $dbr->newSelectQueryBuilder()
3078 ->select( '*' )
3079 ->from( 'revision' )
3080 ->where( [ 'rev_page' => $this->getArticleID() ] )
3081 ->caller( __METHOD__ )
3082 ->estimateRowCount();
3083 }
3084
3085 return $this->mEstimateRevisions;
3086 }
3087
3088 /**
3089 * Compares with another Title.
3090 *
3091 * A Title object is considered equal to another Title if it has the same text,
3092 * the same interwiki prefix, and the same namespace.
3093 *
3094 * @note This is different from isSameLinkAs(), which also compares the fragment part,
3095 * and from isSamePageAs(), which takes into account the page ID.
3096 *
3097 * @phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
3098 * @param Title|object $other
3099 *
3100 * @return bool true if $other is a Title and refers to the same page.
3101 */
3102 public function equals( object $other ) {
3103 // NOTE: In contrast to isSameLinkAs(), this ignores the fragment part!
3104 // NOTE: In contrast to isSamePageAs(), this ignores the page ID!
3105 // NOTE: === is necessary for proper matching of number-like titles
3106 return $other instanceof Title
3107 && $this->getInterwiki() === $other->getInterwiki()
3108 && $this->getNamespace() === $other->getNamespace()
3109 && $this->getDBkey() === $other->getDBkey();
3110 }
3111
3112 /**
3113 * @inheritDoc
3114 * @since 1.36
3115 */
3116 public function isSamePageAs( PageReference $other ): bool {
3117 // NOTE: keep in sync with PageReferenceValue::isSamePageAs()!
3118 return $this->getWikiId() === $other->getWikiId()
3119 && $this->getNamespace() === $other->getNamespace()
3120 && $this->getDBkey() === $other->getDBkey();
3121 }
3122
3123 /**
3124 * Check if this title is a subpage of another title
3125 *
3126 * @param Title $title
3127 * @return bool
3128 */
3129 public function isSubpageOf( Title $title ) {
3130 return $this->mInterwiki === $title->mInterwiki
3131 && $this->mNamespace == $title->mNamespace
3132 && str_starts_with( $this->mDbkeyform, $title->mDbkeyform . '/' );
3133 }
3134
3135 /**
3136 * Check if page exists. For historical reasons, this function simply
3137 * checks for the existence of the title in the page table, and will
3138 * thus return false for interwiki links, special pages and the like.
3139 * If you want to know if a title can be meaningfully viewed, you should
3140 * probably call the isKnown() method instead.
3141 *
3142 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
3143 * @return bool
3144 */
3145 public function exists( $flags = 0 ): bool {
3146 $exists = $this->getArticleID( $flags ) != 0;
3147 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onTitleExists( $this, $exists );
3148 return $exists;
3149 }
3150
3151 /**
3152 * Should links to this title be shown as potentially viewable (i.e. as
3153 * "bluelinks"), even if there's no record by this title in the page
3154 * table?
3155 *
3156 * This function is semi-deprecated for public use, as well as somewhat
3157 * misleadingly named. You probably just want to call isKnown(), which
3158 * calls this function internally.
3159 *
3160 * (ISSUE: Most of these checks are cheap, but the file existence check
3161 * can potentially be quite expensive. Including it here fixes a lot of
3162 * existing code, but we might want to add an optional parameter to skip
3163 * it and any other expensive checks.)
3164 *
3165 * @return bool
3166 */
3167 public function isAlwaysKnown() {
3168 $isKnown = null;
3169
3170 $services = MediaWikiServices::getInstance();
3171 ( new HookRunner( $services->getHookContainer() ) )->onTitleIsAlwaysKnown( $this, $isKnown );
3172
3173 if ( $isKnown !== null ) {
3174 return $isKnown;
3175 }
3176
3177 if ( $this->isExternal() ) {
3178 return true; // any interwiki link might be viewable, for all we know
3179 }
3180
3181 switch ( $this->mNamespace ) {
3182 case NS_MEDIA:
3183 case NS_FILE:
3184 // file exists, possibly in a foreign repo
3185 return (bool)$services->getRepoGroup()->findFile( $this );
3186 case NS_SPECIAL:
3187 // valid special page
3188 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
3189 case NS_MAIN:
3190 // selflink, possibly with fragment
3191 return $this->mDbkeyform == '';
3192 case NS_MEDIAWIKI:
3193 // known system message
3194 return $this->hasSourceText() !== false;
3195 default:
3196 return false;
3197 }
3198 }
3199
3200 /**
3201 * Does this title refer to a page that can (or might) be meaningfully
3202 * viewed? In particular, this function may be used to determine if
3203 * links to the title should be rendered as "bluelinks" (as opposed to
3204 * "redlinks" to non-existent pages).
3205 * Adding something else to this function will cause inconsistency
3206 * since LinkHolderArray calls isAlwaysKnown() and does its own
3207 * page existence check.
3208 *
3209 * @return bool
3210 */
3211 public function isKnown() {
3212 return $this->isAlwaysKnown() || $this->exists();
3213 }
3214
3215 /**
3216 * Does this page have source text?
3217 *
3218 * @return bool
3219 */
3220 public function hasSourceText() {
3221 if ( $this->exists() ) {
3222 return true;
3223 }
3224
3225 if ( $this->mNamespace === NS_MEDIAWIKI ) {
3226 $services = MediaWikiServices::getInstance();
3227 // If the page doesn't exist but is a known system message, default
3228 // message content will be displayed, same for language subpages-
3229 // Use always content language to avoid loading hundreds of languages
3230 // to get the link color.
3231 $contLang = $services->getContentLanguage();
3232 [ $name, ] = $services->getMessageCache()->figureMessage(
3233 $contLang->lcfirst( $this->getText() )
3234 );
3235 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
3236 return $message->exists();
3237 }
3238
3239 return false;
3240 }
3241
3242 /**
3243 * Get the default (plain) message contents for a page that overrides an
3244 * interface message key.
3245 *
3246 * Primary use cases:
3247 *
3248 * - Article:
3249 * - Show default when viewing the page. The Article::getSubstituteContent
3250 * method displays the default message content, instead of the
3251 * 'noarticletext' placeholder message normally used.
3252 *
3253 * - EditPage:
3254 * - Title of edit page. When creating an interface message override,
3255 * the editor is told they are "Editing the page", instead of
3256 * "Creating the page". (EditPage::setHeaders)
3257 * - Edit notice. The 'translateinterface' edit notice is shown when creating
3258 * or editing an interface message override. (EditPage::showIntro)
3259 * - Opening the editor. The contents of the localisation message are used
3260 * as contents of the editor when creating a new page in the MediaWiki
3261 * namespace. This simplifies the process for editors when "changing"
3262 * an interface message by creating an override. (EditPage::getContentObject)
3263 * - Showing a diff. The left-hand side of a diff when an editor is
3264 * previewing their changes before saving the creation of a page in the
3265 * MediaWiki namespace. (EditPage::showDiff)
3266 * - Disallowing a save. When attempting to create a MediaWiki-namespace
3267 * page with the proposed content matching the interface message default,
3268 * the save is rejected, the same way we disallow blank pages from being
3269 * created. (EditPage using DefaultTextConstraint)
3270 *
3271 * - ApiEditPage:
3272 * - Default content, when using the 'prepend' or 'append' feature.
3273 *
3274 * - SkinTemplate:
3275 * - Label the create action as "Edit", if the page can be an override.
3276 *
3277 * @return string|false
3278 */
3279 public function getDefaultMessageText() {
3280 $message = $this->getDefaultSystemMessage();
3281
3282 return $message ? $message->plain() : false;
3283 }
3284
3285 /**
3286 * Same as getDefaultMessageText, but returns a Message object.
3287 *
3288 * @see ::getDefaultMessageText
3289 *
3290 * @return ?Message
3291 */
3292 public function getDefaultSystemMessage(): ?Message {
3293 if ( $this->mNamespace !== NS_MEDIAWIKI ) { // Just in case
3294 return null;
3295 }
3296
3297 [ $name, $lang ] = MediaWikiServices::getInstance()->getMessageCache()->figureMessage(
3298 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
3299 );
3300
3301 if ( wfMessage( $name )->inLanguage( $lang )->useDatabase( false )->exists() ) {
3302 return wfMessage( $name )->inLanguage( $lang );
3303 } else {
3304 return null;
3305 }
3306 }
3307
3308 /**
3309 * Updates page_touched for this page; called from LinksUpdate.php
3310 *
3311 * @param string|null $purgeTime [optional] TS_MW timestamp
3312 * @return bool True if the update succeeded
3313 */
3314 public function invalidateCache( $purgeTime = null ) {
3315 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
3316 return false;
3317 }
3318 if ( $this->mArticleID === 0 ) {
3319 // avoid gap locking if we know it's not there
3320 return true;
3321 }
3322
3323 $conds = $this->pageCond();
3324
3325 // Periodically recompute page_random (T309477). This mitigates bias on
3326 // Special:Random due deleted pages leaving "gaps" in the distribution.
3327 //
3328 // Optimization: Update page_random only for 10% of updates.
3329 // Optimization: Do this outside the main transaction to avoid locking for too long.
3330 // Optimization: Update page_random alongside page_touched to avoid extra database writes.
3331 DeferredUpdates::addUpdate(
3332 new AutoCommitUpdate(
3333 $this->getDbProvider()->getPrimaryDatabase(),
3334 __METHOD__,
3335 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
3336 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
3337 $update = $dbw->newUpdateQueryBuilder()
3338 ->update( 'page' )
3339 ->set( [ 'page_touched' => $dbTimestamp ] )
3340 ->where( $conds )
3341 ->andWhere( $dbw->expr( 'page_touched', '<', $dbTimestamp ) );
3342
3343 if ( mt_rand( 1, 10 ) === 1 ) {
3344 $update->andSet( [ 'page_random' => wfRandom() ] );
3345 }
3346
3347 $update->caller( $fname )->execute();
3348
3349 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
3350
3351 WikiModule::invalidateModuleCache(
3352 $this, null, null, $dbw->getDomainID() );
3353 }
3354 ),
3355 DeferredUpdates::PRESEND
3356 );
3357
3358 return true;
3359 }
3360
3361 /**
3362 * Update page_touched timestamps and send CDN purge messages for
3363 * pages linking to this title. May be sent to the job queue depending
3364 * on the number of links. Typically called on create and delete.
3365 */
3366 public function touchLinks() {
3367 $jobs = [];
3368 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
3369 $this,
3370 'pagelinks',
3371 [ 'causeAction' => 'page-touch' ]
3372 );
3373 if ( $this->mNamespace === NS_CATEGORY ) {
3374 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
3375 $this,
3376 'categorylinks',
3377 [ 'causeAction' => 'category-touch' ]
3378 );
3379 }
3380
3381 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
3382 }
3383
3384 /**
3385 * Get the last touched timestamp
3386 *
3387 * @param int $flags one of the READ_XXX constants.
3388 * @return string|false Last-touched timestamp
3389 */
3390 public function getTouched( int $flags = IDBAccessObject::READ_NORMAL ) {
3391 $touched = $this->getFieldFromPageStore( 'page_touched', $flags );
3392 return $touched ? MWTimestamp::convert( TS_MW, $touched ) : false;
3393 }
3394
3395 /**
3396 * Generate strings used for xml 'id' names in monobook tabs
3397 *
3398 * @param string $prepend Defaults to 'nstab-'
3399 * @return string XML 'id' name
3400 */
3401 public function getNamespaceKey( $prepend = 'nstab-' ) {
3402 // Gets the subject namespace of this title
3403 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
3404 $subjectNS = $nsInfo->getSubject( $this->mNamespace );
3405 // Prefer canonical namespace name for HTML IDs
3406 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
3407 if ( $namespaceKey === false ) {
3408 // Fallback to localised text
3409 $namespaceKey = $this->getSubjectNsText();
3410 }
3411 // Makes namespace key lowercase
3412 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
3413 // Uses main
3414 if ( $namespaceKey == '' ) {
3415 $namespaceKey = 'main';
3416 }
3417 // Changes file to image for backwards compatibility
3418 if ( $namespaceKey == 'file' ) {
3419 $namespaceKey = 'image';
3420 }
3421 return $prepend . $namespaceKey;
3422 }
3423
3424 /**
3425 * Get all extant redirects to this Title
3426 *
3427 * @param int|null $ns Single namespace to consider; null to consider all namespaces
3428 * @return Title[]
3429 */
3430 public function getRedirectsHere( $ns = null ) {
3431 $redirs = [];
3432
3433 $queryBuilder = $this->getDbProvider()->getReplicaDatabase()->newSelectQueryBuilder()
3434 ->select( [ 'page_namespace', 'page_title' ] )
3435 ->from( 'redirect' )
3436 ->join( 'page', null, 'rd_from = page_id' )
3437 ->where( [
3438 'rd_namespace' => $this->mNamespace,
3439 'rd_title' => $this->mDbkeyform,
3440 'rd_interwiki' => $this->isExternal() ? $this->mInterwiki : '',
3441 ] );
3442
3443 if ( $ns !== null ) {
3444 $queryBuilder->andWhere( [ 'page_namespace' => $ns ] );
3445 }
3446
3447 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
3448
3449 foreach ( $res as $row ) {
3450 $redirs[] = self::newFromRow( $row );
3451 }
3452 return $redirs;
3453 }
3454
3455 /**
3456 * Check if this Title is a valid redirect target
3457 *
3458 * @return bool
3459 */
3460 public function isValidRedirectTarget() {
3461 global $wgInvalidRedirectTargets;
3462
3463 if ( $this->isSpecialPage() ) {
3464 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
3465 foreach ( [ 'Userlogout', ...$wgInvalidRedirectTargets ] as $target ) {
3466 if ( $this->isSpecial( $target ) ) {
3467 return false;
3468 }
3469 }
3470 return true;
3471 }
3472
3473 // relative section links are not valid redirect targets (T278367)
3474 return $this->getDBkey() !== '' && $this->isValid();
3475 }
3476
3477 /**
3478 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
3479 *
3480 * @return bool
3481 */
3482 public function canUseNoindex() {
3483 global $wgExemptFromUserRobotsControl;
3484
3485 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
3486 MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
3487
3488 return !in_array( $this->mNamespace, $bannedNamespaces );
3489 }
3490
3491 /**
3492 * Returns the raw sort key to be used for categories, with the specified
3493 * prefix. This will be fed to Collation::getSortKey() to get a
3494 * binary sortkey that can be used for actual sorting.
3495 *
3496 * @param string $prefix The prefix to be used, specified using
3497 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
3498 * prefix.
3499 * @return string
3500 */
3501 public function getCategorySortkey( $prefix = '' ) {
3502 $unprefixed = $this->getText();
3503
3504 // Anything that uses this hook should only depend
3505 // on the Title object passed in, and should probably
3506 // tell the users to run updateCollations.php --force
3507 // in order to re-sort existing category relations.
3508 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
3509 ->onGetDefaultSortkey( $this, $unprefixed );
3510 if ( $prefix !== '' ) {
3511 # Separate with a line feed, so the unprefixed part is only used as
3512 # a tiebreaker when two pages have the exact same prefix.
3513 # In UCA, tab is the only character that can sort above LF
3514 # so we strip both of them from the original prefix.
3515 $prefix = strtr( $prefix, "\n\t", ' ' );
3516 return "$prefix\n$unprefixed";
3517 }
3518 return $unprefixed;
3519 }
3520
3521 /**
3522 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
3523 * to true in LocalSettings.php, otherwise returns null. If there is no language saved in
3524 * the database, it will return null.
3525 *
3526 * @param int $flags
3527 *
3528 * @return ?string
3529 */
3530 private function getDbPageLanguageCode( int $flags = 0 ): ?string {
3531 global $wgPageLanguageUseDB;
3532
3533 // check, if the page language could be saved in the database, and if so and
3534 // the value is not requested already, lookup the page language using PageStore
3535 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
3536 $this->mDbPageLanguage = $this->getFieldFromPageStore( 'page_lang', $flags ) ?: null;
3537 }
3538
3539 return $this->mDbPageLanguage ?: null;
3540 }
3541
3542 /**
3543 * Returns the Language object from the page language code saved in the database.
3544 * If $wgPageLanguageUseDB is set to false or there is no language saved in the database
3545 * or the language code in the database is invalid or unsupported, it will return null.
3546 *
3547 * @return Language|null
3548 */
3549 private function getDbPageLanguage(): ?Language {
3550 $languageCode = $this->getDbPageLanguageCode();
3551 if ( $languageCode === null ) {
3552 return null;
3553 }
3554 $services = MediaWikiServices::getInstance();
3555 if ( !$services->getLanguageNameUtils()->isKnownLanguageTag( $languageCode ) ) {
3556 return null;
3557 }
3558 return $services->getLanguageFactory()->getLanguage( $languageCode );
3559 }
3560
3561 /**
3562 * Get the language in which the content of this page is written in
3563 * wikitext. Defaults to content language, but in certain cases it can be
3564 * e.g. $wgLang (such as special pages, which are in the user language).
3565 *
3566 * @since 1.18
3567 * @return Language
3568 */
3569 public function getPageLanguage() {
3570 global $wgLanguageCode;
3571 if ( $this->isSpecialPage() ) {
3572 // special pages are in the user language
3573 return RequestContext::getMain()->getLanguage();
3574 }
3575
3576 // Checking if DB language is set
3577 $dbPageLanguage = $this->getDbPageLanguage();
3578 if ( $dbPageLanguage ) {
3579 return $dbPageLanguage;
3580 }
3581
3582 $services = MediaWikiServices::getInstance();
3583 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
3584 // Note that this may depend on user settings, so the cache should
3585 // be only per-request.
3586 // NOTE: ContentHandler::getPageLanguage() may need to load the
3587 // content to determine the page language!
3588 // Checking $wgLanguageCode hasn't changed for the benefit of unit
3589 // tests.
3590 $contentHandler = $services->getContentHandlerFactory()
3591 ->getContentHandler( $this->getContentModel() );
3592 $langObj = $contentHandler->getPageLanguage( $this );
3593 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
3594 } else {
3595 $langObj = $services->getLanguageFactory()
3596 ->getLanguage( $this->mPageLanguage[0] );
3597 }
3598
3599 return $langObj;
3600 }
3601
3602 /**
3603 * Get the language in which the content of this page is written when
3604 * viewed by user. Defaults to content language, but in certain cases it can be
3605 * e.g. the user language (such as special pages).
3606 *
3607 * @deprecated since 1.42 Use ParserOutput::getLanguage instead. See also OutputPage::getContLangForJS.
3608 * Hard-deprecated since 1.43.
3609 * @since 1.20
3610 * @return Language
3611 */
3612 public function getPageViewLanguage() {
3613 wfDeprecated( __METHOD__, '1.42' );
3614 $services = MediaWikiServices::getInstance();
3615
3616 if ( $this->isSpecialPage() ) {
3617 // If the user chooses a variant, the content is actually
3618 // in a language whose code is the variant code.
3619 $userLang = RequestContext::getMain()->getLanguage();
3620 $variant = $this->getLanguageConverter( $userLang )->getPreferredVariant();
3621 if ( $userLang->getCode() !== $variant ) {
3622 return $services->getLanguageFactory()
3623 ->getLanguage( $variant );
3624 }
3625
3626 return $userLang;
3627 }
3628
3629 // Checking if DB language is set
3630 $pageLang = $this->getDbPageLanguage();
3631 if ( $pageLang ) {
3632 $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
3633 if ( $pageLang->getCode() !== $variant ) {
3634 return $services->getLanguageFactory()
3635 ->getLanguage( $variant );
3636 }
3637
3638 return $pageLang;
3639 }
3640
3641 // @note Can't be cached persistently, depends on user settings.
3642 // @note ContentHandler::getPageViewLanguage() may need to load the
3643 // content to determine the page language!
3644 $contentHandler = $services->getContentHandlerFactory()
3645 ->getContentHandler( $this->getContentModel() );
3646 $pageLang = $contentHandler->getPageViewLanguage( $this );
3647 return $pageLang;
3648 }
3649
3650 /**
3651 * Get a list of rendered edit notices for this page.
3652 *
3653 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
3654 * they will already be wrapped in paragraphs.
3655 *
3656 * @since 1.21
3657 * @param int $oldid Revision ID that's being edited
3658 * @return string[]
3659 */
3660 public function getEditNotices( $oldid = 0 ) {
3661 $notices = [];
3662
3663 $editnotice_base = 'editnotice-' . $this->mNamespace;
3664 // Optional notice for the entire namespace
3665 $messages = [ $editnotice_base => 'namespace' ];
3666
3667 if (
3668 MediaWikiServices::getInstance()->getNamespaceInfo()->
3669 hasSubpages( $this->mNamespace )
3670 ) {
3671 // Optional notice for page itself and any parent page
3672 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
3673 $editnotice_base .= '-' . $part;
3674 $messages[$editnotice_base] = 'base';
3675 }
3676 } else {
3677 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
3678 $messages[$editnotice_base . '-' . strtr( $this->mDbkeyform, '/', '-' )] = 'page';
3679 }
3680
3681 foreach ( $messages as $editnoticeText => $class ) {
3682 // The following messages are used here:
3683 // * editnotice-0
3684 // * editnotice-0-Title
3685 // * editnotice-0-Title-Subpage
3686 // * editnotice-…
3687 $msg = wfMessage( $editnoticeText )->page( $this );
3688 if ( $msg->exists() ) {
3689 $html = $msg->parseAsBlock();
3690 // Edit notices may have complex logic, but output nothing (T91715)
3691 if ( trim( $html ) !== '' ) {
3692 $notices[$editnoticeText] = Html::rawElement(
3693 'div',
3694 [ 'class' => [
3695 'mw-editnotice',
3696 // The following classes are used here:
3697 // * mw-editnotice-namespace
3698 // * mw-editnotice-base
3699 // * mw-editnotice-page
3700 "mw-editnotice-$class",
3701 // The following classes are used here:
3702 // * mw-editnotice-0
3703 // * mw-editnotice-…
3704 Sanitizer::escapeClass( "mw-$editnoticeText" )
3705 ] ],
3706 $html
3707 );
3708 }
3709 }
3710 }
3711
3712 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
3713 ->onTitleGetEditNotices( $this, $oldid, $notices );
3714 return $notices;
3715 }
3716
3717 /**
3718 * @param string $field
3719 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
3720 * @return string|false
3721 */
3722 private function getFieldFromPageStore( $field, $flags ) {
3723 $pageStore = MediaWikiServices::getInstance()->getPageStore();
3724
3725 if ( !in_array( $field, $pageStore->getSelectFields(), true ) ) {
3726 throw new InvalidArgumentException( "Unknown field: $field" );
3727 }
3728
3729 if ( $flags === IDBAccessObject::READ_NORMAL && $this->mArticleID === 0 ) {
3730 // page does not exist
3731 return false;
3732 }
3733
3734 if ( !$this->canExist() ) {
3735 return false;
3736 }
3737
3738 $page = $pageStore->getPageByReference( $this, $flags );
3739
3740 if ( $page instanceof PageStoreRecord ) {
3741 return $page->getField( $field );
3742 } else {
3743 // The page record failed to load, remember the page as non-existing.
3744 // Note that this can happen even if a page ID was known before under some
3745 // rare circumstances, if this method is called with the READ_LATEST bit set
3746 // and the page has been deleted since the ID had initially been determined.
3747 $this->mArticleID = 0;
3748 return false;
3749 }
3750 }
3751
3752 /**
3753 * @return array
3754 */
3755 public function __sleep() {
3756 return [
3757 'mNamespace',
3758 'mDbkeyform',
3759 'mFragment',
3760 'mInterwiki',
3761 'mLocalInterwiki',
3762 ];
3763 }
3764
3765 public function __wakeup() {
3766 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
3767 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3768 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3769 }
3770
3771 public function __clone() {
3772 $this->mInstanceCacheKey = null;
3773 }
3774
3775 /**
3776 * Returns false to indicate that this Title belongs to the local wiki.
3777 *
3778 * @note The behavior of this method is considered undefined for interwiki links.
3779 * At the moment, this method always returns false. But this may change in the future.
3780 *
3781 * @since 1.36
3782 * @return string|false Always self::LOCAL
3783 */
3784 public function getWikiId() {
3785 return self::LOCAL;
3786 }
3787
3788 /**
3789 * Returns the page ID.
3790 *
3791 * If this ID is 0, this means the page does not exist.
3792 *
3793 * @see getArticleID()
3794 * @since 1.36, since 1.35.6 as an alias of getArticleID()
3795 *
3796 * @param string|false $wikiId The wiki ID expected by the caller.
3797 *
3798 * @throws PreconditionException if this Title instance does not represent a proper page,
3799 * that is, if it is a section link, interwiki link, link to a special page, or such.
3800 * @throws PreconditionException if $wikiId is not false.
3801 *
3802 * @return int
3803 */
3804 public function getId( $wikiId = self::LOCAL ): int {
3805 $this->assertWiki( $wikiId );
3806 $this->assertProperPage();
3807 return $this->getArticleID();
3808 }
3809
3810 /**
3811 * Code that requires this Title to be a "proper page" in the sense
3812 * defined by PageIdentity should call this method.
3813 *
3814 * For the purpose of the Title class, a proper page is one that can
3815 * exist in the page table. That is, a Title represents a proper page
3816 * if canExist() returns true.
3817 *
3818 * @see canExist()
3819 *
3820 * @throws PreconditionException
3821 */
3822 private function assertProperPage() {
3823 Assert::precondition(
3824 $this->canExist(),
3825 'This Title instance does not represent a proper page, but merely a link target.'
3826 );
3827 }
3828
3829 /**
3830 * Returns the page represented by this Title as a ProperPageIdentity.
3831 * The ProperPageIdentity returned by this method is guaranteed to be immutable.
3832 * If this Title does not represent a proper page, an exception is thrown.
3833 *
3834 * It is preferred to use this method rather than using the Title as a PageIdentity directly.
3835 *
3836 * @return ProperPageIdentity
3837 * @throws PreconditionException if the page is not a proper page, that is, if it is a section
3838 * link, interwiki link, link to a special page, or such.
3839 * @since 1.36
3840 */
3841 public function toPageIdentity(): ProperPageIdentity {
3842 // TODO: replace individual member fields with a PageIdentityValue that is always present
3843
3844 $this->assertProperPage();
3845
3846 return new PageIdentityValue(
3847 $this->getId(),
3848 $this->getNamespace(),
3849 $this->getDBkey(),
3850 $this->getWikiId()
3851 );
3852 }
3853
3854 /**
3855 * Returns the page represented by this Title as a ProperPageRecord.
3856 * The PageRecord returned by this method is guaranteed to be immutable,
3857 * the page is guaranteed to exist.
3858 *
3859 * @note For now, this method queries the database on every call.
3860 * @since 1.36
3861 *
3862 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
3863 *
3864 * @return ExistingPageRecord
3865 * @throws PreconditionException if the page does not exist, or is not a proper page,
3866 * that is, if it is a section link, interwiki link, link to a special page, or such.
3867 */
3868 public function toPageRecord( $flags = 0 ): ExistingPageRecord {
3869 // TODO: Cache this? Construct is more efficiently?
3870
3871 $this->assertProperPage();
3872
3873 Assert::precondition(
3874 $this->exists( $flags ),
3875 'This Title instance does not represent an existing page: ' . $this
3876 );
3877
3878 return new PageStoreRecord(
3879 (object)[
3880 'page_id' => $this->getArticleID( $flags ),
3881 'page_namespace' => $this->getNamespace(),
3882 'page_title' => $this->getDBkey(),
3883 'page_wiki_id' => $this->getWikiId(),
3884 'page_latest' => $this->getLatestRevID( $flags ),
3885 'page_is_new' => $this->isNewPage( $flags ),
3886 'page_is_redirect' => $this->isRedirect( $flags ),
3887 'page_touched' => $this->getTouched( $flags ),
3888 'page_lang' => $this->getDbPageLanguageCode( $flags ),
3889 ],
3890 PageIdentity::LOCAL
3891 );
3892 }
3893
3894 }
3895
3896 /** @deprecated class alias since 1.40 */
3897 class_alias( Title::class, 'Title' );