Merge "Remove Revision::getRevisionText from migrateArchiveText"
[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\Revision\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(). Note that the new method will
1565 * throw if asked for the talk page of a section-only link, or of an interwiki
1566 * link.
1567 * @return Title The object for the talk page
1568 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1569 * or because it's a relative link, or an interwiki link.
1570 */
1571 public function getTalkPage() {
1572 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1573 // Instead of failing on invalid titles, let's just log the issue for now.
1574 // See the discussion on T227817.
1575
1576 // Is this the same title?
1577 $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
1578 if ( $this->mNamespace == $talkNS ) {
1579 return $this;
1580 }
1581
1582 $title = self::makeTitle( $talkNS, $this->mDbkeyform );
1583
1584 $this->warnIfPageCannotExist( $title, __METHOD__ );
1585
1586 return $title;
1587 // TODO: replace the above with the code below:
1588 // return self::castFromLinkTarget(
1589 // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1590 }
1591
1592 /**
1593 * Get a Title object associated with the talk page of this article,
1594 * if such a talk page can exist.
1595 *
1596 * @since 1.30
1597 *
1598 * @return Title|null The object for the talk page,
1599 * or null if no associated talk page can exist, according to canHaveTalkPage().
1600 */
1601 public function getTalkPageIfDefined() {
1602 if ( !$this->canHaveTalkPage() ) {
1603 return null;
1604 }
1605
1606 return $this->getTalkPage();
1607 }
1608
1609 /**
1610 * Get a title object associated with the subject page of this
1611 * talk page
1612 *
1613 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1614 * @return Title The object for the subject page
1615 */
1616 public function getSubjectPage() {
1617 // Is this the same title?
1618 $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
1619 ->getSubject( $this->mNamespace );
1620 if ( $this->mNamespace == $subjectNS ) {
1621 return $this;
1622 }
1623 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1624 // Instead of failing on invalid titles, let's just log the issue for now.
1625 // See the discussion on T227817.
1626 $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
1627
1628 $this->warnIfPageCannotExist( $title, __METHOD__ );
1629
1630 return $title;
1631 // TODO: replace the above with the code below:
1632 // return self::castFromLinkTarget(
1633 // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1634 }
1635
1636 /**
1637 * @param Title $title
1638 * @param string $method
1639 *
1640 * @return bool whether a warning was issued
1641 */
1642 private function warnIfPageCannotExist( Title $title, $method ) {
1643 if ( $this->getText() == '' ) {
1644 wfLogWarning(
1645 $method . ': called on empty title ' . $this->getFullText() . ', returning '
1646 . $title->getFullText()
1647 );
1648
1649 return true;
1650 }
1651
1652 if ( $this->getInterwiki() !== '' ) {
1653 wfLogWarning(
1654 $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1655 . $title->getFullText()
1656 );
1657
1658 return true;
1659 }
1660
1661 return false;
1662 }
1663
1664 /**
1665 * Get the other title for this page, if this is a subject page
1666 * get the talk page, if it is a subject page get the talk page
1667 *
1668 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1669 * @since 1.25
1670 * @throws MWException If the page doesn't have an other page
1671 * @return Title
1672 */
1673 public function getOtherPage() {
1674 // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1675 // until their semantics has become exactly the same.
1676 // See the discussion on T227817.
1677 if ( $this->isSpecialPage() ) {
1678 throw new MWException( 'Special pages cannot have other pages' );
1679 }
1680 if ( $this->isTalkPage() ) {
1681 return $this->getSubjectPage();
1682 } else {
1683 if ( !$this->canHaveTalkPage() ) {
1684 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1685 }
1686 return $this->getTalkPage();
1687 }
1688 // TODO: replace the above with the code below:
1689 // return self::castFromLinkTarget(
1690 // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1691 }
1692
1693 /**
1694 * Get the default namespace index, for when there is no namespace
1695 *
1696 * @return int Default namespace index
1697 */
1698 public function getDefaultNamespace() {
1699 return $this->mDefaultNamespace;
1700 }
1701
1702 /**
1703 * Get the Title fragment (i.e.\ the bit after the #) in text form
1704 *
1705 * Use Title::hasFragment to check for a fragment
1706 *
1707 * @return string Title fragment
1708 */
1709 public function getFragment() {
1710 return $this->mFragment;
1711 }
1712
1713 /**
1714 * Check if a Title fragment is set
1715 *
1716 * @return bool
1717 * @since 1.23
1718 */
1719 public function hasFragment() {
1720 return $this->mFragment !== '';
1721 }
1722
1723 /**
1724 * Get the fragment in URL form, including the "#" character if there is one
1725 *
1726 * @return string Fragment in URL form
1727 */
1728 public function getFragmentForURL() {
1729 if ( !$this->hasFragment() ) {
1730 return '';
1731 } elseif ( $this->isExternal() ) {
1732 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1733 // so we treat it like a local interwiki.
1734 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1735 if ( $interwiki && !$interwiki->isLocal() ) {
1736 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1737 }
1738 }
1739
1740 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1741 }
1742
1743 /**
1744 * Set the fragment for this title. Removes the first character from the
1745 * specified fragment before setting, so it assumes you're passing it with
1746 * an initial "#".
1747 *
1748 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1749 * or Title::createFragmentTarget().
1750 * Still in active use privately.
1751 *
1752 * @private
1753 * @param string $fragment Text
1754 */
1755 public function setFragment( $fragment ) {
1756 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1757 }
1758
1759 /**
1760 * Creates a new Title for a different fragment of the same page.
1761 *
1762 * @since 1.27
1763 * @param string $fragment
1764 * @return Title
1765 */
1766 public function createFragmentTarget( $fragment ) {
1767 return self::makeTitle(
1768 $this->mNamespace,
1769 $this->getText(),
1770 $fragment,
1771 $this->mInterwiki
1772 );
1773 }
1774
1775 /**
1776 * Prefix some arbitrary text with the namespace or interwiki prefix
1777 * of this object
1778 *
1779 * @param string $name The text
1780 * @return string The prefixed text
1781 */
1782 private function prefix( $name ) {
1783 $p = '';
1784 if ( $this->isExternal() ) {
1785 $p = $this->mInterwiki . ':';
1786 }
1787
1788 if ( $this->mNamespace != 0 ) {
1789 $nsText = $this->getNsText();
1790
1791 if ( $nsText === false ) {
1792 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1793 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1794 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1795 }
1796
1797 $p .= $nsText . ':';
1798 }
1799 return $p . $name;
1800 }
1801
1802 /**
1803 * Get the prefixed database key form
1804 *
1805 * @return string The prefixed title, with underscores and
1806 * any interwiki and namespace prefixes
1807 */
1808 public function getPrefixedDBkey() {
1809 $s = $this->prefix( $this->mDbkeyform );
1810 $s = strtr( $s, ' ', '_' );
1811 return $s;
1812 }
1813
1814 /**
1815 * Get the prefixed title with spaces.
1816 * This is the form usually used for display
1817 *
1818 * @return string The prefixed title, with spaces
1819 */
1820 public function getPrefixedText() {
1821 if ( $this->prefixedText === null ) {
1822 $s = $this->prefix( $this->mTextform );
1823 $s = strtr( $s, '_', ' ' );
1824 $this->prefixedText = $s;
1825 }
1826 return $this->prefixedText;
1827 }
1828
1829 /**
1830 * Return a string representation of this title
1831 *
1832 * @return string Representation of this title
1833 */
1834 public function __toString() {
1835 return $this->getPrefixedText();
1836 }
1837
1838 /**
1839 * Get the prefixed title with spaces, plus any fragment
1840 * (part beginning with '#')
1841 *
1842 * @return string The prefixed title, with spaces and the fragment, including '#'
1843 */
1844 public function getFullText() {
1845 $text = $this->getPrefixedText();
1846 if ( $this->hasFragment() ) {
1847 $text .= '#' . $this->mFragment;
1848 }
1849 return $text;
1850 }
1851
1852 /**
1853 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1854 *
1855 * @note the return value may contain trailing whitespace and is thus
1856 * not safe for use with makeTitle or TitleValue.
1857 *
1858 * @par Example:
1859 * @code
1860 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1861 * # returns: 'Foo'
1862 * @endcode
1863 *
1864 * @return string Root name
1865 * @since 1.20
1866 */
1867 public function getRootText() {
1868 if (
1869 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1870 hasSubpages( $this->mNamespace )
1871 || strtok( $this->getText(), '/' ) === false
1872 ) {
1873 return $this->getText();
1874 }
1875
1876 return strtok( $this->getText(), '/' );
1877 }
1878
1879 /**
1880 * Get the root page name title, i.e. the leftmost part before any slashes
1881 *
1882 * @par Example:
1883 * @code
1884 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1885 * # returns: Title{User:Foo}
1886 * @endcode
1887 *
1888 * @return Title Root title
1889 * @since 1.20
1890 */
1891 public function getRootTitle() {
1892 $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1893 Assert::postcondition(
1894 $title !== null,
1895 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1896 );
1897 return $title;
1898 }
1899
1900 /**
1901 * Get the base page name without a namespace, i.e. the part before the subpage name
1902 *
1903 * @note the return value may contain trailing whitespace and is thus
1904 * not safe for use with makeTitle or TitleValue.
1905 *
1906 * @par Example:
1907 * @code
1908 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1909 * # returns: 'Foo/Bar'
1910 * @endcode
1911 *
1912 * @return string Base name
1913 */
1914 public function getBaseText() {
1915 $text = $this->getText();
1916 if (
1917 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1918 hasSubpages( $this->mNamespace )
1919 ) {
1920 return $text;
1921 }
1922
1923 $lastSlashPos = strrpos( $text, '/' );
1924 // Don't discard the real title if there's no subpage involved
1925 if ( $lastSlashPos === false ) {
1926 return $text;
1927 }
1928
1929 return substr( $text, 0, $lastSlashPos );
1930 }
1931
1932 /**
1933 * Get the base page name title, i.e. the part before the subpage name.
1934 *
1935 * @par Example:
1936 * @code
1937 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1938 * # returns: Title{User:Foo/Bar}
1939 * @endcode
1940 *
1941 * @return Title Base title
1942 * @since 1.20
1943 */
1944 public function getBaseTitle() {
1945 $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
1946 Assert::postcondition(
1947 $title !== null,
1948 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1949 );
1950 return $title;
1951 }
1952
1953 /**
1954 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1955 *
1956 * @par Example:
1957 * @code
1958 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1959 * # returns: "Baz"
1960 * @endcode
1961 *
1962 * @return string Subpage name
1963 */
1964 public function getSubpageText() {
1965 if (
1966 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1967 hasSubpages( $this->mNamespace )
1968 ) {
1969 return $this->mTextform;
1970 }
1971 $parts = explode( '/', $this->mTextform );
1972 return $parts[count( $parts ) - 1];
1973 }
1974
1975 /**
1976 * Get the title for a subpage of the current page
1977 *
1978 * @par Example:
1979 * @code
1980 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1981 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1982 * @endcode
1983 *
1984 * @param string $text The subpage name to add to the title
1985 * @return Title|null Subpage title, or null on an error
1986 * @since 1.20
1987 */
1988 public function getSubpage( $text ) {
1989 return self::makeTitleSafe(
1990 $this->mNamespace,
1991 $this->getText() . '/' . $text,
1992 '',
1993 $this->mInterwiki
1994 );
1995 }
1996
1997 /**
1998 * Get a URL-encoded form of the subpage text
1999 *
2000 * @return string URL-encoded subpage name
2001 */
2002 public function getSubpageUrlForm() {
2003 $text = $this->getSubpageText();
2004 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
2005 return $text;
2006 }
2007
2008 /**
2009 * Get a URL-encoded title (not an actual URL) including interwiki
2010 *
2011 * @return string The URL-encoded form
2012 */
2013 public function getPrefixedURL() {
2014 $s = $this->prefix( $this->mDbkeyform );
2015 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2016 return $s;
2017 }
2018
2019 /**
2020 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
2021 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
2022 * second argument named variant. This was deprecated in favor
2023 * of passing an array of option with a "variant" key
2024 * Once $query2 is removed for good, this helper can be dropped
2025 * and the wfArrayToCgi moved to getLocalURL();
2026 *
2027 * @since 1.19 (r105919)
2028 * @param array|string $query
2029 * @param string|string[]|bool $query2
2030 * @return string
2031 */
2032 private static function fixUrlQueryArgs( $query, $query2 = false ) {
2033 if ( $query2 !== false ) {
2034 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
2035 "method called with a second parameter is deprecated. Add your " .
2036 "parameter to an array passed as the first parameter.", "1.19" );
2037 }
2038 if ( is_array( $query ) ) {
2039 $query = wfArrayToCgi( $query );
2040 }
2041 if ( $query2 ) {
2042 if ( is_string( $query2 ) ) {
2043 // $query2 is a string, we will consider this to be
2044 // a deprecated $variant argument and add it to the query
2045 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
2046 } else {
2047 $query2 = wfArrayToCgi( $query2 );
2048 }
2049 // If we have $query content add a & to it first
2050 if ( $query ) {
2051 $query .= '&';
2052 }
2053 // Now append the queries together
2054 $query .= $query2;
2055 }
2056 return $query;
2057 }
2058
2059 /**
2060 * Get a real URL referring to this title, with interwiki link and
2061 * fragment
2062 *
2063 * @see self::getLocalURL for the arguments.
2064 * @see wfExpandUrl
2065 * @param string|array $query
2066 * @param string|string[]|bool $query2
2067 * @param string|int|null $proto Protocol type to use in URL
2068 * @return string The URL
2069 */
2070 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
2071 $query = self::fixUrlQueryArgs( $query, $query2 );
2072
2073 # Hand off all the decisions on urls to getLocalURL
2074 $url = $this->getLocalURL( $query );
2075
2076 # Expand the url to make it a full url. Note that getLocalURL has the
2077 # potential to output full urls for a variety of reasons, so we use
2078 # wfExpandUrl instead of simply prepending $wgServer
2079 $url = wfExpandUrl( $url, $proto );
2080
2081 # Finally, add the fragment.
2082 $url .= $this->getFragmentForURL();
2083 // Avoid PHP 7.1 warning from passing $this by reference
2084 $titleRef = $this;
2085 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
2086 return $url;
2087 }
2088
2089 /**
2090 * Get a url appropriate for making redirects based on an untrusted url arg
2091 *
2092 * This is basically the same as getFullUrl(), but in the case of external
2093 * interwikis, we send the user to a landing page, to prevent possible
2094 * phishing attacks and the like.
2095 *
2096 * @note Uses current protocol by default, since technically relative urls
2097 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2098 * places where the url gets cached, as might pollute between
2099 * https and non-https users.
2100 * @see self::getLocalURL for the arguments.
2101 * @param array|string $query
2102 * @param string $proto Protocol type to use in URL
2103 * @return string A url suitable to use in an HTTP location header.
2104 */
2105 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2106 $target = $this;
2107 if ( $this->isExternal() ) {
2108 $target = SpecialPage::getTitleFor(
2109 'GoToInterwiki',
2110 $this->getPrefixedDBkey()
2111 );
2112 }
2113 return $target->getFullURL( $query, false, $proto );
2114 }
2115
2116 /**
2117 * Get a URL with no fragment or server name (relative URL) from a Title object.
2118 * If this page is generated with action=render, however,
2119 * $wgServer is prepended to make an absolute URL.
2120 *
2121 * @see self::getFullURL to always get an absolute URL.
2122 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2123 * valid to link, locally, to the current Title.
2124 * @see self::newFromText to produce a Title object.
2125 *
2126 * @param string|array $query An optional query string,
2127 * not used for interwiki links. Can be specified as an associative array as well,
2128 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2129 * Some query patterns will trigger various shorturl path replacements.
2130 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2131 * be an array. If a string is passed it will be interpreted as a deprecated
2132 * variant argument and urlencoded into a variant= argument.
2133 * This second query argument will be added to the $query
2134 * The second parameter is deprecated since 1.19. Pass it as a key,value
2135 * pair in the first parameter array instead.
2136 *
2137 * @return string String of the URL.
2138 */
2139 public function getLocalURL( $query = '', $query2 = false ) {
2140 global $wgArticlePath, $wgScript, $wgServer, $wgRequest, $wgMainPageIsDomainRoot;
2141
2142 $query = self::fixUrlQueryArgs( $query, $query2 );
2143
2144 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2145 if ( $interwiki ) {
2146 $namespace = $this->getNsText();
2147 if ( $namespace != '' ) {
2148 # Can this actually happen? Interwikis shouldn't be parsed.
2149 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2150 $namespace .= ':';
2151 }
2152 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2153 $url = wfAppendQuery( $url, $query );
2154 } else {
2155 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2156 if ( $query == '' ) {
2157 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2158 // Avoid PHP 7.1 warning from passing $this by reference
2159 $titleRef = $this;
2160 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2161 } else {
2162 global $wgVariantArticlePath, $wgActionPaths;
2163 $url = false;
2164 $matches = [];
2165
2166 $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
2167
2168 if ( $articlePaths
2169 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2170 ) {
2171 $action = urldecode( $matches[2] );
2172 if ( isset( $articlePaths[$action] ) ) {
2173 $query = $matches[1];
2174 if ( isset( $matches[4] ) ) {
2175 $query .= $matches[4];
2176 }
2177 $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2178 if ( $query != '' ) {
2179 $url = wfAppendQuery( $url, $query );
2180 }
2181 }
2182 }
2183
2184 if ( $url === false
2185 && $wgVariantArticlePath
2186 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2187 && $this->getPageLanguage()->equals(
2188 MediaWikiServices::getInstance()->getContentLanguage() )
2189 && $this->getPageLanguage()->hasVariants()
2190 ) {
2191 $variant = urldecode( $matches[1] );
2192 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2193 // Only do the variant replacement if the given variant is a valid
2194 // variant for the page's language.
2195 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2196 $url = str_replace( '$1', $dbkey, $url );
2197 }
2198 }
2199
2200 if ( $url === false ) {
2201 if ( $query == '-' ) {
2202 $query = '';
2203 }
2204 $url = "{$wgScript}?title={$dbkey}&{$query}";
2205 }
2206 }
2207 // Avoid PHP 7.1 warning from passing $this by reference
2208 $titleRef = $this;
2209 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2210
2211 // @todo FIXME: This causes breakage in various places when we
2212 // actually expected a local URL and end up with dupe prefixes.
2213 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2214 $url = $wgServer . $url;
2215 }
2216 }
2217
2218 if ( $wgMainPageIsDomainRoot && $this->isMainPage() && $query === '' ) {
2219 return '/';
2220 }
2221
2222 // Avoid PHP 7.1 warning from passing $this by reference
2223 $titleRef = $this;
2224 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2225 return $url;
2226 }
2227
2228 /**
2229 * Get a URL that's the simplest URL that will be valid to link, locally,
2230 * to the current Title. It includes the fragment, but does not include
2231 * the server unless action=render is used (or the link is external). If
2232 * there's a fragment but the prefixed text is empty, we just return a link
2233 * to the fragment.
2234 *
2235 * The result obviously should not be URL-escaped, but does need to be
2236 * HTML-escaped if it's being output in HTML.
2237 *
2238 * @param string|string[] $query
2239 * @param bool $query2
2240 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2241 * or false (default) for no expansion
2242 * @see self::getLocalURL for the arguments.
2243 * @return string The URL
2244 */
2245 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2246 if ( $this->isExternal() || $proto !== false ) {
2247 $ret = $this->getFullURL( $query, $query2, $proto );
2248 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2249 $ret = $this->getFragmentForURL();
2250 } else {
2251 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2252 }
2253 return $ret;
2254 }
2255
2256 /**
2257 * Get the URL form for an internal link.
2258 * - Used in various CDN-related code, in case we have a different
2259 * internal hostname for the server from the exposed one.
2260 *
2261 * This uses $wgInternalServer to qualify the path, or $wgServer
2262 * if $wgInternalServer is not set. If the server variable used is
2263 * protocol-relative, the URL will be expanded to http://
2264 *
2265 * @see self::getLocalURL for the arguments.
2266 * @param string|array $query
2267 * @param string|bool $query2 Deprecated
2268 * @return string The URL
2269 */
2270 public function getInternalURL( $query = '', $query2 = false ) {
2271 global $wgInternalServer, $wgServer;
2272 $query = self::fixUrlQueryArgs( $query, $query2 );
2273 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2274 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2275 // Avoid PHP 7.1 warning from passing $this by reference
2276 $titleRef = $this;
2277 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2278 return $url;
2279 }
2280
2281 /**
2282 * Get the URL for a canonical link, for use in things like IRC and
2283 * e-mail notifications. Uses $wgCanonicalServer and the
2284 * GetCanonicalURL hook.
2285 *
2286 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2287 *
2288 * @see self::getLocalURL for the arguments.
2289 * @param string|array $query
2290 * @param string|bool $query2 Deprecated
2291 * @return string The URL
2292 * @since 1.18
2293 */
2294 public function getCanonicalURL( $query = '', $query2 = false ) {
2295 $query = self::fixUrlQueryArgs( $query, $query2 );
2296 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2297 // Avoid PHP 7.1 warning from passing $this by reference
2298 $titleRef = $this;
2299 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2300 return $url;
2301 }
2302
2303 /**
2304 * Get the edit URL for this Title
2305 *
2306 * @return string The URL, or a null string if this is an interwiki link
2307 */
2308 public function getEditURL() {
2309 if ( $this->isExternal() ) {
2310 return '';
2311 }
2312 $s = $this->getLocalURL( 'action=edit' );
2313
2314 return $s;
2315 }
2316
2317 /**
2318 * Can $user perform $action on this page?
2319 * This skips potentially expensive cascading permission checks
2320 * as well as avoids expensive error formatting
2321 *
2322 * Suitable for use for nonessential UI controls in common cases, but
2323 * _not_ for functional access control.
2324 *
2325 * May provide false positives, but should never provide a false negative.
2326 *
2327 * @param string $action Action that permission needs to be checked for
2328 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2329 *
2330 * @return bool
2331 * @throws Exception
2332 *
2333 * @deprecated since 1.33,
2334 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2335 *
2336 */
2337 public function quickUserCan( $action, $user = null ) {
2338 return $this->userCan( $action, $user, false );
2339 }
2340
2341 /**
2342 * Can $user perform $action on this page?
2343 *
2344 * @param string $action Action that permission needs to be checked for
2345 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2346 * provided.
2347 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2348 *
2349 * @return bool
2350 * @throws Exception
2351 *
2352 * @deprecated since 1.33,
2353 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2354 *
2355 */
2356 public function userCan( $action, $user = null, $rigor = PermissionManager::RIGOR_SECURE ) {
2357 if ( !$user instanceof User ) {
2358 global $wgUser;
2359 $user = $wgUser;
2360 }
2361
2362 // TODO: this is for b/c, eventually will be removed
2363 if ( $rigor === true ) {
2364 $rigor = PermissionManager::RIGOR_SECURE; // b/c
2365 } elseif ( $rigor === false ) {
2366 $rigor = PermissionManager::RIGOR_QUICK; // b/c
2367 }
2368
2369 return MediaWikiServices::getInstance()->getPermissionManager()
2370 ->userCan( $action, $user, $this, $rigor );
2371 }
2372
2373 /**
2374 * Can $user perform $action on this page?
2375 *
2376 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2377 *
2378 * @param string $action Action that permission needs to be checked for
2379 * @param User $user User to check
2380 * @param string $rigor One of (quick,full,secure)
2381 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2382 * - full : does cheap and expensive checks possibly from a replica DB
2383 * - secure : does cheap and expensive checks, using the master as needed
2384 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2385 * whose corresponding errors may be ignored.
2386 *
2387 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2388 * @throws Exception
2389 *
2390 * @deprecated since 1.33,
2391 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2392 *
2393 */
2394 public function getUserPermissionsErrors(
2395 $action, $user, $rigor = PermissionManager::RIGOR_SECURE, $ignoreErrors = []
2396 ) {
2397 // TODO: this is for b/c, eventually will be removed
2398 if ( $rigor === true ) {
2399 $rigor = PermissionManager::RIGOR_SECURE; // b/c
2400 } elseif ( $rigor === false ) {
2401 $rigor = PermissionManager::RIGOR_QUICK; // b/c
2402 }
2403
2404 return MediaWikiServices::getInstance()->getPermissionManager()
2405 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2406 }
2407
2408 /**
2409 * Get a filtered list of all restriction types supported by this wiki.
2410 * @param bool $exists True to get all restriction types that apply to
2411 * titles that do exist, False for all restriction types that apply to
2412 * titles that do not exist
2413 * @return array
2414 */
2415 public static function getFilteredRestrictionTypes( $exists = true ) {
2416 global $wgRestrictionTypes;
2417 $types = $wgRestrictionTypes;
2418 if ( $exists ) {
2419 # Remove the create restriction for existing titles
2420 $types = array_diff( $types, [ 'create' ] );
2421 } else {
2422 # Only the create and upload restrictions apply to non-existing titles
2423 $types = array_intersect( $types, [ 'create', 'upload' ] );
2424 }
2425 return $types;
2426 }
2427
2428 /**
2429 * Returns restriction types for the current Title
2430 *
2431 * @return array Applicable restriction types
2432 */
2433 public function getRestrictionTypes() {
2434 if ( $this->isSpecialPage() ) {
2435 return [];
2436 }
2437
2438 $types = self::getFilteredRestrictionTypes( $this->exists() );
2439
2440 if ( $this->mNamespace != NS_FILE ) {
2441 # Remove the upload restriction for non-file titles
2442 $types = array_diff( $types, [ 'upload' ] );
2443 }
2444
2445 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2446
2447 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2448 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2449
2450 return $types;
2451 }
2452
2453 /**
2454 * Is this title subject to title protection?
2455 * Title protection is the one applied against creation of such title.
2456 *
2457 * @return array|bool An associative array representing any existent title
2458 * protection, or false if there's none.
2459 */
2460 public function getTitleProtection() {
2461 $protection = $this->getTitleProtectionInternal();
2462 if ( $protection ) {
2463 if ( $protection['permission'] == 'sysop' ) {
2464 $protection['permission'] = 'editprotected'; // B/C
2465 }
2466 if ( $protection['permission'] == 'autoconfirmed' ) {
2467 $protection['permission'] = 'editsemiprotected'; // B/C
2468 }
2469 }
2470 return $protection;
2471 }
2472
2473 /**
2474 * Fetch title protection settings
2475 *
2476 * To work correctly, $this->loadRestrictions() needs to have access to the
2477 * actual protections in the database without munging 'sysop' =>
2478 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2479 * callers probably want $this->getTitleProtection() instead.
2480 *
2481 * @return array|bool
2482 */
2483 protected function getTitleProtectionInternal() {
2484 // Can't protect pages in special namespaces
2485 if ( $this->mNamespace < 0 ) {
2486 return false;
2487 }
2488
2489 // Can't protect pages that exist.
2490 if ( $this->exists() ) {
2491 return false;
2492 }
2493
2494 if ( $this->mTitleProtection === null ) {
2495 $dbr = wfGetDB( DB_REPLICA );
2496 $commentStore = CommentStore::getStore();
2497 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2498 $res = $dbr->select(
2499 [ 'protected_titles' ] + $commentQuery['tables'],
2500 [
2501 'user' => 'pt_user',
2502 'expiry' => 'pt_expiry',
2503 'permission' => 'pt_create_perm'
2504 ] + $commentQuery['fields'],
2505 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2506 __METHOD__,
2507 [],
2508 $commentQuery['joins']
2509 );
2510
2511 // fetchRow returns false if there are no rows.
2512 $row = $dbr->fetchRow( $res );
2513 if ( $row ) {
2514 $this->mTitleProtection = [
2515 'user' => $row['user'],
2516 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2517 'permission' => $row['permission'],
2518 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
2519 ];
2520 } else {
2521 $this->mTitleProtection = false;
2522 }
2523 }
2524 return $this->mTitleProtection;
2525 }
2526
2527 /**
2528 * Remove any title protection due to page existing
2529 */
2530 public function deleteTitleProtection() {
2531 $dbw = wfGetDB( DB_MASTER );
2532
2533 $dbw->delete(
2534 'protected_titles',
2535 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2536 __METHOD__
2537 );
2538 $this->mTitleProtection = false;
2539 }
2540
2541 /**
2542 * Is this page "semi-protected" - the *only* protection levels are listed
2543 * in $wgSemiprotectedRestrictionLevels?
2544 *
2545 * @param string $action Action to check (default: edit)
2546 * @return bool
2547 */
2548 public function isSemiProtected( $action = 'edit' ) {
2549 global $wgSemiprotectedRestrictionLevels;
2550
2551 $restrictions = $this->getRestrictions( $action );
2552 $semi = $wgSemiprotectedRestrictionLevels;
2553 if ( !$restrictions || !$semi ) {
2554 // Not protected, or all protection is full protection
2555 return false;
2556 }
2557
2558 // Remap autoconfirmed to editsemiprotected for BC
2559 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2560 $semi[$key] = 'editsemiprotected';
2561 }
2562 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2563 $restrictions[$key] = 'editsemiprotected';
2564 }
2565
2566 return !array_diff( $restrictions, $semi );
2567 }
2568
2569 /**
2570 * Does the title correspond to a protected article?
2571 *
2572 * @param string $action The action the page is protected from,
2573 * by default checks all actions.
2574 * @return bool
2575 */
2576 public function isProtected( $action = '' ) {
2577 global $wgRestrictionLevels;
2578
2579 $restrictionTypes = $this->getRestrictionTypes();
2580
2581 # Special pages have inherent protection
2582 if ( $this->isSpecialPage() ) {
2583 return true;
2584 }
2585
2586 # Check regular protection levels
2587 foreach ( $restrictionTypes as $type ) {
2588 if ( $action == $type || $action == '' ) {
2589 $r = $this->getRestrictions( $type );
2590 foreach ( $wgRestrictionLevels as $level ) {
2591 if ( in_array( $level, $r ) && $level != '' ) {
2592 return true;
2593 }
2594 }
2595 }
2596 }
2597
2598 return false;
2599 }
2600
2601 /**
2602 * Determines if $user is unable to edit this page because it has been protected
2603 * by $wgNamespaceProtection.
2604 *
2605 * @deprecated since 1.34 Don't use this function in new code.
2606 * @param User $user User object to check permissions
2607 * @return bool
2608 */
2609 public function isNamespaceProtected( User $user ) {
2610 global $wgNamespaceProtection;
2611
2612 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2613 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2614 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2615 if ( !$permissionManager->userHasRight( $user, $right ) ) {
2616 return true;
2617 }
2618 }
2619 }
2620 return false;
2621 }
2622
2623 /**
2624 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2625 *
2626 * @return bool If the page is subject to cascading restrictions.
2627 */
2628 public function isCascadeProtected() {
2629 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2630 return ( $sources > 0 );
2631 }
2632
2633 /**
2634 * Determines whether cascading protection sources have already been loaded from
2635 * the database.
2636 *
2637 * @param bool $getPages True to check if the pages are loaded, or false to check
2638 * if the status is loaded.
2639 * @return bool Whether or not the specified information has been loaded
2640 * @since 1.23
2641 */
2642 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2643 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2644 }
2645
2646 /**
2647 * Cascading protection: Get the source of any cascading restrictions on this page.
2648 *
2649 * @param bool $getPages Whether or not to retrieve the actual pages
2650 * that the restrictions have come from and the actual restrictions
2651 * themselves.
2652 * @return array Two elements: First is an array of Title objects of the
2653 * pages from which cascading restrictions have come, false for
2654 * none, or true if such restrictions exist but $getPages was not
2655 * set. Second is an array like that returned by
2656 * Title::getAllRestrictions(), or an empty array if $getPages is
2657 * false.
2658 */
2659 public function getCascadeProtectionSources( $getPages = true ) {
2660 $pagerestrictions = [];
2661
2662 if ( $this->mCascadeSources !== null && $getPages ) {
2663 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2664 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2665 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2666 }
2667
2668 $dbr = wfGetDB( DB_REPLICA );
2669
2670 if ( $this->mNamespace == NS_FILE ) {
2671 $tables = [ 'imagelinks', 'page_restrictions' ];
2672 $where_clauses = [
2673 'il_to' => $this->mDbkeyform,
2674 'il_from=pr_page',
2675 'pr_cascade' => 1
2676 ];
2677 } else {
2678 $tables = [ 'templatelinks', 'page_restrictions' ];
2679 $where_clauses = [
2680 'tl_namespace' => $this->mNamespace,
2681 'tl_title' => $this->mDbkeyform,
2682 'tl_from=pr_page',
2683 'pr_cascade' => 1
2684 ];
2685 }
2686
2687 if ( $getPages ) {
2688 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2689 'pr_expiry', 'pr_type', 'pr_level' ];
2690 $where_clauses[] = 'page_id=pr_page';
2691 $tables[] = 'page';
2692 } else {
2693 $cols = [ 'pr_expiry' ];
2694 }
2695
2696 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2697
2698 $sources = $getPages ? [] : false;
2699 $now = wfTimestampNow();
2700
2701 foreach ( $res as $row ) {
2702 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2703 if ( $expiry > $now ) {
2704 if ( $getPages ) {
2705 $page_id = $row->pr_page;
2706 $page_ns = $row->page_namespace;
2707 $page_title = $row->page_title;
2708 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
2709 # Add groups needed for each restriction type if its not already there
2710 # Make sure this restriction type still exists
2711
2712 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2713 $pagerestrictions[$row->pr_type] = [];
2714 }
2715
2716 if (
2717 isset( $pagerestrictions[$row->pr_type] )
2718 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2719 ) {
2720 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2721 }
2722 } else {
2723 $sources = true;
2724 }
2725 }
2726 }
2727
2728 if ( $getPages ) {
2729 $this->mCascadeSources = $sources;
2730 $this->mCascadingRestrictions = $pagerestrictions;
2731 } else {
2732 $this->mHasCascadingRestrictions = $sources;
2733 }
2734
2735 return [ $sources, $pagerestrictions ];
2736 }
2737
2738 /**
2739 * Accessor for mRestrictionsLoaded
2740 *
2741 * @return bool Whether or not the page's restrictions have already been
2742 * loaded from the database
2743 * @since 1.23
2744 */
2745 public function areRestrictionsLoaded() {
2746 return $this->mRestrictionsLoaded;
2747 }
2748
2749 /**
2750 * Accessor/initialisation for mRestrictions
2751 *
2752 * @param string $action Action that permission needs to be checked for
2753 * @return array Restriction levels needed to take the action. All levels are
2754 * required. Note that restriction levels are normally user rights, but 'sysop'
2755 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2756 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2757 */
2758 public function getRestrictions( $action ) {
2759 if ( !$this->mRestrictionsLoaded ) {
2760 $this->loadRestrictions();
2761 }
2762 return $this->mRestrictions[$action] ?? [];
2763 }
2764
2765 /**
2766 * Accessor/initialisation for mRestrictions
2767 *
2768 * @return array Keys are actions, values are arrays as returned by
2769 * Title::getRestrictions()
2770 * @since 1.23
2771 */
2772 public function getAllRestrictions() {
2773 if ( !$this->mRestrictionsLoaded ) {
2774 $this->loadRestrictions();
2775 }
2776 return $this->mRestrictions;
2777 }
2778
2779 /**
2780 * Get the expiry time for the restriction against a given action
2781 *
2782 * @param string $action
2783 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2784 * or not protected at all, or false if the action is not recognised.
2785 */
2786 public function getRestrictionExpiry( $action ) {
2787 if ( !$this->mRestrictionsLoaded ) {
2788 $this->loadRestrictions();
2789 }
2790 return $this->mRestrictionsExpiry[$action] ?? false;
2791 }
2792
2793 /**
2794 * Returns cascading restrictions for the current article
2795 *
2796 * @return bool
2797 */
2798 function areRestrictionsCascading() {
2799 if ( !$this->mRestrictionsLoaded ) {
2800 $this->loadRestrictions();
2801 }
2802
2803 return $this->mCascadeRestriction;
2804 }
2805
2806 /**
2807 * Compiles list of active page restrictions from both page table (pre 1.10)
2808 * and page_restrictions table for this existing page.
2809 * Public for usage by LiquidThreads.
2810 *
2811 * @param array $rows Array of db result objects
2812 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2813 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2814 * Edit and move sections are separated by a colon
2815 * Example: "edit=autoconfirmed,sysop:move=sysop"
2816 */
2817 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2818 // This function will only read rows from a table that we migrated away
2819 // from before adding READ_LATEST support to loadRestrictions, so we
2820 // don't need to support reading from DB_MASTER here.
2821 $dbr = wfGetDB( DB_REPLICA );
2822
2823 $restrictionTypes = $this->getRestrictionTypes();
2824
2825 foreach ( $restrictionTypes as $type ) {
2826 $this->mRestrictions[$type] = [];
2827 $this->mRestrictionsExpiry[$type] = 'infinity';
2828 }
2829
2830 $this->mCascadeRestriction = false;
2831
2832 # Backwards-compatibility: also load the restrictions from the page record (old format).
2833 if ( $oldFashionedRestrictions !== null ) {
2834 $this->mOldRestrictions = $oldFashionedRestrictions;
2835 }
2836
2837 if ( $this->mOldRestrictions === false ) {
2838 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2839 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2840 $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2841 }
2842
2843 if ( $this->mOldRestrictions != '' ) {
2844 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2845 $temp = explode( '=', trim( $restrict ) );
2846 if ( count( $temp ) == 1 ) {
2847 // old old format should be treated as edit/move restriction
2848 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2849 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2850 } else {
2851 $restriction = trim( $temp[1] );
2852 if ( $restriction != '' ) { // some old entries are empty
2853 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2854 }
2855 }
2856 }
2857 }
2858
2859 if ( count( $rows ) ) {
2860 # Current system - load second to make them override.
2861 $now = wfTimestampNow();
2862
2863 # Cycle through all the restrictions.
2864 foreach ( $rows as $row ) {
2865 // Don't take care of restrictions types that aren't allowed
2866 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2867 continue;
2868 }
2869
2870 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2871
2872 // Only apply the restrictions if they haven't expired!
2873 if ( !$expiry || $expiry > $now ) {
2874 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2875 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2876
2877 $this->mCascadeRestriction |= $row->pr_cascade;
2878 }
2879 }
2880 }
2881
2882 $this->mRestrictionsLoaded = true;
2883 }
2884
2885 /**
2886 * Load restrictions from the page_restrictions table
2887 *
2888 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2889 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2890 * Edit and move sections are separated by a colon
2891 * Example: "edit=autoconfirmed,sysop:move=sysop"
2892 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2893 * from the master DB.
2894 */
2895 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2896 $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
2897 if ( $this->mRestrictionsLoaded && !$readLatest ) {
2898 return;
2899 }
2900
2901 $id = $this->getArticleID( $flags );
2902 if ( $id ) {
2903 $fname = __METHOD__;
2904 $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
2905 return iterator_to_array(
2906 $dbr->select(
2907 'page_restrictions',
2908 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2909 [ 'pr_page' => $id ],
2910 $fname
2911 )
2912 );
2913 };
2914
2915 if ( $readLatest ) {
2916 $dbr = wfGetDB( DB_MASTER );
2917 $rows = $loadRestrictionsFromDb( $dbr );
2918 } else {
2919 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2920 $rows = $cache->getWithSetCallback(
2921 // Page protections always leave a new null revision
2922 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2923 $cache::TTL_DAY,
2924 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2925 $dbr = wfGetDB( DB_REPLICA );
2926
2927 $setOpts += Database::getCacheSetOptions( $dbr );
2928 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2929 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2930 // @TODO: cleanup Title cache and caller assumption mess in general
2931 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2932 }
2933
2934 return $loadRestrictionsFromDb( $dbr );
2935 }
2936 );
2937 }
2938
2939 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2940 } else {
2941 $title_protection = $this->getTitleProtectionInternal();
2942
2943 if ( $title_protection ) {
2944 $now = wfTimestampNow();
2945 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
2946
2947 if ( !$expiry || $expiry > $now ) {
2948 // Apply the restrictions
2949 $this->mRestrictionsExpiry['create'] = $expiry;
2950 $this->mRestrictions['create'] =
2951 explode( ',', trim( $title_protection['permission'] ) );
2952 } else { // Get rid of the old restrictions
2953 $this->mTitleProtection = false;
2954 }
2955 } else {
2956 $this->mRestrictionsExpiry['create'] = 'infinity';
2957 }
2958 $this->mRestrictionsLoaded = true;
2959 }
2960 }
2961
2962 /**
2963 * Flush the protection cache in this object and force reload from the database.
2964 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2965 */
2966 public function flushRestrictions() {
2967 $this->mRestrictionsLoaded = false;
2968 $this->mTitleProtection = null;
2969 }
2970
2971 /**
2972 * Purge expired restrictions from the page_restrictions table
2973 *
2974 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2975 */
2976 static function purgeExpiredRestrictions() {
2977 if ( wfReadOnly() ) {
2978 return;
2979 }
2980
2981 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2982 wfGetDB( DB_MASTER ),
2983 __METHOD__,
2984 function ( IDatabase $dbw, $fname ) {
2985 $config = MediaWikiServices::getInstance()->getMainConfig();
2986 $ids = $dbw->selectFieldValues(
2987 'page_restrictions',
2988 'pr_id',
2989 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2990 $fname,
2991 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2992 );
2993 if ( $ids ) {
2994 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2995 }
2996 }
2997 ) );
2998
2999 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3000 wfGetDB( DB_MASTER ),
3001 __METHOD__,
3002 function ( IDatabase $dbw, $fname ) {
3003 $dbw->delete(
3004 'protected_titles',
3005 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3006 $fname
3007 );
3008 }
3009 ) );
3010 }
3011
3012 /**
3013 * Does this have subpages? (Warning, usually requires an extra DB query.)
3014 *
3015 * @return bool
3016 */
3017 public function hasSubpages() {
3018 if (
3019 !MediaWikiServices::getInstance()->getNamespaceInfo()->
3020 hasSubpages( $this->mNamespace )
3021 ) {
3022 # Duh
3023 return false;
3024 }
3025
3026 # We dynamically add a member variable for the purpose of this method
3027 # alone to cache the result. There's no point in having it hanging
3028 # around uninitialized in every Title object; therefore we only add it
3029 # if needed and don't declare it statically.
3030 if ( $this->mHasSubpages === null ) {
3031 $this->mHasSubpages = false;
3032 $subpages = $this->getSubpages( 1 );
3033 if ( $subpages instanceof TitleArray ) {
3034 $this->mHasSubpages = (bool)$subpages->current();
3035 }
3036 }
3037
3038 return $this->mHasSubpages;
3039 }
3040
3041 /**
3042 * Get all subpages of this page.
3043 *
3044 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3045 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3046 * doesn't allow subpages
3047 */
3048 public function getSubpages( $limit = -1 ) {
3049 if (
3050 !MediaWikiServices::getInstance()->getNamespaceInfo()->
3051 hasSubpages( $this->mNamespace )
3052 ) {
3053 return [];
3054 }
3055
3056 $dbr = wfGetDB( DB_REPLICA );
3057 $conds = [ 'page_namespace' => $this->mNamespace ];
3058 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3059 $options = [];
3060 if ( $limit > -1 ) {
3061 $options['LIMIT'] = $limit;
3062 }
3063 return TitleArray::newFromResult(
3064 $dbr->select( 'page',
3065 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3066 $conds,
3067 __METHOD__,
3068 $options
3069 )
3070 );
3071 }
3072
3073 /**
3074 * Is there a version of this page in the deletion archive?
3075 *
3076 * @return int The number of archived revisions
3077 */
3078 public function isDeleted() {
3079 if ( $this->mNamespace < 0 ) {
3080 $n = 0;
3081 } else {
3082 $dbr = wfGetDB( DB_REPLICA );
3083
3084 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3085 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3086 __METHOD__
3087 );
3088 if ( $this->mNamespace == NS_FILE ) {
3089 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3090 [ 'fa_name' => $this->mDbkeyform ],
3091 __METHOD__
3092 );
3093 }
3094 }
3095 return (int)$n;
3096 }
3097
3098 /**
3099 * Is there a version of this page in the deletion archive?
3100 *
3101 * @return bool
3102 */
3103 public function isDeletedQuick() {
3104 if ( $this->mNamespace < 0 ) {
3105 return false;
3106 }
3107 $dbr = wfGetDB( DB_REPLICA );
3108 $deleted = (bool)$dbr->selectField( 'archive', '1',
3109 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3110 __METHOD__
3111 );
3112 if ( !$deleted && $this->mNamespace == NS_FILE ) {
3113 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3114 [ 'fa_name' => $this->mDbkeyform ],
3115 __METHOD__
3116 );
3117 }
3118 return $deleted;
3119 }
3120
3121 /**
3122 * Get the article ID for this Title from the link cache,
3123 * adding it if necessary
3124 *
3125 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3126 * @return int The ID
3127 */
3128 public function getArticleID( $flags = 0 ) {
3129 if ( $this->mNamespace < 0 ) {
3130 $this->mArticleID = 0;
3131
3132 return $this->mArticleID;
3133 }
3134
3135 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3136 if ( $flags & self::GAID_FOR_UPDATE ) {
3137 $oldUpdate = $linkCache->forUpdate( true );
3138 $linkCache->clearLink( $this );
3139 $this->mArticleID = $linkCache->addLinkObj( $this );
3140 $linkCache->forUpdate( $oldUpdate );
3141 } elseif ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3142 $this->mArticleID = (int)$this->loadFieldFromDB( 'page_id', $flags );
3143 } elseif ( $this->mArticleID == -1 ) {
3144 $this->mArticleID = $linkCache->addLinkObj( $this );
3145 }
3146
3147 return $this->mArticleID;
3148 }
3149
3150 /**
3151 * Is this an article that is a redirect page?
3152 * Uses link cache, adding it if necessary
3153 *
3154 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3155 * @return bool
3156 */
3157 public function isRedirect( $flags = 0 ) {
3158 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3159 $this->mRedirect = (bool)$this->loadFieldFromDB( 'page_is_redirect', $flags );
3160 } else {
3161 if ( $this->mRedirect !== null ) {
3162 return $this->mRedirect;
3163 } elseif ( !$this->getArticleID( $flags ) ) {
3164 $this->mRedirect = false;
3165
3166 return $this->mRedirect;
3167 }
3168
3169 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3170 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3171 // Note that LinkCache returns null if it thinks the page does not exist;
3172 // always trust the state of LinkCache over that of this Title instance.
3173 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3174 }
3175
3176 return $this->mRedirect;
3177 }
3178
3179 /**
3180 * What is the length of this page?
3181 * Uses link cache, adding it if necessary
3182 *
3183 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3184 * @return int
3185 */
3186 public function getLength( $flags = 0 ) {
3187 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3188 $this->mLength = (int)$this->loadFieldFromDB( 'page_len', $flags );
3189 } else {
3190 if ( $this->mLength != -1 ) {
3191 return $this->mLength;
3192 } elseif ( !$this->getArticleID( $flags ) ) {
3193 $this->mLength = 0;
3194 return $this->mLength;
3195 }
3196
3197 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3198 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3199 // Note that LinkCache returns null if it thinks the page does not exist;
3200 // always trust the state of LinkCache over that of this Title instance.
3201 $this->mLength = (int)$linkCache->getGoodLinkFieldObj( $this, 'length' );
3202 }
3203
3204 return $this->mLength;
3205 }
3206
3207 /**
3208 * What is the page_latest field for this page?
3209 *
3210 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3211 * @return int Int or 0 if the page doesn't exist
3212 */
3213 public function getLatestRevID( $flags = 0 ) {
3214 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3215 $this->mLatestID = (int)$this->loadFieldFromDB( 'page_latest', $flags );
3216 } else {
3217 if ( $this->mLatestID !== false ) {
3218 return (int)$this->mLatestID;
3219 } elseif ( !$this->getArticleID( $flags ) ) {
3220 $this->mLatestID = 0;
3221
3222 return $this->mLatestID;
3223 }
3224
3225 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3226 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3227 // Note that LinkCache returns null if it thinks the page does not exist;
3228 // always trust the state of LinkCache over that of this Title instance.
3229 $this->mLatestID = (int)$linkCache->getGoodLinkFieldObj( $this, 'revision' );
3230 }
3231
3232 return $this->mLatestID;
3233 }
3234
3235 /**
3236 * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
3237 *
3238 * This can be called on page insertion to allow loading of the new page_id without
3239 * having to create a new Title instance. Likewise with deletion.
3240 *
3241 * @note This overrides Title::setContentModel()
3242 *
3243 * @param int|bool $id Page ID, 0 for non-existant, or false for "unknown" (lazy-load)
3244 */
3245 public function resetArticleID( $id ) {
3246 if ( $id === false ) {
3247 $this->mArticleID = -1;
3248 } else {
3249 $this->mArticleID = (int)$id;
3250 }
3251 $this->mRestrictionsLoaded = false;
3252 $this->mRestrictions = [];
3253 $this->mOldRestrictions = false;
3254 $this->mRedirect = null;
3255 $this->mLength = -1;
3256 $this->mLatestID = false;
3257 $this->mContentModel = false;
3258 $this->mForcedContentModel = false;
3259 $this->mEstimateRevisions = null;
3260 $this->mPageLanguage = null;
3261 $this->mDbPageLanguage = false;
3262 $this->mIsBigDeletion = null;
3263
3264 MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
3265 }
3266
3267 public static function clearCaches() {
3268 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3269 $linkCache->clear();
3270
3271 $titleCache = self::getTitleCache();
3272 $titleCache->clear();
3273 }
3274
3275 /**
3276 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3277 *
3278 * @param string $text Containing title to capitalize
3279 * @param int $ns Namespace index, defaults to NS_MAIN
3280 * @return string Containing capitalized title
3281 */
3282 public static function capitalize( $text, $ns = NS_MAIN ) {
3283 $services = MediaWikiServices::getInstance();
3284 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3285 return $services->getContentLanguage()->ucfirst( $text );
3286 } else {
3287 return $text;
3288 }
3289 }
3290
3291 /**
3292 * Secure and split - main initialisation function for this object
3293 *
3294 * Assumes that mDbkeyform has been set, and is urldecoded
3295 * and uses underscores, but not otherwise munged. This function
3296 * removes illegal characters, splits off the interwiki and
3297 * namespace prefixes, sets the other forms, and canonicalizes
3298 * everything.
3299 *
3300 * @throws MalformedTitleException On invalid titles
3301 * @return bool True on success
3302 */
3303 private function secureAndSplit() {
3304 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3305 // the parsing code with Title, while avoiding massive refactoring.
3306 // @todo: get rid of secureAndSplit, refactor parsing code.
3307 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3308 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3309 /** @var MediaWikiTitleCodec $titleCodec */
3310 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3311 '@phan-var MediaWikiTitleCodec $titleCodec';
3312 // MalformedTitleException can be thrown here
3313 $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
3314
3315 # Fill fields
3316 $this->setFragment( '#' . $parts['fragment'] );
3317 $this->mInterwiki = $parts['interwiki'];
3318 $this->mLocalInterwiki = $parts['local_interwiki'];
3319 $this->mNamespace = $parts['namespace'];
3320 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3321
3322 $this->mDbkeyform = $parts['dbkey'];
3323 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3324 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3325
3326 # We already know that some pages won't be in the database!
3327 if ( $this->isExternal() || $this->isSpecialPage() ) {
3328 $this->mArticleID = 0;
3329 }
3330
3331 return true;
3332 }
3333
3334 /**
3335 * Get an array of Title objects linking to this Title
3336 * Also stores the IDs in the link cache.
3337 *
3338 * WARNING: do not use this function on arbitrary user-supplied titles!
3339 * On heavily-used templates it will max out the memory.
3340 *
3341 * @param array $options May be FOR UPDATE
3342 * @param string $table Table name
3343 * @param string $prefix Fields prefix
3344 * @return Title[] Array of Title objects linking here
3345 */
3346 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3347 if ( count( $options ) > 0 ) {
3348 $db = wfGetDB( DB_MASTER );
3349 } else {
3350 $db = wfGetDB( DB_REPLICA );
3351 }
3352
3353 $res = $db->select(
3354 [ 'page', $table ],
3355 self::getSelectFields(),
3356 [
3357 "{$prefix}_from=page_id",
3358 "{$prefix}_namespace" => $this->mNamespace,
3359 "{$prefix}_title" => $this->mDbkeyform ],
3360 __METHOD__,
3361 $options
3362 );
3363
3364 $retVal = [];
3365 if ( $res->numRows() ) {
3366 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3367 foreach ( $res as $row ) {
3368 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3369 if ( $titleObj ) {
3370 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3371 $retVal[] = $titleObj;
3372 }
3373 }
3374 }
3375 return $retVal;
3376 }
3377
3378 /**
3379 * Get an array of Title objects using this Title as a template
3380 * Also stores the IDs in the link cache.
3381 *
3382 * WARNING: do not use this function on arbitrary user-supplied titles!
3383 * On heavily-used templates it will max out the memory.
3384 *
3385 * @param array $options Query option to Database::select()
3386 * @return Title[] Array of Title the Title objects linking here
3387 */
3388 public function getTemplateLinksTo( $options = [] ) {
3389 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3390 }
3391
3392 /**
3393 * Get an array of Title objects linked from this Title
3394 * Also stores the IDs in the link cache.
3395 *
3396 * WARNING: do not use this function on arbitrary user-supplied titles!
3397 * On heavily-used templates it will max out the memory.
3398 *
3399 * @param array $options Query option to Database::select()
3400 * @param string $table Table name
3401 * @param string $prefix Fields prefix
3402 * @return array Array of Title objects linking here
3403 */
3404 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3405 $id = $this->getArticleID();
3406
3407 # If the page doesn't exist; there can't be any link from this page
3408 if ( !$id ) {
3409 return [];
3410 }
3411
3412 $db = wfGetDB( DB_REPLICA );
3413
3414 $blNamespace = "{$prefix}_namespace";
3415 $blTitle = "{$prefix}_title";
3416
3417 $pageQuery = WikiPage::getQueryInfo();
3418 $res = $db->select(
3419 [ $table, 'nestpage' => $pageQuery['tables'] ],
3420 array_merge(
3421 [ $blNamespace, $blTitle ],
3422 $pageQuery['fields']
3423 ),
3424 [ "{$prefix}_from" => $id ],
3425 __METHOD__,
3426 $options,
3427 [ 'nestpage' => [
3428 'LEFT JOIN',
3429 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3430 ] ] + $pageQuery['joins']
3431 );
3432
3433 $retVal = [];
3434 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3435 foreach ( $res as $row ) {
3436 if ( $row->page_id ) {
3437 $titleObj = self::newFromRow( $row );
3438 } else {
3439 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3440 $linkCache->addBadLinkObj( $titleObj );
3441 }
3442 $retVal[] = $titleObj;
3443 }
3444
3445 return $retVal;
3446 }
3447
3448 /**
3449 * Get an array of Title objects used on this Title as a template
3450 * Also stores the IDs in the link cache.
3451 *
3452 * WARNING: do not use this function on arbitrary user-supplied titles!
3453 * On heavily-used templates it will max out the memory.
3454 *
3455 * @param array $options May be FOR UPDATE
3456 * @return Title[] Array of Title the Title objects used here
3457 */
3458 public function getTemplateLinksFrom( $options = [] ) {
3459 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3460 }
3461
3462 /**
3463 * Get an array of Title objects referring to non-existent articles linked
3464 * from this page.
3465 *
3466 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3467 * should use redirect table in this case).
3468 * @return Title[] Array of Title the Title objects
3469 */
3470 public function getBrokenLinksFrom() {
3471 if ( $this->getArticleID() == 0 ) {
3472 # All links from article ID 0 are false positives
3473 return [];
3474 }
3475
3476 $dbr = wfGetDB( DB_REPLICA );
3477 $res = $dbr->select(
3478 [ 'page', 'pagelinks' ],
3479 [ 'pl_namespace', 'pl_title' ],
3480 [
3481 'pl_from' => $this->getArticleID(),
3482 'page_namespace IS NULL'
3483 ],
3484 __METHOD__, [],
3485 [
3486 'page' => [
3487 'LEFT JOIN',
3488 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3489 ]
3490 ]
3491 );
3492
3493 $retVal = [];
3494 foreach ( $res as $row ) {
3495 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3496 }
3497 return $retVal;
3498 }
3499
3500 /**
3501 * Get a list of URLs to purge from the CDN cache when this
3502 * page changes
3503 *
3504 * @return string[] Array of String the URLs
3505 */
3506 public function getCdnUrls() {
3507 $urls = [
3508 $this->getInternalURL(),
3509 $this->getInternalURL( 'action=history' )
3510 ];
3511
3512 $pageLang = $this->getPageLanguage();
3513 if ( $pageLang->hasVariants() ) {
3514 $variants = $pageLang->getVariants();
3515 foreach ( $variants as $vCode ) {
3516 $urls[] = $this->getInternalURL( $vCode );
3517 }
3518 }
3519
3520 // If we are looking at a css/js user subpage, purge the action=raw.
3521 if ( $this->isUserJsConfigPage() ) {
3522 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3523 } elseif ( $this->isUserJsonConfigPage() ) {
3524 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3525 } elseif ( $this->isUserCssConfigPage() ) {
3526 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3527 }
3528
3529 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3530 return $urls;
3531 }
3532
3533 /**
3534 * Purge all applicable CDN URLs
3535 */
3536 public function purgeSquid() {
3537 DeferredUpdates::addUpdate(
3538 new CdnCacheUpdate( $this->getCdnUrls() ),
3539 DeferredUpdates::PRESEND
3540 );
3541 }
3542
3543 /**
3544 * Check whether a given move operation would be valid.
3545 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3546 *
3547 * @deprecated since 1.25, use MovePage's methods instead
3548 * @param Title &$nt The new title
3549 * @param bool $auth Whether to check user permissions (uses $wgUser)
3550 * @param string $reason Is the log summary of the move, used for spam checking
3551 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3552 */
3553 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3554 wfDeprecated( __METHOD__, '1.25' );
3555
3556 global $wgUser;
3557
3558 if ( !( $nt instanceof Title ) ) {
3559 // Normally we'd add this to $errors, but we'll get
3560 // lots of syntax errors if $nt is not an object
3561 return [ [ 'badtitletext' ] ];
3562 }
3563
3564 $mp = MediaWikiServices::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3565 $errors = $mp->isValidMove()->getErrorsArray();
3566 if ( $auth ) {
3567 $errors = wfMergeErrorArrays(
3568 $errors,
3569 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3570 );
3571 }
3572
3573 return $errors ?: true;
3574 }
3575
3576 /**
3577 * Move a title to a new location
3578 *
3579 * @deprecated since 1.25, use the MovePage class instead
3580 * @param Title &$nt The new title
3581 * @param bool $auth Indicates whether $wgUser's permissions
3582 * should be checked
3583 * @param string $reason The reason for the move
3584 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3585 * Ignored if the user doesn't have the suppressredirect right.
3586 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3587 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3588 */
3589 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3590 array $changeTags = []
3591 ) {
3592 wfDeprecated( __METHOD__, '1.25' );
3593
3594 global $wgUser;
3595
3596 $mp = MediaWikiServices::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3597 $method = $auth ? 'moveIfAllowed' : 'move';
3598 /** @var Status $status */
3599 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3600 if ( $status->isOK() ) {
3601 return true;
3602 } else {
3603 return $status->getErrorsArray();
3604 }
3605 }
3606
3607 /**
3608 * Move this page's subpages to be subpages of $nt
3609 *
3610 * @deprecated since 1.34, use MovePage instead
3611 * @param Title $nt Move target
3612 * @param bool $auth Whether $wgUser's permissions should be checked
3613 * @param string $reason The reason for the move
3614 * @param bool $createRedirect Whether to create redirects from the old subpages to
3615 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3616 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3617 * @return array Array with old page titles as keys, and strings (new page titles) or
3618 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3619 * getUserPermissionsErrors()-like error array with numeric indices if
3620 * no pages were moved
3621 */
3622 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3623 array $changeTags = []
3624 ) {
3625 wfDeprecated( __METHOD__, '1.34' );
3626
3627 global $wgUser;
3628
3629 $mp = new MovePage( $this, $nt );
3630 $method = $auth ? 'moveSubpagesIfAllowed' : 'moveSubpages';
3631 /** @var Status $result */
3632 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3633
3634 if ( !$result->isOK() ) {
3635 return $result->getErrorsArray();
3636 }
3637
3638 $retval = [];
3639 foreach ( $result->getValue() as $key => $status ) {
3640 /** @var Status $status */
3641 if ( $status->isOK() ) {
3642 $retval[$key] = $status->getValue();
3643 } else {
3644 $retval[$key] = $status->getErrorsArray();
3645 }
3646 }
3647 return $retval;
3648 }
3649
3650 /**
3651 * Locks the page row and check if this page is single revision redirect
3652 *
3653 * This updates the cached fields of this instance via Title::loadFromRow()
3654 *
3655 * @return bool
3656 */
3657 public function isSingleRevRedirect() {
3658 global $wgContentHandlerUseDB;
3659
3660 $dbw = wfGetDB( DB_MASTER );
3661
3662 # Is it a redirect?
3663 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3664 if ( $wgContentHandlerUseDB ) {
3665 $fields[] = 'page_content_model';
3666 }
3667
3668 $row = $dbw->selectRow( 'page',
3669 $fields,
3670 $this->pageCond(),
3671 __METHOD__,
3672 [ 'FOR UPDATE' ]
3673 );
3674 # Cache some fields we may want
3675 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3676 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3677 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3678 $this->mContentModel = $row && isset( $row->page_content_model )
3679 ? strval( $row->page_content_model )
3680 : false;
3681
3682 if ( !$this->mRedirect ) {
3683 return false;
3684 }
3685 # Does the article have a history?
3686 $row = $dbw->selectField( [ 'page', 'revision' ],
3687 'rev_id',
3688 [ 'page_namespace' => $this->mNamespace,
3689 'page_title' => $this->mDbkeyform,
3690 'page_id=rev_page',
3691 'page_latest != rev_id'
3692 ],
3693 __METHOD__,
3694 [ 'FOR UPDATE' ]
3695 );
3696 # Return true if there was no history
3697 return ( $row === false );
3698 }
3699
3700 /**
3701 * Checks if $this can be moved to a given Title
3702 * - Selects for update, so don't call it unless you mean business
3703 *
3704 * @deprecated since 1.25, use MovePage's methods instead
3705 * @param Title $nt The new title to check
3706 * @return bool
3707 */
3708 public function isValidMoveTarget( $nt ) {
3709 wfDeprecated( __METHOD__, '1.25' );
3710
3711 # Is it an existing file?
3712 if ( $nt->getNamespace() == NS_FILE ) {
3713 $file = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
3714 ->newFile( $nt );
3715 $file->load( File::READ_LATEST );
3716 if ( $file->exists() ) {
3717 wfDebug( __METHOD__ . ": file exists\n" );
3718 return false;
3719 }
3720 }
3721 # Is it a redirect with no history?
3722 if ( !$nt->isSingleRevRedirect() ) {
3723 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3724 return false;
3725 }
3726 # Get the article text
3727 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3728 if ( !is_object( $rev ) ) {
3729 return false;
3730 }
3731 $content = $rev->getContent();
3732 # Does the redirect point to the source?
3733 # Or is it a broken self-redirect, usually caused by namespace collisions?
3734 $redirTitle = $content ? $content->getRedirectTarget() : null;
3735
3736 if ( $redirTitle ) {
3737 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3738 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3739 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3740 return false;
3741 } else {
3742 return true;
3743 }
3744 } else {
3745 # Fail safe (not a redirect after all. strange.)
3746 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3747 " is a redirect, but it doesn't contain a valid redirect.\n" );
3748 return false;
3749 }
3750 }
3751
3752 /**
3753 * Get categories to which this Title belongs and return an array of
3754 * categories' names.
3755 *
3756 * @return array Array of parents in the form:
3757 * $parent => $currentarticle
3758 */
3759 public function getParentCategories() {
3760 $data = [];
3761
3762 $titleKey = $this->getArticleID();
3763
3764 if ( $titleKey === 0 ) {
3765 return $data;
3766 }
3767
3768 $dbr = wfGetDB( DB_REPLICA );
3769
3770 $res = $dbr->select(
3771 'categorylinks',
3772 'cl_to',
3773 [ 'cl_from' => $titleKey ],
3774 __METHOD__
3775 );
3776
3777 if ( $res->numRows() > 0 ) {
3778 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
3779 foreach ( $res as $row ) {
3780 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3781 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
3782 $this->getFullText();
3783 }
3784 }
3785 return $data;
3786 }
3787
3788 /**
3789 * Get a tree of parent categories
3790 *
3791 * @param array $children Array with the children in the keys, to check for circular refs
3792 * @return array Tree of parent categories
3793 */
3794 public function getParentCategoryTree( $children = [] ) {
3795 $stack = [];
3796 $parents = $this->getParentCategories();
3797
3798 if ( $parents ) {
3799 foreach ( $parents as $parent => $current ) {
3800 if ( array_key_exists( $parent, $children ) ) {
3801 # Circular reference
3802 $stack[$parent] = [];
3803 } else {
3804 $nt = self::newFromText( $parent );
3805 if ( $nt ) {
3806 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3807 }
3808 }
3809 }
3810 }
3811
3812 return $stack;
3813 }
3814
3815 /**
3816 * Get an associative array for selecting this title from
3817 * the "page" table
3818 *
3819 * @return array Array suitable for the $where parameter of DB::select()
3820 */
3821 public function pageCond() {
3822 if ( $this->mArticleID > 0 ) {
3823 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3824 return [ 'page_id' => $this->mArticleID ];
3825 } else {
3826 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3827 }
3828 }
3829
3830 /**
3831 * Get next/previous revision ID relative to another revision ID
3832 * @param int $revId Revision ID. Get the revision that was before this one.
3833 * @param int $flags Bitfield of class READ_* constants
3834 * @param string $dir 'next' or 'prev'
3835 * @return int|bool New revision ID, or false if none exists
3836 */
3837 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3838 $rl = MediaWikiServices::getInstance()->getRevisionLookup();
3839 $rev = $rl->getRevisionById( $revId, $flags );
3840 if ( !$rev ) {
3841 return false;
3842 }
3843
3844 $oldRev = ( $dir === 'next' )
3845 ? $rl->getNextRevision( $rev, $flags )
3846 : $rl->getPreviousRevision( $rev, $flags );
3847
3848 return $oldRev ? $oldRev->getId() : false;
3849 }
3850
3851 /**
3852 * Get the revision ID of the previous revision
3853 *
3854 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3855 * @param int $revId Revision ID. Get the revision that was before this one.
3856 * @param int $flags Bitfield of class READ_* constants
3857 * @return int|bool Old revision ID, or false if none exists
3858 */
3859 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3860 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3861 }
3862
3863 /**
3864 * Get the revision ID of the next revision
3865 *
3866 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3867 * @param int $revId Revision ID. Get the revision that was after this one.
3868 * @param int $flags Bitfield of class READ_* constants
3869 * @return int|bool Next revision ID, or false if none exists
3870 */
3871 public function getNextRevisionID( $revId, $flags = 0 ) {
3872 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3873 }
3874
3875 /**
3876 * Get the first revision of the page
3877 *
3878 * @param int $flags Bitfield of class READ_* constants
3879 * @return Revision|null If page doesn't exist
3880 */
3881 public function getFirstRevision( $flags = 0 ) {
3882 $pageId = $this->getArticleID( $flags );
3883 if ( $pageId ) {
3884 $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
3885 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
3886 $revQuery = Revision::getQueryInfo();
3887 $row = wfGetDB( $index )->selectRow(
3888 $revQuery['tables'], $revQuery['fields'],
3889 [ 'rev_page' => $pageId ],
3890 __METHOD__,
3891 array_merge(
3892 [
3893 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3894 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3895 ],
3896 $options
3897 ),
3898 $revQuery['joins']
3899 );
3900 if ( $row ) {
3901 return new Revision( $row, 0, $this );
3902 }
3903 }
3904 return null;
3905 }
3906
3907 /**
3908 * Get the oldest revision timestamp of this page
3909 *
3910 * @param int $flags Bitfield of class READ_* constants
3911 * @return string|null MW timestamp
3912 */
3913 public function getEarliestRevTime( $flags = 0 ) {
3914 $rev = $this->getFirstRevision( $flags );
3915 return $rev ? $rev->getTimestamp() : null;
3916 }
3917
3918 /**
3919 * Check if this is a new page
3920 *
3921 * @return bool
3922 */
3923 public function isNewPage() {
3924 $dbr = wfGetDB( DB_REPLICA );
3925 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3926 }
3927
3928 /**
3929 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3930 *
3931 * @return bool
3932 */
3933 public function isBigDeletion() {
3934 global $wgDeleteRevisionsLimit;
3935
3936 if ( !$wgDeleteRevisionsLimit ) {
3937 return false;
3938 }
3939
3940 if ( $this->mIsBigDeletion === null ) {
3941 $dbr = wfGetDB( DB_REPLICA );
3942
3943 $revCount = $dbr->selectRowCount(
3944 'revision',
3945 '1',
3946 [ 'rev_page' => $this->getArticleID() ],
3947 __METHOD__,
3948 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
3949 );
3950
3951 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
3952 }
3953
3954 return $this->mIsBigDeletion;
3955 }
3956
3957 /**
3958 * Get the approximate revision count of this page.
3959 *
3960 * @return int
3961 */
3962 public function estimateRevisionCount() {
3963 if ( !$this->exists() ) {
3964 return 0;
3965 }
3966
3967 if ( $this->mEstimateRevisions === null ) {
3968 $dbr = wfGetDB( DB_REPLICA );
3969 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
3970 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
3971 }
3972
3973 return $this->mEstimateRevisions;
3974 }
3975
3976 /**
3977 * Get the number of revisions between the given revision.
3978 * Used for diffs and other things that really need it.
3979 *
3980 * @param int|Revision $old Old revision or rev ID (first before range)
3981 * @param int|Revision $new New revision or rev ID (first after range)
3982 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3983 * @return int Number of revisions between these revisions.
3984 */
3985 public function countRevisionsBetween( $old, $new, $max = null ) {
3986 if ( !( $old instanceof Revision ) ) {
3987 $old = Revision::newFromTitle( $this, (int)$old );
3988 }
3989 if ( !( $new instanceof Revision ) ) {
3990 $new = Revision::newFromTitle( $this, (int)$new );
3991 }
3992 if ( !$old || !$new ) {
3993 return 0; // nothing to compare
3994 }
3995 $dbr = wfGetDB( DB_REPLICA );
3996 $conds = [
3997 'rev_page' => $this->getArticleID(),
3998 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3999 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4000 ];
4001 if ( $max !== null ) {
4002 return $dbr->selectRowCount( 'revision', '1',
4003 $conds,
4004 __METHOD__,
4005 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4006 );
4007 } else {
4008 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4009 }
4010 }
4011
4012 /**
4013 * Get the authors between the given revisions or revision IDs.
4014 * Used for diffs and other things that really need it.
4015 *
4016 * @since 1.23
4017 *
4018 * @param int|Revision $old Old revision or rev ID (first before range by default)
4019 * @param int|Revision $new New revision or rev ID (first after range by default)
4020 * @param int $limit Maximum number of authors
4021 * @param string|array $options (Optional): Single option, or an array of options:
4022 * 'include_old' Include $old in the range; $new is excluded.
4023 * 'include_new' Include $new in the range; $old is excluded.
4024 * 'include_both' Include both $old and $new in the range.
4025 * Unknown option values are ignored.
4026 * @return array|null Names of revision authors in the range; null if not both revisions exist
4027 */
4028 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4029 if ( !( $old instanceof Revision ) ) {
4030 $old = Revision::newFromTitle( $this, (int)$old );
4031 }
4032 if ( !( $new instanceof Revision ) ) {
4033 $new = Revision::newFromTitle( $this, (int)$new );
4034 }
4035 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4036 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4037 // in the sanity check below?
4038 if ( !$old || !$new ) {
4039 return null; // nothing to compare
4040 }
4041 $authors = [];
4042 $old_cmp = '>';
4043 $new_cmp = '<';
4044 $options = (array)$options;
4045 if ( in_array( 'include_old', $options ) ) {
4046 $old_cmp = '>=';
4047 }
4048 if ( in_array( 'include_new', $options ) ) {
4049 $new_cmp = '<=';
4050 }
4051 if ( in_array( 'include_both', $options ) ) {
4052 $old_cmp = '>=';
4053 $new_cmp = '<=';
4054 }
4055 // No DB query needed if $old and $new are the same or successive revisions:
4056 if ( $old->getId() === $new->getId() ) {
4057 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4058 [] :
4059 [ $old->getUserText( RevisionRecord::RAW ) ];
4060 } elseif ( $old->getId() === $new->getParentId() ) {
4061 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4062 $authors[] = $oldUserText = $old->getUserText( RevisionRecord::RAW );
4063 $newUserText = $new->getUserText( RevisionRecord::RAW );
4064 if ( $oldUserText != $newUserText ) {
4065 $authors[] = $newUserText;
4066 }
4067 } elseif ( $old_cmp === '>=' ) {
4068 $authors[] = $old->getUserText( RevisionRecord::RAW );
4069 } elseif ( $new_cmp === '<=' ) {
4070 $authors[] = $new->getUserText( RevisionRecord::RAW );
4071 }
4072 return $authors;
4073 }
4074 $dbr = wfGetDB( DB_REPLICA );
4075 $revQuery = Revision::getQueryInfo();
4076 $authors = $dbr->selectFieldValues(
4077 $revQuery['tables'],
4078 $revQuery['fields']['rev_user_text'],
4079 [
4080 'rev_page' => $this->getArticleID(),
4081 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4082 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4083 ], __METHOD__,
4084 [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
4085 $revQuery['joins']
4086 );
4087 return $authors;
4088 }
4089
4090 /**
4091 * Get the number of authors between the given revisions or revision IDs.
4092 * Used for diffs and other things that really need it.
4093 *
4094 * @param int|Revision $old Old revision or rev ID (first before range by default)
4095 * @param int|Revision $new New revision or rev ID (first after range by default)
4096 * @param int $limit Maximum number of authors
4097 * @param string|array $options (Optional): Single option, or an array of options:
4098 * 'include_old' Include $old in the range; $new is excluded.
4099 * 'include_new' Include $new in the range; $old is excluded.
4100 * 'include_both' Include both $old and $new in the range.
4101 * Unknown option values are ignored.
4102 * @return int Number of revision authors in the range; zero if not both revisions exist
4103 */
4104 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4105 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4106 return $authors ? count( $authors ) : 0;
4107 }
4108
4109 /**
4110 * Compare with another title.
4111 *
4112 * @param LinkTarget $title
4113 * @return bool
4114 */
4115 public function equals( LinkTarget $title ) {
4116 // Note: === is necessary for proper matching of number-like titles.
4117 return $this->mInterwiki === $title->getInterwiki()
4118 && $this->mNamespace == $title->getNamespace()
4119 && $this->mDbkeyform === $title->getDBkey();
4120 }
4121
4122 /**
4123 * Check if this title is a subpage of another title
4124 *
4125 * @param Title $title
4126 * @return bool
4127 */
4128 public function isSubpageOf( Title $title ) {
4129 return $this->mInterwiki === $title->mInterwiki
4130 && $this->mNamespace == $title->mNamespace
4131 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
4132 }
4133
4134 /**
4135 * Check if page exists. For historical reasons, this function simply
4136 * checks for the existence of the title in the page table, and will
4137 * thus return false for interwiki links, special pages and the like.
4138 * If you want to know if a title can be meaningfully viewed, you should
4139 * probably call the isKnown() method instead.
4140 *
4141 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
4142 * @return bool
4143 */
4144 public function exists( $flags = 0 ) {
4145 $exists = $this->getArticleID( $flags ) != 0;
4146 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4147 return $exists;
4148 }
4149
4150 /**
4151 * Should links to this title be shown as potentially viewable (i.e. as
4152 * "bluelinks"), even if there's no record by this title in the page
4153 * table?
4154 *
4155 * This function is semi-deprecated for public use, as well as somewhat
4156 * misleadingly named. You probably just want to call isKnown(), which
4157 * calls this function internally.
4158 *
4159 * (ISSUE: Most of these checks are cheap, but the file existence check
4160 * can potentially be quite expensive. Including it here fixes a lot of
4161 * existing code, but we might want to add an optional parameter to skip
4162 * it and any other expensive checks.)
4163 *
4164 * @return bool
4165 */
4166 public function isAlwaysKnown() {
4167 $isKnown = null;
4168
4169 /**
4170 * Allows overriding default behavior for determining if a page exists.
4171 * If $isKnown is kept as null, regular checks happen. If it's
4172 * a boolean, this value is returned by the isKnown method.
4173 *
4174 * @since 1.20
4175 *
4176 * @param Title $title
4177 * @param bool|null $isKnown
4178 */
4179 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4180
4181 if ( !is_null( $isKnown ) ) {
4182 return $isKnown;
4183 }
4184
4185 if ( $this->isExternal() ) {
4186 return true; // any interwiki link might be viewable, for all we know
4187 }
4188
4189 $services = MediaWikiServices::getInstance();
4190 switch ( $this->mNamespace ) {
4191 case NS_MEDIA:
4192 case NS_FILE:
4193 // file exists, possibly in a foreign repo
4194 return (bool)$services->getRepoGroup()->findFile( $this );
4195 case NS_SPECIAL:
4196 // valid special page
4197 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
4198 case NS_MAIN:
4199 // selflink, possibly with fragment
4200 return $this->mDbkeyform == '';
4201 case NS_MEDIAWIKI:
4202 // known system message
4203 return $this->hasSourceText() !== false;
4204 default:
4205 return false;
4206 }
4207 }
4208
4209 /**
4210 * Does this title refer to a page that can (or might) be meaningfully
4211 * viewed? In particular, this function may be used to determine if
4212 * links to the title should be rendered as "bluelinks" (as opposed to
4213 * "redlinks" to non-existent pages).
4214 * Adding something else to this function will cause inconsistency
4215 * since LinkHolderArray calls isAlwaysKnown() and does its own
4216 * page existence check.
4217 *
4218 * @return bool
4219 */
4220 public function isKnown() {
4221 return $this->isAlwaysKnown() || $this->exists();
4222 }
4223
4224 /**
4225 * Does this page have source text?
4226 *
4227 * @return bool
4228 */
4229 public function hasSourceText() {
4230 if ( $this->exists() ) {
4231 return true;
4232 }
4233
4234 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4235 // If the page doesn't exist but is a known system message, default
4236 // message content will be displayed, same for language subpages-
4237 // Use always content language to avoid loading hundreds of languages
4238 // to get the link color.
4239 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4240 list( $name, ) = MessageCache::singleton()->figureMessage(
4241 $contLang->lcfirst( $this->getText() )
4242 );
4243 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4244 return $message->exists();
4245 }
4246
4247 return false;
4248 }
4249
4250 /**
4251 * Get the default (plain) message contents for an page that overrides an
4252 * interface message key.
4253 *
4254 * Primary use cases:
4255 *
4256 * - Article:
4257 * - Show default when viewing the page. The Article::getSubstituteContent
4258 * method displays the default message content, instead of the
4259 * 'noarticletext' placeholder message normally used.
4260 *
4261 * - EditPage:
4262 * - Title of edit page. When creating an interface message override,
4263 * the editor is told they are "Editing the page", instead of
4264 * "Creating the page". (EditPage::setHeaders)
4265 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4266 * or editing a an interface message override. (EditPage::showIntro)
4267 * - Opening the editor. The contents of the localisation message are used
4268 * as contents of the editor when creating a new page in the MediaWiki
4269 * namespace. This simplifies the process for editors when "changing"
4270 * an interface message by creating an override. (EditPage::getContentObject)
4271 * - Showing a diff. The left-hand side of a diff when an editor is
4272 * previewing their changes before saving the creation of a page in the
4273 * MediaWiki namespace. (EditPage::showDiff)
4274 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4275 * page with the proposed content matching the interface message default,
4276 * the save is rejected, the same way we disallow blank pages from being
4277 * created. (EditPage::internalAttemptSave)
4278 *
4279 * - ApiEditPage:
4280 * - Default content, when using the 'prepend' or 'append' feature.
4281 *
4282 * - SkinTemplate:
4283 * - Label the create action as "Edit", if the page can be an override.
4284 *
4285 * @return string|bool
4286 */
4287 public function getDefaultMessageText() {
4288 if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
4289 return false;
4290 }
4291
4292 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4293 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4294 );
4295 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4296
4297 if ( $message->exists() ) {
4298 return $message->plain();
4299 } else {
4300 return false;
4301 }
4302 }
4303
4304 /**
4305 * Updates page_touched for this page; called from LinksUpdate.php
4306 *
4307 * @param string|null $purgeTime [optional] TS_MW timestamp
4308 * @return bool True if the update succeeded
4309 */
4310 public function invalidateCache( $purgeTime = null ) {
4311 if ( wfReadOnly() ) {
4312 return false;
4313 } elseif ( $this->mArticleID === 0 ) {
4314 return true; // avoid gap locking if we know it's not there
4315 }
4316
4317 $dbw = wfGetDB( DB_MASTER );
4318 $dbw->onTransactionPreCommitOrIdle(
4319 function () use ( $dbw ) {
4320 ResourceLoaderWikiModule::invalidateModuleCache(
4321 $this, null, null, $dbw->getDomainID() );
4322 },
4323 __METHOD__
4324 );
4325
4326 $conds = $this->pageCond();
4327 DeferredUpdates::addUpdate(
4328 new AutoCommitUpdate(
4329 $dbw,
4330 __METHOD__,
4331 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4332 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4333 $dbw->update(
4334 'page',
4335 [ 'page_touched' => $dbTimestamp ],
4336 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4337 $fname
4338 );
4339 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4340 }
4341 ),
4342 DeferredUpdates::PRESEND
4343 );
4344
4345 return true;
4346 }
4347
4348 /**
4349 * Update page_touched timestamps and send CDN purge messages for
4350 * pages linking to this title. May be sent to the job queue depending
4351 * on the number of links. Typically called on create and delete.
4352 */
4353 public function touchLinks() {
4354 $jobs = [];
4355 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
4356 $this,
4357 'pagelinks',
4358 [ 'causeAction' => 'page-touch' ]
4359 );
4360 if ( $this->mNamespace == NS_CATEGORY ) {
4361 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
4362 $this,
4363 'categorylinks',
4364 [ 'causeAction' => 'category-touch' ]
4365 );
4366 }
4367
4368 JobQueueGroup::singleton()->lazyPush( $jobs );
4369 }
4370
4371 /**
4372 * Get the last touched timestamp
4373 *
4374 * @param IDatabase|null $db
4375 * @return string|false Last-touched timestamp
4376 */
4377 public function getTouched( $db = null ) {
4378 if ( $db === null ) {
4379 $db = wfGetDB( DB_REPLICA );
4380 }
4381 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4382 return $touched;
4383 }
4384
4385 /**
4386 * Get the timestamp when this page was updated since the user last saw it.
4387 *
4388 * @param User|null $user
4389 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4390 */
4391 public function getNotificationTimestamp( $user = null ) {
4392 global $wgUser;
4393
4394 // Assume current user if none given
4395 if ( !$user ) {
4396 $user = $wgUser;
4397 }
4398 // Check cache first
4399 $uid = $user->getId();
4400 if ( !$uid ) {
4401 return false;
4402 }
4403 // avoid isset here, as it'll return false for null entries
4404 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4405 return $this->mNotificationTimestamp[$uid];
4406 }
4407 // Don't cache too much!
4408 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4409 $this->mNotificationTimestamp = [];
4410 }
4411
4412 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4413 $watchedItem = $store->getWatchedItem( $user, $this );
4414 if ( $watchedItem ) {
4415 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4416 } else {
4417 $this->mNotificationTimestamp[$uid] = false;
4418 }
4419
4420 return $this->mNotificationTimestamp[$uid];
4421 }
4422
4423 /**
4424 * Generate strings used for xml 'id' names in monobook tabs
4425 *
4426 * @param string $prepend Defaults to 'nstab-'
4427 * @return string XML 'id' name
4428 */
4429 public function getNamespaceKey( $prepend = 'nstab-' ) {
4430 // Gets the subject namespace of this title
4431 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
4432 $subjectNS = $nsInfo->getSubject( $this->mNamespace );
4433 // Prefer canonical namespace name for HTML IDs
4434 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4435 if ( $namespaceKey === false ) {
4436 // Fallback to localised text
4437 $namespaceKey = $this->getSubjectNsText();
4438 }
4439 // Makes namespace key lowercase
4440 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4441 // Uses main
4442 if ( $namespaceKey == '' ) {
4443 $namespaceKey = 'main';
4444 }
4445 // Changes file to image for backwards compatibility
4446 if ( $namespaceKey == 'file' ) {
4447 $namespaceKey = 'image';
4448 }
4449 return $prepend . $namespaceKey;
4450 }
4451
4452 /**
4453 * Get all extant redirects to this Title
4454 *
4455 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4456 * @return Title[] Array of Title redirects to this title
4457 */
4458 public function getRedirectsHere( $ns = null ) {
4459 $redirs = [];
4460
4461 $dbr = wfGetDB( DB_REPLICA );
4462 $where = [
4463 'rd_namespace' => $this->mNamespace,
4464 'rd_title' => $this->mDbkeyform,
4465 'rd_from = page_id'
4466 ];
4467 if ( $this->isExternal() ) {
4468 $where['rd_interwiki'] = $this->mInterwiki;
4469 } else {
4470 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4471 }
4472 if ( !is_null( $ns ) ) {
4473 $where['page_namespace'] = $ns;
4474 }
4475
4476 $res = $dbr->select(
4477 [ 'redirect', 'page' ],
4478 [ 'page_namespace', 'page_title' ],
4479 $where,
4480 __METHOD__
4481 );
4482
4483 foreach ( $res as $row ) {
4484 $redirs[] = self::newFromRow( $row );
4485 }
4486 return $redirs;
4487 }
4488
4489 /**
4490 * Check if this Title is a valid redirect target
4491 *
4492 * @return bool
4493 */
4494 public function isValidRedirectTarget() {
4495 global $wgInvalidRedirectTargets;
4496
4497 if ( $this->isSpecialPage() ) {
4498 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4499 if ( $this->isSpecial( 'Userlogout' ) ) {
4500 return false;
4501 }
4502
4503 foreach ( $wgInvalidRedirectTargets as $target ) {
4504 if ( $this->isSpecial( $target ) ) {
4505 return false;
4506 }
4507 }
4508 }
4509
4510 return true;
4511 }
4512
4513 /**
4514 * Get a backlink cache object
4515 *
4516 * @return BacklinkCache
4517 */
4518 public function getBacklinkCache() {
4519 return BacklinkCache::get( $this );
4520 }
4521
4522 /**
4523 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4524 *
4525 * @return bool
4526 */
4527 public function canUseNoindex() {
4528 global $wgExemptFromUserRobotsControl;
4529
4530 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4531 MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
4532
4533 return !in_array( $this->mNamespace, $bannedNamespaces );
4534 }
4535
4536 /**
4537 * Returns the raw sort key to be used for categories, with the specified
4538 * prefix. This will be fed to Collation::getSortKey() to get a
4539 * binary sortkey that can be used for actual sorting.
4540 *
4541 * @param string $prefix The prefix to be used, specified using
4542 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4543 * prefix.
4544 * @return string
4545 */
4546 public function getCategorySortkey( $prefix = '' ) {
4547 $unprefixed = $this->getText();
4548
4549 // Anything that uses this hook should only depend
4550 // on the Title object passed in, and should probably
4551 // tell the users to run updateCollations.php --force
4552 // in order to re-sort existing category relations.
4553 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4554 if ( $prefix !== '' ) {
4555 # Separate with a line feed, so the unprefixed part is only used as
4556 # a tiebreaker when two pages have the exact same prefix.
4557 # In UCA, tab is the only character that can sort above LF
4558 # so we strip both of them from the original prefix.
4559 $prefix = strtr( $prefix, "\n\t", ' ' );
4560 return "$prefix\n$unprefixed";
4561 }
4562 return $unprefixed;
4563 }
4564
4565 /**
4566 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4567 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4568 * the db, it will return NULL.
4569 *
4570 * @return string|null|bool
4571 */
4572 private function getDbPageLanguageCode() {
4573 global $wgPageLanguageUseDB;
4574
4575 // check, if the page language could be saved in the database, and if so and
4576 // the value is not requested already, lookup the page language using LinkCache
4577 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4578 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
4579 $linkCache->addLinkObj( $this );
4580 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4581 }
4582
4583 return $this->mDbPageLanguage;
4584 }
4585
4586 /**
4587 * Get the language in which the content of this page is written in
4588 * wikitext. Defaults to content language, but in certain cases it can be
4589 * e.g. $wgLang (such as special pages, which are in the user language).
4590 *
4591 * @since 1.18
4592 * @return Language
4593 */
4594 public function getPageLanguage() {
4595 global $wgLang, $wgLanguageCode;
4596 if ( $this->isSpecialPage() ) {
4597 // special pages are in the user language
4598 return $wgLang;
4599 }
4600
4601 // Checking if DB language is set
4602 $dbPageLanguage = $this->getDbPageLanguageCode();
4603 if ( $dbPageLanguage ) {
4604 return wfGetLangObj( $dbPageLanguage );
4605 }
4606
4607 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4608 // Note that this may depend on user settings, so the cache should
4609 // be only per-request.
4610 // NOTE: ContentHandler::getPageLanguage() may need to load the
4611 // content to determine the page language!
4612 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4613 // tests.
4614 $contentHandler = ContentHandler::getForTitle( $this );
4615 $langObj = $contentHandler->getPageLanguage( $this );
4616 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4617 } else {
4618 $langObj = Language::factory( $this->mPageLanguage[0] );
4619 }
4620
4621 return $langObj;
4622 }
4623
4624 /**
4625 * Get the language in which the content of this page is written when
4626 * viewed by user. Defaults to content language, but in certain cases it can be
4627 * e.g. $wgLang (such as special pages, which are in the user language).
4628 *
4629 * @since 1.20
4630 * @return Language
4631 */
4632 public function getPageViewLanguage() {
4633 global $wgLang;
4634
4635 if ( $this->isSpecialPage() ) {
4636 // If the user chooses a variant, the content is actually
4637 // in a language whose code is the variant code.
4638 $variant = $wgLang->getPreferredVariant();
4639 if ( $wgLang->getCode() !== $variant ) {
4640 return Language::factory( $variant );
4641 }
4642
4643 return $wgLang;
4644 }
4645
4646 // Checking if DB language is set
4647 $dbPageLanguage = $this->getDbPageLanguageCode();
4648 if ( $dbPageLanguage ) {
4649 $pageLang = wfGetLangObj( $dbPageLanguage );
4650 $variant = $pageLang->getPreferredVariant();
4651 if ( $pageLang->getCode() !== $variant ) {
4652 $pageLang = Language::factory( $variant );
4653 }
4654
4655 return $pageLang;
4656 }
4657
4658 // @note Can't be cached persistently, depends on user settings.
4659 // @note ContentHandler::getPageViewLanguage() may need to load the
4660 // content to determine the page language!
4661 $contentHandler = ContentHandler::getForTitle( $this );
4662 $pageLang = $contentHandler->getPageViewLanguage( $this );
4663 return $pageLang;
4664 }
4665
4666 /**
4667 * Get a list of rendered edit notices for this page.
4668 *
4669 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4670 * they will already be wrapped in paragraphs.
4671 *
4672 * @since 1.21
4673 * @param int $oldid Revision ID that's being edited
4674 * @return array
4675 */
4676 public function getEditNotices( $oldid = 0 ) {
4677 $notices = [];
4678
4679 // Optional notice for the entire namespace
4680 $editnotice_ns = 'editnotice-' . $this->mNamespace;
4681 $msg = wfMessage( $editnotice_ns );
4682 if ( $msg->exists() ) {
4683 $html = $msg->parseAsBlock();
4684 // Edit notices may have complex logic, but output nothing (T91715)
4685 if ( trim( $html ) !== '' ) {
4686 $notices[$editnotice_ns] = Html::rawElement(
4687 'div',
4688 [ 'class' => [
4689 'mw-editnotice',
4690 'mw-editnotice-namespace',
4691 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4692 ] ],
4693 $html
4694 );
4695 }
4696 }
4697
4698 if (
4699 MediaWikiServices::getInstance()->getNamespaceInfo()->
4700 hasSubpages( $this->mNamespace )
4701 ) {
4702 // Optional notice for page itself and any parent page
4703 $editnotice_base = $editnotice_ns;
4704 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
4705 $editnotice_base .= '-' . $part;
4706 $msg = wfMessage( $editnotice_base );
4707 if ( $msg->exists() ) {
4708 $html = $msg->parseAsBlock();
4709 if ( trim( $html ) !== '' ) {
4710 $notices[$editnotice_base] = Html::rawElement(
4711 'div',
4712 [ 'class' => [
4713 'mw-editnotice',
4714 'mw-editnotice-base',
4715 Sanitizer::escapeClass( "mw-$editnotice_base" )
4716 ] ],
4717 $html
4718 );
4719 }
4720 }
4721 }
4722 } else {
4723 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4724 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
4725 $msg = wfMessage( $editnoticeText );
4726 if ( $msg->exists() ) {
4727 $html = $msg->parseAsBlock();
4728 if ( trim( $html ) !== '' ) {
4729 $notices[$editnoticeText] = Html::rawElement(
4730 'div',
4731 [ 'class' => [
4732 'mw-editnotice',
4733 'mw-editnotice-page',
4734 Sanitizer::escapeClass( "mw-$editnoticeText" )
4735 ] ],
4736 $html
4737 );
4738 }
4739 }
4740 }
4741
4742 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4743 return $notices;
4744 }
4745
4746 /**
4747 * @param int $flags Bitfield of class READ_* constants
4748 * @return string|bool
4749 */
4750 private function loadFieldFromDB( $field, $flags ) {
4751 if ( !in_array( $field, self::getSelectFields(), true ) ) {
4752 return false; // field does not exist
4753 }
4754
4755 $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
4756 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
4757
4758 return wfGetDB( $index )->selectField(
4759 'page',
4760 $field,
4761 $this->pageCond(),
4762 __METHOD__,
4763 $options
4764 );
4765 }
4766
4767 /**
4768 * @return array
4769 */
4770 public function __sleep() {
4771 return [
4772 'mNamespace',
4773 'mDbkeyform',
4774 'mFragment',
4775 'mInterwiki',
4776 'mLocalInterwiki',
4777 'mUserCaseDBKey',
4778 'mDefaultNamespace',
4779 ];
4780 }
4781
4782 public function __wakeup() {
4783 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4784 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4785 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4786 }
4787
4788 }