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