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