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