Merge "Title: Title::getSubpage should not lose the interwiki prefix"
[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 Wikimedia\Assert\Assert;
27 use Wikimedia\Rdbms\Database;
28 use Wikimedia\Rdbms\IDatabase;
29 use MediaWiki\Linker\LinkTarget;
30 use MediaWiki\Interwiki\InterwikiLookup;
31 use MediaWiki\MediaWikiServices;
32
33 /**
34 * Represents a title within MediaWiki.
35 * Optionally may contain an interwiki designation or namespace.
36 * @note This class can fetch various kinds of data from the database;
37 * however, it does so inefficiently.
38 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
39 * and does not rely on global state or the database.
40 */
41 class Title implements LinkTarget, IDBAccessObject {
42 /** @var MapCacheLRU|null */
43 private static $titleCache = null;
44
45 /**
46 * Title::newFromText maintains a cache to avoid expensive re-normalization of
47 * commonly used titles. On a batch operation this can become a memory leak
48 * if not bounded. After hitting this many titles reset the cache.
49 */
50 const CACHE_MAX = 1000;
51
52 /**
53 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
54 * to use the master DB
55 */
56 const GAID_FOR_UPDATE = 1;
57
58 /**
59 * Flag for use with factory methods like newFromLinkTarget() that have
60 * a $forceClone parameter. If set, the method must return a new instance.
61 * Without this flag, some factory methods may return existing instances.
62 *
63 * @since 1.33
64 */
65 const NEW_CLONE = 'clone';
66
67 /**
68 * @name Private member variables
69 * Please use the accessor functions instead.
70 * @private
71 */
72 // @{
73
74 /** @var string Text form (spaces not underscores) of the main part */
75 public $mTextform = '';
76
77 /** @var string URL-encoded form of the main part */
78 public $mUrlform = '';
79
80 /** @var string Main part with underscores */
81 public $mDbkeyform = '';
82
83 /** @var string Database key with the initial letter in the case specified by the user */
84 protected $mUserCaseDBKey;
85
86 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
87 public $mNamespace = NS_MAIN;
88
89 /** @var string Interwiki prefix */
90 public $mInterwiki = '';
91
92 /** @var bool Was this Title created from a string with a local interwiki prefix? */
93 private $mLocalInterwiki = false;
94
95 /** @var string Title fragment (i.e. the bit after the #) */
96 public $mFragment = '';
97
98 /** @var int Article ID, fetched from the link cache on demand */
99 public $mArticleID = -1;
100
101 /** @var bool|int ID of most recent revision */
102 protected $mLatestID = false;
103
104 /**
105 * @var bool|string ID of the page's content model, i.e. one of the
106 * CONTENT_MODEL_XXX constants
107 */
108 private $mContentModel = false;
109
110 /**
111 * @var bool If a content model was forced via setContentModel()
112 * this will be true to avoid having other code paths reset it
113 */
114 private $mForcedContentModel = false;
115
116 /** @var int Estimated number of revisions; null of not loaded */
117 private $mEstimateRevisions;
118
119 /** @var array Array of groups allowed to edit this article */
120 public $mRestrictions = [];
121
122 /**
123 * @var string|bool Comma-separated set of permission keys
124 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
125 * Edit and move sections are separated by a colon
126 * Example: "edit=autoconfirmed,sysop:move=sysop"
127 */
128 protected $mOldRestrictions = false;
129
130 /** @var bool Cascade restrictions on this page to included templates and images? */
131 public $mCascadeRestriction;
132
133 /** Caching the results of getCascadeProtectionSources */
134 public $mCascadingRestrictions;
135
136 /** @var array When do the restrictions on this page expire? */
137 protected $mRestrictionsExpiry = [];
138
139 /** @var bool Are cascading restrictions in effect on this page? */
140 protected $mHasCascadingRestrictions;
141
142 /** @var array Where are the cascading restrictions coming from on this page? */
143 public $mCascadeSources;
144
145 /** @var bool Boolean for initialisation on demand */
146 public $mRestrictionsLoaded = false;
147
148 /**
149 * Text form including namespace/interwiki, initialised on demand
150 *
151 * Only public to share cache with TitleFormatter
152 *
153 * @private
154 * @var string|null
155 */
156 public $prefixedText = null;
157
158 /** @var mixed Cached value for getTitleProtection (create protection) */
159 public $mTitleProtection;
160
161 /**
162 * @var int Namespace index when there is no namespace. Don't change the
163 * following default, NS_MAIN is hardcoded in several places. See T2696.
164 * Zero except in {{transclusion}} tags.
165 */
166 public $mDefaultNamespace = NS_MAIN;
167
168 /** @var int The page length, 0 for special pages */
169 protected $mLength = -1;
170
171 /** @var null Is the article at this title a redirect? */
172 public $mRedirect = null;
173
174 /** @var array Associative array of user ID -> timestamp/false */
175 private $mNotificationTimestamp = [];
176
177 /** @var bool Whether a page has any subpages */
178 private $mHasSubpages;
179
180 /** @var bool The (string) language code of the page's language and content code. */
181 private $mPageLanguage = false;
182
183 /** @var string|bool|null The page language code from the database, null if not saved in
184 * the database or false if not loaded, yet. */
185 private $mDbPageLanguage = false;
186
187 /** @var TitleValue|null A corresponding TitleValue object */
188 private $mTitleValue = null;
189
190 /** @var bool|null Would deleting this page be a big deletion? */
191 private $mIsBigDeletion = null;
192 // @}
193
194 /**
195 * B/C kludge: provide a TitleParser for use by Title.
196 * Ideally, Title would have no methods that need this.
197 * Avoid usage of this singleton by using TitleValue
198 * and the associated services when possible.
199 *
200 * @return TitleFormatter
201 */
202 private static function getTitleFormatter() {
203 return MediaWikiServices::getInstance()->getTitleFormatter();
204 }
205
206 /**
207 * B/C kludge: provide an InterwikiLookup for use by Title.
208 * Ideally, Title would have no methods that need this.
209 * Avoid usage of this singleton by using TitleValue
210 * and the associated services when possible.
211 *
212 * @return InterwikiLookup
213 */
214 private static function getInterwikiLookup() {
215 return MediaWikiServices::getInstance()->getInterwikiLookup();
216 }
217
218 /**
219 * @protected
220 */
221 function __construct() {
222 }
223
224 /**
225 * Create a new Title from a prefixed DB key
226 *
227 * @param string $key The database key, which has underscores
228 * instead of spaces, possibly including namespace and
229 * interwiki prefixes
230 * @return Title|null Title, or null on an error
231 */
232 public static function newFromDBkey( $key ) {
233 $t = new self();
234 $t->mDbkeyform = $key;
235
236 try {
237 $t->secureAndSplit();
238 return $t;
239 } catch ( MalformedTitleException $ex ) {
240 return null;
241 }
242 }
243
244 /**
245 * Returns a Title given a TitleValue.
246 * If the given TitleValue is already a Title instance, that instance is returned,
247 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
248 * is already a Title instance, that instance is copied using the clone operator.
249 *
250 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
251 *
252 * @param TitleValue $titleValue Assumed to be safe.
253 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
254 *
255 * @return Title
256 */
257 public static function newFromTitleValue( TitleValue $titleValue, $forceClone = '' ) {
258 return self::newFromLinkTarget( $titleValue, $forceClone );
259 }
260
261 /**
262 * Returns a Title given a LinkTarget.
263 * If the given LinkTarget is already a Title instance, that instance is returned,
264 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
265 * is already a Title instance, that instance is copied using the clone operator.
266 *
267 * @param LinkTarget $linkTarget Assumed to be safe.
268 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
269 *
270 * @return Title
271 */
272 public static function newFromLinkTarget( LinkTarget $linkTarget, $forceClone = '' ) {
273 if ( $linkTarget instanceof Title ) {
274 // Special case if it's already a Title object
275 if ( $forceClone === self::NEW_CLONE ) {
276 return clone $linkTarget;
277 } else {
278 return $linkTarget;
279 }
280 }
281 return self::makeTitle(
282 $linkTarget->getNamespace(),
283 $linkTarget->getText(),
284 $linkTarget->getFragment(),
285 $linkTarget->getInterwiki()
286 );
287 }
288
289 /**
290 * Same as newFromLinkTarget, but if passed null, returns null.
291 *
292 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
293 *
294 * @return Title|null
295 */
296 public static function castFromLinkTarget( $linkTarget ) {
297 return $linkTarget ? self::newFromLinkTarget( $linkTarget ) : null;
298 }
299
300 /**
301 * Create a new Title from text, such as what one would find in a link. De-
302 * codes any HTML entities in the text.
303 *
304 * Title objects returned by this method are guaranteed to be valid, and
305 * thus return true from the isValid() method.
306 *
307 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
308 * It may instead be a cached instance created previously, with references to it remaining
309 * elsewhere.
310 *
311 * @param string|int|null $text The link text; spaces, prefixes, and an
312 * initial ':' indicating the main namespace are accepted.
313 * @param int $defaultNamespace The namespace to use if none is specified
314 * by a prefix. If you want to force a specific namespace even if
315 * $text might begin with a namespace prefix, use makeTitle() or
316 * makeTitleSafe().
317 * @throws InvalidArgumentException
318 * @return Title|null Title or null on an error.
319 */
320 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
321 // DWIM: Integers can be passed in here when page titles are used as array keys.
322 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
323 throw new InvalidArgumentException( '$text must be a string.' );
324 }
325 if ( $text === null ) {
326 return null;
327 }
328
329 try {
330 return self::newFromTextThrow( (string)$text, $defaultNamespace );
331 } catch ( MalformedTitleException $ex ) {
332 return null;
333 }
334 }
335
336 /**
337 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
338 * rather than returning null.
339 *
340 * The exception subclasses encode detailed information about why the title is invalid.
341 *
342 * Title objects returned by this method are guaranteed to be valid, and
343 * thus return true from the isValid() method.
344 *
345 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
346 * It may instead be a cached instance created previously, with references to it remaining
347 * elsewhere.
348 *
349 * @see Title::newFromText
350 *
351 * @since 1.25
352 * @param string $text Title text to check
353 * @param int $defaultNamespace
354 * @throws MalformedTitleException If the title is invalid
355 * @return Title
356 */
357 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
358 if ( is_object( $text ) ) {
359 throw new MWException( '$text must be a string, given an object' );
360 } elseif ( $text === null ) {
361 // Legacy code relies on MalformedTitleException being thrown in this case
362 // (happens when URL with no title in it is parsed). TODO fix
363 throw new MalformedTitleException( 'title-invalid-empty' );
364 }
365
366 $titleCache = self::getTitleCache();
367
368 // Wiki pages often contain multiple links to the same page.
369 // Title normalization and parsing can become expensive on pages with many
370 // links, so we can save a little time by caching them.
371 // In theory these are value objects and won't get changed...
372 if ( $defaultNamespace == NS_MAIN ) {
373 $t = $titleCache->get( $text );
374 if ( $t ) {
375 return $t;
376 }
377 }
378
379 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
380 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
381
382 $t = new Title();
383 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
384 $t->mDefaultNamespace = (int)$defaultNamespace;
385
386 $t->secureAndSplit();
387 if ( $defaultNamespace == NS_MAIN ) {
388 $titleCache->set( $text, $t );
389 }
390 return $t;
391 }
392
393 /**
394 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
395 *
396 * Example of wrong and broken code:
397 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
398 *
399 * Example of right code:
400 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
401 *
402 * Create a new Title from URL-encoded text. Ensures that
403 * the given title's length does not exceed the maximum.
404 *
405 * @param string $url The title, as might be taken from a URL
406 * @return Title|null The new object, or null on an error
407 */
408 public static function newFromURL( $url ) {
409 $t = new Title();
410
411 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
412 # but some URLs used it as a space replacement and they still come
413 # from some external search tools.
414 if ( strpos( self::legalChars(), '+' ) === false ) {
415 $url = strtr( $url, '+', ' ' );
416 }
417
418 $t->mDbkeyform = strtr( $url, ' ', '_' );
419
420 try {
421 $t->secureAndSplit();
422 return $t;
423 } catch ( MalformedTitleException $ex ) {
424 return null;
425 }
426 }
427
428 /**
429 * @return MapCacheLRU
430 */
431 private static function getTitleCache() {
432 if ( self::$titleCache === null ) {
433 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
434 }
435 return self::$titleCache;
436 }
437
438 /**
439 * Returns a list of fields that are to be selected for initializing Title
440 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
441 * whether to include page_content_model.
442 *
443 * @return array
444 */
445 protected static function getSelectFields() {
446 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
447
448 $fields = [
449 'page_namespace', 'page_title', 'page_id',
450 'page_len', 'page_is_redirect', 'page_latest',
451 ];
452
453 if ( $wgContentHandlerUseDB ) {
454 $fields[] = 'page_content_model';
455 }
456
457 if ( $wgPageLanguageUseDB ) {
458 $fields[] = 'page_lang';
459 }
460
461 return $fields;
462 }
463
464 /**
465 * Create a new Title from an article ID
466 *
467 * @param int $id The page_id corresponding to the Title to create
468 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
469 * @return Title|null The new object, or null on an error
470 */
471 public static function newFromID( $id, $flags = 0 ) {
472 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
473 $row = $db->selectRow(
474 'page',
475 self::getSelectFields(),
476 [ 'page_id' => $id ],
477 __METHOD__
478 );
479 if ( $row !== false ) {
480 $title = self::newFromRow( $row );
481 } else {
482 $title = null;
483 }
484
485 return $title;
486 }
487
488 /**
489 * Make an array of titles from an array of IDs
490 *
491 * @param int[] $ids Array of IDs
492 * @return Title[] Array of Titles
493 */
494 public static function newFromIDs( $ids ) {
495 if ( !count( $ids ) ) {
496 return [];
497 }
498 $dbr = wfGetDB( DB_REPLICA );
499
500 $res = $dbr->select(
501 'page',
502 self::getSelectFields(),
503 [ 'page_id' => $ids ],
504 __METHOD__
505 );
506
507 $titles = [];
508 foreach ( $res as $row ) {
509 $titles[] = self::newFromRow( $row );
510 }
511 return $titles;
512 }
513
514 /**
515 * Make a Title object from a DB row
516 *
517 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
518 * @return Title Corresponding Title
519 */
520 public static function newFromRow( $row ) {
521 $t = self::makeTitle( $row->page_namespace, $row->page_title );
522 $t->loadFromRow( $row );
523 return $t;
524 }
525
526 /**
527 * Load Title object fields from a DB row.
528 * If false is given, the title will be treated as non-existing.
529 *
530 * @param stdClass|bool $row Database row
531 */
532 public function loadFromRow( $row ) {
533 if ( $row ) { // page found
534 if ( isset( $row->page_id ) ) {
535 $this->mArticleID = (int)$row->page_id;
536 }
537 if ( isset( $row->page_len ) ) {
538 $this->mLength = (int)$row->page_len;
539 }
540 if ( isset( $row->page_is_redirect ) ) {
541 $this->mRedirect = (bool)$row->page_is_redirect;
542 }
543 if ( isset( $row->page_latest ) ) {
544 $this->mLatestID = (int)$row->page_latest;
545 }
546 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
547 $this->mContentModel = (string)$row->page_content_model;
548 } elseif ( !$this->mForcedContentModel ) {
549 $this->mContentModel = false; # initialized lazily in getContentModel()
550 }
551 if ( isset( $row->page_lang ) ) {
552 $this->mDbPageLanguage = (string)$row->page_lang;
553 }
554 if ( isset( $row->page_restrictions ) ) {
555 $this->mOldRestrictions = $row->page_restrictions;
556 }
557 } else { // page not found
558 $this->mArticleID = 0;
559 $this->mLength = 0;
560 $this->mRedirect = false;
561 $this->mLatestID = 0;
562 if ( !$this->mForcedContentModel ) {
563 $this->mContentModel = false; # initialized lazily in getContentModel()
564 }
565 }
566 }
567
568 /**
569 * Create a new Title from a namespace index and a DB key.
570 *
571 * It's assumed that $ns and $title are safe, for instance when
572 * they came directly from the database or a special page name,
573 * not from user input.
574 *
575 * No validation is applied. For convenience, spaces are normalized
576 * to underscores, so that e.g. user_text fields can be used directly.
577 *
578 * @note This method may return Title objects that are "invalid"
579 * according to the isValid() method. This is usually caused by
580 * configuration changes: e.g. a namespace that was once defined is
581 * no longer configured, or a character that was once allowed in
582 * titles is now forbidden.
583 *
584 * @param int $ns The namespace of the article
585 * @param string $title The unprefixed database key form
586 * @param string $fragment The link fragment (after the "#")
587 * @param string $interwiki The interwiki prefix
588 * @return Title The new object
589 */
590 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
591 $t = new Title();
592 $t->mInterwiki = $interwiki;
593 $t->mFragment = $fragment;
594 $t->mNamespace = $ns = (int)$ns;
595 $t->mDbkeyform = strtr( $title, ' ', '_' );
596 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
597 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
598 $t->mTextform = strtr( $title, '_', ' ' );
599 $t->mContentModel = false; # initialized lazily in getContentModel()
600 return $t;
601 }
602
603 /**
604 * Create a new Title from a namespace index and a DB key.
605 * The parameters will be checked for validity, which is a bit slower
606 * than makeTitle() but safer for user-provided data.
607 *
608 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
609 * that is, they return true from the isValid() method. If no valid Title
610 * can be constructed from the input, this method returns null.
611 *
612 * @param int $ns The namespace of the article
613 * @param string $title Database key form
614 * @param string $fragment The link fragment (after the "#")
615 * @param string $interwiki Interwiki prefix
616 * @return Title|null The new object, or null on an error
617 */
618 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
619 // NOTE: ideally, this would just call makeTitle() and then isValid(),
620 // but presently, that means more overhead on a potential performance hotspot.
621
622 if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
623 return null;
624 }
625
626 $t = new Title();
627 $t->mDbkeyform = self::makeName( $ns, $title, $fragment, $interwiki, true );
628
629 try {
630 $t->secureAndSplit();
631 return $t;
632 } catch ( MalformedTitleException $ex ) {
633 return null;
634 }
635 }
636
637 /**
638 * Create a new Title for the Main Page
639 *
640 * This uses the 'mainpage' interface message, which could be specified in
641 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
642 * will use the user language, which would involve initialising the session
643 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
644 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
645 * or ResourceloaderContext) to prevent an error.
646 *
647 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
648 * It may instead be a cached instance created previously, with references to it remaining
649 * elsewhere.
650 *
651 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
652 * @return Title
653 */
654 public static function newMainPage( MessageLocalizer $localizer = null ) {
655 if ( $localizer ) {
656 $msg = $localizer->msg( 'mainpage' );
657 } else {
658 $msg = wfMessage( 'mainpage' );
659 }
660
661 $title = self::newFromText( $msg->inContentLanguage()->text() );
662
663 // Every page renders at least one link to the Main Page (e.g. sidebar).
664 // If the localised value is invalid, don't produce fatal errors that
665 // would make the wiki inaccessible (and hard to fix the invalid message).
666 // Gracefully fallback...
667 if ( !$title ) {
668 $title = self::newFromText( 'Main Page' );
669 }
670 return $title;
671 }
672
673 /**
674 * Get the prefixed DB key associated with an ID
675 *
676 * @param int $id The page_id of the article
677 * @return Title|null An object representing the article, or null if no such article was found
678 */
679 public static function nameOf( $id ) {
680 $dbr = wfGetDB( DB_REPLICA );
681
682 $s = $dbr->selectRow(
683 'page',
684 [ 'page_namespace', 'page_title' ],
685 [ 'page_id' => $id ],
686 __METHOD__
687 );
688 if ( $s === false ) {
689 return null;
690 }
691
692 $n = self::makeName( $s->page_namespace, $s->page_title );
693 return $n;
694 }
695
696 /**
697 * Get a regex character class describing the legal characters in a link
698 *
699 * @return string The list of characters, not delimited
700 */
701 public static function legalChars() {
702 global $wgLegalTitleChars;
703 return $wgLegalTitleChars;
704 }
705
706 /**
707 * Utility method for converting a character sequence from bytes to Unicode.
708 *
709 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
710 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
711 *
712 * @param string $byteClass
713 * @return string
714 */
715 public static function convertByteClassToUnicodeClass( $byteClass ) {
716 $length = strlen( $byteClass );
717 // Input token queue
718 $x0 = $x1 = $x2 = '';
719 // Decoded queue
720 $d0 = $d1 = $d2 = '';
721 // Decoded integer codepoints
722 $ord0 = $ord1 = $ord2 = 0;
723 // Re-encoded queue
724 $r0 = $r1 = $r2 = '';
725 // Output
726 $out = '';
727 // Flags
728 $allowUnicode = false;
729 for ( $pos = 0; $pos < $length; $pos++ ) {
730 // Shift the queues down
731 $x2 = $x1;
732 $x1 = $x0;
733 $d2 = $d1;
734 $d1 = $d0;
735 $ord2 = $ord1;
736 $ord1 = $ord0;
737 $r2 = $r1;
738 $r1 = $r0;
739 // Load the current input token and decoded values
740 $inChar = $byteClass[$pos];
741 if ( $inChar == '\\' ) {
742 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
743 $x0 = $inChar . $m[0];
744 $d0 = chr( hexdec( $m[1] ) );
745 $pos += strlen( $m[0] );
746 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
747 $x0 = $inChar . $m[0];
748 $d0 = chr( octdec( $m[0] ) );
749 $pos += strlen( $m[0] );
750 } elseif ( $pos + 1 >= $length ) {
751 $x0 = $d0 = '\\';
752 } else {
753 $d0 = $byteClass[$pos + 1];
754 $x0 = $inChar . $d0;
755 $pos += 1;
756 }
757 } else {
758 $x0 = $d0 = $inChar;
759 }
760 $ord0 = ord( $d0 );
761 // Load the current re-encoded value
762 if ( $ord0 < 32 || $ord0 == 0x7f ) {
763 $r0 = sprintf( '\x%02x', $ord0 );
764 } elseif ( $ord0 >= 0x80 ) {
765 // Allow unicode if a single high-bit character appears
766 $r0 = sprintf( '\x%02x', $ord0 );
767 $allowUnicode = true;
768 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
769 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
770 $r0 = '\\' . $d0;
771 } else {
772 $r0 = $d0;
773 }
774 // Do the output
775 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
776 // Range
777 if ( $ord2 > $ord0 ) {
778 // Empty range
779 } elseif ( $ord0 >= 0x80 ) {
780 // Unicode range
781 $allowUnicode = true;
782 if ( $ord2 < 0x80 ) {
783 // Keep the non-unicode section of the range
784 $out .= "$r2-\\x7F";
785 }
786 } else {
787 // Normal range
788 $out .= "$r2-$r0";
789 }
790 // Reset state to the initial value
791 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
792 } elseif ( $ord2 < 0x80 ) {
793 // ASCII character
794 $out .= $r2;
795 }
796 }
797 if ( $ord1 < 0x80 ) {
798 $out .= $r1;
799 }
800 if ( $ord0 < 0x80 ) {
801 $out .= $r0;
802 }
803 if ( $allowUnicode ) {
804 $out .= '\u0080-\uFFFF';
805 }
806 return $out;
807 }
808
809 /**
810 * Make a prefixed DB key from a DB key and a namespace index
811 *
812 * @param int $ns Numerical representation of the namespace
813 * @param string $title The DB key form the title
814 * @param string $fragment The link fragment (after the "#")
815 * @param string $interwiki The interwiki prefix
816 * @param bool $canonicalNamespace If true, use the canonical name for
817 * $ns instead of the localized version.
818 * @return string The prefixed form of the title
819 */
820 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
821 $canonicalNamespace = false
822 ) {
823 if ( $canonicalNamespace ) {
824 $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
825 getCanonicalName( $ns );
826 } else {
827 $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
828 }
829 $name = $namespace == '' ? $title : "$namespace:$title";
830 if ( strval( $interwiki ) != '' ) {
831 $name = "$interwiki:$name";
832 }
833 if ( strval( $fragment ) != '' ) {
834 $name .= '#' . $fragment;
835 }
836 return $name;
837 }
838
839 /**
840 * Callback for usort() to do title sorts by (namespace, title)
841 *
842 * @param LinkTarget $a
843 * @param LinkTarget $b
844 *
845 * @return int Result of string comparison, or namespace comparison
846 */
847 public static function compare( LinkTarget $a, LinkTarget $b ) {
848 return $a->getNamespace() <=> $b->getNamespace()
849 ?: strcmp( $a->getText(), $b->getText() );
850 }
851
852 /**
853 * Returns true if the title is valid, false if it is invalid.
854 *
855 * Valid titles can be round-tripped via makeTitle() and newFromText().
856 * Their DB key can be used in the database, though it may not have the correct
857 * capitalization.
858 *
859 * Invalid titles may get returned from makeTitle(), and it may be useful to
860 * allow them to exist, e.g. in order to process log entries about pages in
861 * namespaces that belong to extensions that are no longer installed.
862 *
863 * @note This method is relatively expensive. When constructing Title
864 * objects that need to be valid, use an instantiator method that is guaranteed
865 * to return valid titles, such as makeTitleSafe() or newFromText().
866 *
867 * @return bool
868 */
869 public function isValid() {
870 $services = MediaWikiServices::getInstance();
871 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace ) ) {
872 return false;
873 }
874
875 try {
876 $services->getTitleParser()->parseTitle( $this->mDbkeyform, $this->mNamespace );
877 } catch ( MalformedTitleException $ex ) {
878 return false;
879 }
880
881 try {
882 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
883 new TitleValue(
884 $this->mNamespace,
885 $this->mDbkeyform,
886 $this->mFragment,
887 $this->mInterwiki
888 );
889 } catch ( InvalidArgumentException $ex ) {
890 return false;
891 }
892
893 return true;
894 }
895
896 /**
897 * Determine whether the object refers to a page within
898 * this project (either this wiki or a wiki with a local
899 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
900 *
901 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
902 */
903 public function isLocal() {
904 if ( $this->isExternal() ) {
905 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
906 if ( $iw ) {
907 return $iw->isLocal();
908 }
909 }
910 return true;
911 }
912
913 /**
914 * Is this Title interwiki?
915 *
916 * @return bool
917 */
918 public function isExternal() {
919 return $this->mInterwiki !== '';
920 }
921
922 /**
923 * Get the interwiki prefix
924 *
925 * Use Title::isExternal to check if a interwiki is set
926 *
927 * @return string Interwiki prefix
928 */
929 public function getInterwiki() {
930 return $this->mInterwiki;
931 }
932
933 /**
934 * Was this a local interwiki link?
935 *
936 * @return bool
937 */
938 public function wasLocalInterwiki() {
939 return $this->mLocalInterwiki;
940 }
941
942 /**
943 * Determine whether the object refers to a page within
944 * this project and is transcludable.
945 *
946 * @return bool True if this is transcludable
947 */
948 public function isTrans() {
949 if ( !$this->isExternal() ) {
950 return false;
951 }
952
953 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
954 }
955
956 /**
957 * Returns the DB name of the distant wiki which owns the object.
958 *
959 * @return string|false The DB name
960 */
961 public function getTransWikiID() {
962 if ( !$this->isExternal() ) {
963 return false;
964 }
965
966 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
967 }
968
969 /**
970 * Get a TitleValue object representing this Title.
971 *
972 * @note Not all valid Titles have a corresponding valid TitleValue
973 * (e.g. TitleValues cannot represent page-local links that have a
974 * fragment but no title text).
975 *
976 * @return TitleValue|null
977 */
978 public function getTitleValue() {
979 if ( $this->mTitleValue === null ) {
980 try {
981 $this->mTitleValue = new TitleValue(
982 $this->mNamespace,
983 $this->mDbkeyform,
984 $this->mFragment,
985 $this->mInterwiki
986 );
987 } catch ( InvalidArgumentException $ex ) {
988 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
989 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
990 }
991 }
992
993 return $this->mTitleValue;
994 }
995
996 /**
997 * Get the text form (spaces not underscores) of the main part
998 *
999 * @return string Main part of the title
1000 */
1001 public function getText() {
1002 return $this->mTextform;
1003 }
1004
1005 /**
1006 * Get the URL-encoded form of the main part
1007 *
1008 * @return string Main part of the title, URL-encoded
1009 */
1010 public function getPartialURL() {
1011 return $this->mUrlform;
1012 }
1013
1014 /**
1015 * Get the main part with underscores
1016 *
1017 * @return string Main part of the title, with underscores
1018 */
1019 public function getDBkey() {
1020 return $this->mDbkeyform;
1021 }
1022
1023 /**
1024 * Get the DB key with the initial letter case as specified by the user
1025 * @deprecated since 1.33; please use Title::getDBKey() instead
1026 *
1027 * @return string DB key
1028 */
1029 function getUserCaseDBKey() {
1030 if ( !is_null( $this->mUserCaseDBKey ) ) {
1031 return $this->mUserCaseDBKey;
1032 } else {
1033 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1034 return $this->mDbkeyform;
1035 }
1036 }
1037
1038 /**
1039 * Get the namespace index, i.e. one of the NS_xxxx constants.
1040 *
1041 * @return int Namespace index
1042 */
1043 public function getNamespace() {
1044 return $this->mNamespace;
1045 }
1046
1047 /**
1048 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1049 *
1050 * @todo Deprecate this in favor of SlotRecord::getModel()
1051 *
1052 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1053 * @return string Content model id
1054 */
1055 public function getContentModel( $flags = 0 ) {
1056 if ( !$this->mForcedContentModel
1057 && ( !$this->mContentModel || $flags === self::GAID_FOR_UPDATE )
1058 && $this->getArticleID( $flags )
1059 ) {
1060 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1061 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1062 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
1063 }
1064
1065 if ( !$this->mContentModel ) {
1066 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
1067 }
1068
1069 return $this->mContentModel;
1070 }
1071
1072 /**
1073 * Convenience method for checking a title's content model name
1074 *
1075 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1076 * @return bool True if $this->getContentModel() == $id
1077 */
1078 public function hasContentModel( $id ) {
1079 return $this->getContentModel() == $id;
1080 }
1081
1082 /**
1083 * Set a proposed content model for the page for permissions
1084 * checking. This does not actually change the content model
1085 * of a title!
1086 *
1087 * Additionally, you should make sure you've checked
1088 * ContentHandler::canBeUsedOn() first.
1089 *
1090 * @since 1.28
1091 * @param string $model CONTENT_MODEL_XXX constant
1092 */
1093 public function setContentModel( $model ) {
1094 $this->mContentModel = $model;
1095 $this->mForcedContentModel = true;
1096 }
1097
1098 /**
1099 * Get the namespace text
1100 *
1101 * @return string|false Namespace text
1102 */
1103 public function getNsText() {
1104 if ( $this->isExternal() ) {
1105 // This probably shouldn't even happen, except for interwiki transclusion.
1106 // If possible, use the canonical name for the foreign namespace.
1107 $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
1108 getCanonicalName( $this->mNamespace );
1109 if ( $nsText !== false ) {
1110 return $nsText;
1111 }
1112 }
1113
1114 try {
1115 $formatter = self::getTitleFormatter();
1116 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1117 } catch ( InvalidArgumentException $ex ) {
1118 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1119 return false;
1120 }
1121 }
1122
1123 /**
1124 * Get the namespace text of the subject (rather than talk) page
1125 *
1126 * @return string Namespace text
1127 */
1128 public function getSubjectNsText() {
1129 $services = MediaWikiServices::getInstance();
1130 return $services->getContentLanguage()->
1131 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
1132 }
1133
1134 /**
1135 * Get the namespace text of the talk page
1136 *
1137 * @return string Namespace text
1138 */
1139 public function getTalkNsText() {
1140 $services = MediaWikiServices::getInstance();
1141 return $services->getContentLanguage()->
1142 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
1143 }
1144
1145 /**
1146 * Can this title have a corresponding talk page?
1147 *
1148 * False for relative section links (with getText() === ''),
1149 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1150 *
1151 * @see NamespaceInfo::canHaveTalkPage
1152 * @since 1.30
1153 *
1154 * @return bool True if this title either is a talk page or can have a talk page associated.
1155 */
1156 public function canHaveTalkPage() {
1157 return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1158 }
1159
1160 /**
1161 * Is this in a namespace that allows actual pages?
1162 *
1163 * @return bool
1164 */
1165 public function canExist() {
1166 return $this->mNamespace >= NS_MAIN;
1167 }
1168
1169 /**
1170 * Can this title be added to a user's watchlist?
1171 *
1172 * False for relative section links (with getText() === ''),
1173 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1174 *
1175 * @return bool
1176 */
1177 public function isWatchable() {
1178 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
1179 return $this->getText() !== '' && !$this->isExternal() &&
1180 $nsInfo->isWatchable( $this->mNamespace );
1181 }
1182
1183 /**
1184 * Returns true if this is a special page.
1185 *
1186 * @return bool
1187 */
1188 public function isSpecialPage() {
1189 return $this->mNamespace == NS_SPECIAL;
1190 }
1191
1192 /**
1193 * Returns true if this title resolves to the named special page
1194 *
1195 * @param string $name The special page name
1196 * @return bool
1197 */
1198 public function isSpecial( $name ) {
1199 if ( $this->isSpecialPage() ) {
1200 list( $thisName, /* $subpage */ ) =
1201 MediaWikiServices::getInstance()->getSpecialPageFactory()->
1202 resolveAlias( $this->mDbkeyform );
1203 if ( $name == $thisName ) {
1204 return true;
1205 }
1206 }
1207 return false;
1208 }
1209
1210 /**
1211 * If the Title refers to a special page alias which is not the local default, resolve
1212 * the alias, and localise the name as necessary. Otherwise, return $this
1213 *
1214 * @return Title
1215 */
1216 public function fixSpecialName() {
1217 if ( $this->isSpecialPage() ) {
1218 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1219 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform );
1220 if ( $canonicalName ) {
1221 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1222 if ( $localName != $this->mDbkeyform ) {
1223 return self::makeTitle( NS_SPECIAL, $localName );
1224 }
1225 }
1226 }
1227 return $this;
1228 }
1229
1230 /**
1231 * Returns true if the title is inside the specified namespace.
1232 *
1233 * Please make use of this instead of comparing to getNamespace()
1234 * This function is much more resistant to changes we may make
1235 * to namespaces than code that makes direct comparisons.
1236 * @param int $ns The namespace
1237 * @return bool
1238 * @since 1.19
1239 */
1240 public function inNamespace( $ns ) {
1241 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1242 equals( $this->mNamespace, $ns );
1243 }
1244
1245 /**
1246 * Returns true if the title is inside one of the specified namespaces.
1247 *
1248 * @param int|int[] $namespaces,... The namespaces to check for
1249 * @return bool
1250 * @since 1.19
1251 */
1252 public function inNamespaces( /* ... */ ) {
1253 $namespaces = func_get_args();
1254 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1255 $namespaces = $namespaces[0];
1256 }
1257
1258 foreach ( $namespaces as $ns ) {
1259 if ( $this->inNamespace( $ns ) ) {
1260 return true;
1261 }
1262 }
1263
1264 return false;
1265 }
1266
1267 /**
1268 * Returns true if the title has the same subject namespace as the
1269 * namespace specified.
1270 * For example this method will take NS_USER and return true if namespace
1271 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1272 * as their subject namespace.
1273 *
1274 * This is MUCH simpler than individually testing for equivalence
1275 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1276 * @since 1.19
1277 * @param int $ns
1278 * @return bool
1279 */
1280 public function hasSubjectNamespace( $ns ) {
1281 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1282 subjectEquals( $this->mNamespace, $ns );
1283 }
1284
1285 /**
1286 * Is this Title in a namespace which contains content?
1287 * In other words, is this a content page, for the purposes of calculating
1288 * statistics, etc?
1289 *
1290 * @return bool
1291 */
1292 public function isContentPage() {
1293 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1294 isContent( $this->mNamespace );
1295 }
1296
1297 /**
1298 * Would anybody with sufficient privileges be able to move this page?
1299 * Some pages just aren't movable.
1300 *
1301 * @return bool
1302 */
1303 public function isMovable() {
1304 if (
1305 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1306 isMovable( $this->mNamespace ) || $this->isExternal()
1307 ) {
1308 // Interwiki title or immovable namespace. Hooks don't get to override here
1309 return false;
1310 }
1311
1312 $result = true;
1313 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1314 return $result;
1315 }
1316
1317 /**
1318 * Is this the mainpage?
1319 * @note Title::newFromText seems to be sufficiently optimized by the title
1320 * cache that we don't need to over-optimize by doing direct comparisons and
1321 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1322 * ends up reporting something differently than $title->isMainPage();
1323 *
1324 * @since 1.18
1325 * @return bool
1326 */
1327 public function isMainPage() {
1328 return $this->equals( self::newMainPage() );
1329 }
1330
1331 /**
1332 * Is this a subpage?
1333 *
1334 * @return bool
1335 */
1336 public function isSubpage() {
1337 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1338 hasSubpages( $this->mNamespace )
1339 ? strpos( $this->getText(), '/' ) !== false
1340 : false;
1341 }
1342
1343 /**
1344 * Is this a conversion table for the LanguageConverter?
1345 *
1346 * @return bool
1347 */
1348 public function isConversionTable() {
1349 // @todo ConversionTable should become a separate content model.
1350
1351 return $this->mNamespace == NS_MEDIAWIKI &&
1352 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1353 }
1354
1355 /**
1356 * Does that page contain wikitext, or it is JS, CSS or whatever?
1357 *
1358 * @return bool
1359 */
1360 public function isWikitextPage() {
1361 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1362 }
1363
1364 /**
1365 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1366 * global UI. This is generally true for pages in the MediaWiki namespace having
1367 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1368 *
1369 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1370 * for that!
1371 *
1372 * Note that this method should not return true for pages that contain and show
1373 * "inactive" CSS, JSON, or JS.
1374 *
1375 * @return bool
1376 * @since 1.31
1377 */
1378 public function isSiteConfigPage() {
1379 return (
1380 $this->isSiteCssConfigPage()
1381 || $this->isSiteJsonConfigPage()
1382 || $this->isSiteJsConfigPage()
1383 );
1384 }
1385
1386 /**
1387 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1388 *
1389 * @return bool
1390 * @since 1.31
1391 */
1392 public function isUserConfigPage() {
1393 return (
1394 $this->isUserCssConfigPage()
1395 || $this->isUserJsonConfigPage()
1396 || $this->isUserJsConfigPage()
1397 );
1398 }
1399
1400 /**
1401 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1402 *
1403 * @return string Containing skin name from .css, .json, or .js subpage title
1404 * @since 1.31
1405 */
1406 public function getSkinFromConfigSubpage() {
1407 $subpage = explode( '/', $this->mTextform );
1408 $subpage = $subpage[count( $subpage ) - 1];
1409 $lastdot = strrpos( $subpage, '.' );
1410 if ( $lastdot === false ) {
1411 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1412 }
1413 return substr( $subpage, 0, $lastdot );
1414 }
1415
1416 /**
1417 * Is this a CSS "config" sub-page of a user page?
1418 *
1419 * @return bool
1420 * @since 1.31
1421 */
1422 public function isUserCssConfigPage() {
1423 return (
1424 NS_USER == $this->mNamespace
1425 && $this->isSubpage()
1426 && $this->hasContentModel( CONTENT_MODEL_CSS )
1427 );
1428 }
1429
1430 /**
1431 * Is this a JSON "config" sub-page of a user page?
1432 *
1433 * @return bool
1434 * @since 1.31
1435 */
1436 public function isUserJsonConfigPage() {
1437 return (
1438 NS_USER == $this->mNamespace
1439 && $this->isSubpage()
1440 && $this->hasContentModel( CONTENT_MODEL_JSON )
1441 );
1442 }
1443
1444 /**
1445 * Is this a JS "config" sub-page of a user page?
1446 *
1447 * @return bool
1448 * @since 1.31
1449 */
1450 public function isUserJsConfigPage() {
1451 return (
1452 NS_USER == $this->mNamespace
1453 && $this->isSubpage()
1454 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1455 );
1456 }
1457
1458 /**
1459 * Is this a sitewide CSS "config" page?
1460 *
1461 * @return bool
1462 * @since 1.32
1463 */
1464 public function isSiteCssConfigPage() {
1465 return (
1466 NS_MEDIAWIKI == $this->mNamespace
1467 && (
1468 $this->hasContentModel( CONTENT_MODEL_CSS )
1469 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1470 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1471 || substr( $this->mDbkeyform, -4 ) === '.css'
1472 )
1473 );
1474 }
1475
1476 /**
1477 * Is this a sitewide JSON "config" page?
1478 *
1479 * @return bool
1480 * @since 1.32
1481 */
1482 public function isSiteJsonConfigPage() {
1483 return (
1484 NS_MEDIAWIKI == $this->mNamespace
1485 && (
1486 $this->hasContentModel( CONTENT_MODEL_JSON )
1487 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1488 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1489 || substr( $this->mDbkeyform, -5 ) === '.json'
1490 )
1491 );
1492 }
1493
1494 /**
1495 * Is this a sitewide JS "config" page?
1496 *
1497 * @return bool
1498 * @since 1.31
1499 */
1500 public function isSiteJsConfigPage() {
1501 return (
1502 NS_MEDIAWIKI == $this->mNamespace
1503 && (
1504 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1505 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1506 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1507 || substr( $this->mDbkeyform, -3 ) === '.js'
1508 )
1509 );
1510 }
1511
1512 /**
1513 * Is this a message which can contain raw HTML?
1514 *
1515 * @return bool
1516 * @since 1.32
1517 */
1518 public function isRawHtmlMessage() {
1519 global $wgRawHtmlMessages;
1520
1521 if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1522 return false;
1523 }
1524 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1525 return in_array( $message, $wgRawHtmlMessages, true );
1526 }
1527
1528 /**
1529 * Is this a talk page of some sort?
1530 *
1531 * @return bool
1532 */
1533 public function isTalkPage() {
1534 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1535 isTalk( $this->mNamespace );
1536 }
1537
1538 /**
1539 * Get a Title object associated with the talk page of this article
1540 *
1541 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1542 * with NamespaceInfo::canHaveTalkPage().
1543 * @return Title The object for the talk page
1544 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1545 * or because it's a relative link, or an interwiki link.
1546 */
1547 public function getTalkPage() {
1548 return self::castFromLinkTarget(
1549 MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1550 }
1551
1552 /**
1553 * Get a Title object associated with the talk page of this article,
1554 * if such a talk page can exist.
1555 *
1556 * @since 1.30
1557 *
1558 * @return Title|null The object for the talk page,
1559 * or null if no associated talk page can exist, according to canHaveTalkPage().
1560 */
1561 public function getTalkPageIfDefined() {
1562 if ( !$this->canHaveTalkPage() ) {
1563 return null;
1564 }
1565
1566 return $this->getTalkPage();
1567 }
1568
1569 /**
1570 * Get a title object associated with the subject page of this
1571 * talk page
1572 *
1573 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1574 * @return Title The object for the subject page
1575 */
1576 public function getSubjectPage() {
1577 return self::castFromLinkTarget(
1578 MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1579 }
1580
1581 /**
1582 * Get the other title for this page, if this is a subject page
1583 * get the talk page, if it is a subject page get the talk page
1584 *
1585 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1586 * @since 1.25
1587 * @throws MWException If the page doesn't have an other page
1588 * @return Title
1589 */
1590 public function getOtherPage() {
1591 return self::castFromLinkTarget(
1592 MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1593 }
1594
1595 /**
1596 * Get the default namespace index, for when there is no namespace
1597 *
1598 * @return int Default namespace index
1599 */
1600 public function getDefaultNamespace() {
1601 return $this->mDefaultNamespace;
1602 }
1603
1604 /**
1605 * Get the Title fragment (i.e.\ the bit after the #) in text form
1606 *
1607 * Use Title::hasFragment to check for a fragment
1608 *
1609 * @return string Title fragment
1610 */
1611 public function getFragment() {
1612 return $this->mFragment;
1613 }
1614
1615 /**
1616 * Check if a Title fragment is set
1617 *
1618 * @return bool
1619 * @since 1.23
1620 */
1621 public function hasFragment() {
1622 return $this->mFragment !== '';
1623 }
1624
1625 /**
1626 * Get the fragment in URL form, including the "#" character if there is one
1627 *
1628 * @return string Fragment in URL form
1629 */
1630 public function getFragmentForURL() {
1631 if ( !$this->hasFragment() ) {
1632 return '';
1633 } elseif ( $this->isExternal() ) {
1634 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1635 // so we treat it like a local interwiki.
1636 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1637 if ( $interwiki && !$interwiki->isLocal() ) {
1638 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1639 }
1640 }
1641
1642 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1643 }
1644
1645 /**
1646 * Set the fragment for this title. Removes the first character from the
1647 * specified fragment before setting, so it assumes you're passing it with
1648 * an initial "#".
1649 *
1650 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1651 * or Title::createFragmentTarget().
1652 * Still in active use privately.
1653 *
1654 * @private
1655 * @param string $fragment Text
1656 */
1657 public function setFragment( $fragment ) {
1658 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1659 }
1660
1661 /**
1662 * Creates a new Title for a different fragment of the same page.
1663 *
1664 * @since 1.27
1665 * @param string $fragment
1666 * @return Title
1667 */
1668 public function createFragmentTarget( $fragment ) {
1669 return self::makeTitle(
1670 $this->mNamespace,
1671 $this->getText(),
1672 $fragment,
1673 $this->mInterwiki
1674 );
1675 }
1676
1677 /**
1678 * Prefix some arbitrary text with the namespace or interwiki prefix
1679 * of this object
1680 *
1681 * @param string $name The text
1682 * @return string The prefixed text
1683 */
1684 private function prefix( $name ) {
1685 $p = '';
1686 if ( $this->isExternal() ) {
1687 $p = $this->mInterwiki . ':';
1688 }
1689
1690 if ( $this->mNamespace != 0 ) {
1691 $nsText = $this->getNsText();
1692
1693 if ( $nsText === false ) {
1694 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1695 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1696 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1697 }
1698
1699 $p .= $nsText . ':';
1700 }
1701 return $p . $name;
1702 }
1703
1704 /**
1705 * Get the prefixed database key form
1706 *
1707 * @return string The prefixed title, with underscores and
1708 * any interwiki and namespace prefixes
1709 */
1710 public function getPrefixedDBkey() {
1711 $s = $this->prefix( $this->mDbkeyform );
1712 $s = strtr( $s, ' ', '_' );
1713 return $s;
1714 }
1715
1716 /**
1717 * Get the prefixed title with spaces.
1718 * This is the form usually used for display
1719 *
1720 * @return string The prefixed title, with spaces
1721 */
1722 public function getPrefixedText() {
1723 if ( $this->prefixedText === null ) {
1724 $s = $this->prefix( $this->mTextform );
1725 $s = strtr( $s, '_', ' ' );
1726 $this->prefixedText = $s;
1727 }
1728 return $this->prefixedText;
1729 }
1730
1731 /**
1732 * Return a string representation of this title
1733 *
1734 * @return string Representation of this title
1735 */
1736 public function __toString() {
1737 return $this->getPrefixedText();
1738 }
1739
1740 /**
1741 * Get the prefixed title with spaces, plus any fragment
1742 * (part beginning with '#')
1743 *
1744 * @return string The prefixed title, with spaces and the fragment, including '#'
1745 */
1746 public function getFullText() {
1747 $text = $this->getPrefixedText();
1748 if ( $this->hasFragment() ) {
1749 $text .= '#' . $this->mFragment;
1750 }
1751 return $text;
1752 }
1753
1754 /**
1755 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1756 *
1757 * @note the return value may contain trailing whitespace and is thus
1758 * not safe for use with makeTitle or TitleValue.
1759 *
1760 * @par Example:
1761 * @code
1762 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1763 * # returns: 'Foo'
1764 * @endcode
1765 *
1766 * @return string Root name
1767 * @since 1.20
1768 */
1769 public function getRootText() {
1770 if (
1771 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1772 hasSubpages( $this->mNamespace )
1773 ) {
1774 return $this->getText();
1775 }
1776
1777 return strtok( $this->getText(), '/' );
1778 }
1779
1780 /**
1781 * Get the root page name title, i.e. the leftmost part before any slashes
1782 *
1783 * @par Example:
1784 * @code
1785 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1786 * # returns: Title{User:Foo}
1787 * @endcode
1788 *
1789 * @return Title Root title
1790 * @since 1.20
1791 */
1792 public function getRootTitle() {
1793 $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1794 Assert::postcondition(
1795 $title !== null,
1796 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1797 );
1798 return $title;
1799 }
1800
1801 /**
1802 * Get the base page name without a namespace, i.e. the part before the subpage name
1803 *
1804 * @note the return value may contain trailing whitespace and is thus
1805 * not safe for use with makeTitle or TitleValue.
1806 *
1807 * @par Example:
1808 * @code
1809 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1810 * # returns: 'Foo/Bar'
1811 * @endcode
1812 *
1813 * @return string Base name
1814 */
1815 public function getBaseText() {
1816 $text = $this->getText();
1817 if (
1818 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1819 hasSubpages( $this->mNamespace )
1820 ) {
1821 return $text;
1822 }
1823
1824 $lastSlashPos = strrpos( $text, '/' );
1825 // Don't discard the real title if there's no subpage involved
1826 if ( $lastSlashPos === false ) {
1827 return $text;
1828 }
1829
1830 return substr( $text, 0, $lastSlashPos );
1831 }
1832
1833 /**
1834 * Get the base page name title, i.e. the part before the subpage name.
1835 *
1836 * @par Example:
1837 * @code
1838 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1839 * # returns: Title{User:Foo/Bar}
1840 * @endcode
1841 *
1842 * @return Title Base title
1843 * @since 1.20
1844 */
1845 public function getBaseTitle() {
1846 $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
1847 Assert::postcondition(
1848 $title !== null,
1849 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1850 );
1851 return $title;
1852 }
1853
1854 /**
1855 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1856 *
1857 * @par Example:
1858 * @code
1859 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1860 * # returns: "Baz"
1861 * @endcode
1862 *
1863 * @return string Subpage name
1864 */
1865 public function getSubpageText() {
1866 if (
1867 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1868 hasSubpages( $this->mNamespace )
1869 ) {
1870 return $this->mTextform;
1871 }
1872 $parts = explode( '/', $this->mTextform );
1873 return $parts[count( $parts ) - 1];
1874 }
1875
1876 /**
1877 * Get the title for a subpage of the current page
1878 *
1879 * @par Example:
1880 * @code
1881 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1882 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1883 * @endcode
1884 *
1885 * @param string $text The subpage name to add to the title
1886 * @return Title|null Subpage title, or null on an error
1887 * @since 1.20
1888 */
1889 public function getSubpage( $text ) {
1890 return self::makeTitleSafe(
1891 $this->mNamespace,
1892 $this->getText() . '/' . $text,
1893 '',
1894 $this->mInterwiki
1895 );
1896 }
1897
1898 /**
1899 * Get a URL-encoded form of the subpage text
1900 *
1901 * @return string URL-encoded subpage name
1902 */
1903 public function getSubpageUrlForm() {
1904 $text = $this->getSubpageText();
1905 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1906 return $text;
1907 }
1908
1909 /**
1910 * Get a URL-encoded title (not an actual URL) including interwiki
1911 *
1912 * @return string The URL-encoded form
1913 */
1914 public function getPrefixedURL() {
1915 $s = $this->prefix( $this->mDbkeyform );
1916 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1917 return $s;
1918 }
1919
1920 /**
1921 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1922 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1923 * second argument named variant. This was deprecated in favor
1924 * of passing an array of option with a "variant" key
1925 * Once $query2 is removed for good, this helper can be dropped
1926 * and the wfArrayToCgi moved to getLocalURL();
1927 *
1928 * @since 1.19 (r105919)
1929 * @param array|string $query
1930 * @param string|string[]|bool $query2
1931 * @return string
1932 */
1933 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1934 if ( $query2 !== false ) {
1935 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1936 "method called with a second parameter is deprecated. Add your " .
1937 "parameter to an array passed as the first parameter.", "1.19" );
1938 }
1939 if ( is_array( $query ) ) {
1940 $query = wfArrayToCgi( $query );
1941 }
1942 if ( $query2 ) {
1943 if ( is_string( $query2 ) ) {
1944 // $query2 is a string, we will consider this to be
1945 // a deprecated $variant argument and add it to the query
1946 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1947 } else {
1948 $query2 = wfArrayToCgi( $query2 );
1949 }
1950 // If we have $query content add a & to it first
1951 if ( $query ) {
1952 $query .= '&';
1953 }
1954 // Now append the queries together
1955 $query .= $query2;
1956 }
1957 return $query;
1958 }
1959
1960 /**
1961 * Get a real URL referring to this title, with interwiki link and
1962 * fragment
1963 *
1964 * @see self::getLocalURL for the arguments.
1965 * @see wfExpandUrl
1966 * @param string|string[] $query
1967 * @param string|string[]|bool $query2
1968 * @param string|int|null $proto Protocol type to use in URL
1969 * @return string The URL
1970 */
1971 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1972 $query = self::fixUrlQueryArgs( $query, $query2 );
1973
1974 # Hand off all the decisions on urls to getLocalURL
1975 $url = $this->getLocalURL( $query );
1976
1977 # Expand the url to make it a full url. Note that getLocalURL has the
1978 # potential to output full urls for a variety of reasons, so we use
1979 # wfExpandUrl instead of simply prepending $wgServer
1980 $url = wfExpandUrl( $url, $proto );
1981
1982 # Finally, add the fragment.
1983 $url .= $this->getFragmentForURL();
1984 // Avoid PHP 7.1 warning from passing $this by reference
1985 $titleRef = $this;
1986 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1987 return $url;
1988 }
1989
1990 /**
1991 * Get a url appropriate for making redirects based on an untrusted url arg
1992 *
1993 * This is basically the same as getFullUrl(), but in the case of external
1994 * interwikis, we send the user to a landing page, to prevent possible
1995 * phishing attacks and the like.
1996 *
1997 * @note Uses current protocol by default, since technically relative urls
1998 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1999 * places where the url gets cached, as might pollute between
2000 * https and non-https users.
2001 * @see self::getLocalURL for the arguments.
2002 * @param array|string $query
2003 * @param string $proto Protocol type to use in URL
2004 * @return string A url suitable to use in an HTTP location header.
2005 */
2006 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2007 $target = $this;
2008 if ( $this->isExternal() ) {
2009 $target = SpecialPage::getTitleFor(
2010 'GoToInterwiki',
2011 $this->getPrefixedDBkey()
2012 );
2013 }
2014 return $target->getFullURL( $query, false, $proto );
2015 }
2016
2017 /**
2018 * Get a URL with no fragment or server name (relative URL) from a Title object.
2019 * If this page is generated with action=render, however,
2020 * $wgServer is prepended to make an absolute URL.
2021 *
2022 * @see self::getFullURL to always get an absolute URL.
2023 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2024 * valid to link, locally, to the current Title.
2025 * @see self::newFromText to produce a Title object.
2026 *
2027 * @param string|string[] $query An optional query string,
2028 * not used for interwiki links. Can be specified as an associative array as well,
2029 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2030 * Some query patterns will trigger various shorturl path replacements.
2031 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2032 * be an array. If a string is passed it will be interpreted as a deprecated
2033 * variant argument and urlencoded into a variant= argument.
2034 * This second query argument will be added to the $query
2035 * The second parameter is deprecated since 1.19. Pass it as a key,value
2036 * pair in the first parameter array instead.
2037 *
2038 * @return string String of the URL.
2039 */
2040 public function getLocalURL( $query = '', $query2 = false ) {
2041 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
2042
2043 $query = self::fixUrlQueryArgs( $query, $query2 );
2044
2045 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2046 if ( $interwiki ) {
2047 $namespace = $this->getNsText();
2048 if ( $namespace != '' ) {
2049 # Can this actually happen? Interwikis shouldn't be parsed.
2050 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2051 $namespace .= ':';
2052 }
2053 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2054 $url = wfAppendQuery( $url, $query );
2055 } else {
2056 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2057 if ( $query == '' ) {
2058 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2059 // Avoid PHP 7.1 warning from passing $this by reference
2060 $titleRef = $this;
2061 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2062 } else {
2063 global $wgVariantArticlePath, $wgActionPaths;
2064 $url = false;
2065 $matches = [];
2066
2067 if ( !empty( $wgActionPaths )
2068 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2069 ) {
2070 $action = urldecode( $matches[2] );
2071 if ( isset( $wgActionPaths[$action] ) ) {
2072 $query = $matches[1];
2073 if ( isset( $matches[4] ) ) {
2074 $query .= $matches[4];
2075 }
2076 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2077 if ( $query != '' ) {
2078 $url = wfAppendQuery( $url, $query );
2079 }
2080 }
2081 }
2082
2083 if ( $url === false
2084 && $wgVariantArticlePath
2085 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2086 && $this->getPageLanguage()->equals(
2087 MediaWikiServices::getInstance()->getContentLanguage() )
2088 && $this->getPageLanguage()->hasVariants()
2089 ) {
2090 $variant = urldecode( $matches[1] );
2091 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2092 // Only do the variant replacement if the given variant is a valid
2093 // variant for the page's language.
2094 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2095 $url = str_replace( '$1', $dbkey, $url );
2096 }
2097 }
2098
2099 if ( $url === false ) {
2100 if ( $query == '-' ) {
2101 $query = '';
2102 }
2103 $url = "{$wgScript}?title={$dbkey}&{$query}";
2104 }
2105 }
2106 // Avoid PHP 7.1 warning from passing $this by reference
2107 $titleRef = $this;
2108 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2109
2110 // @todo FIXME: This causes breakage in various places when we
2111 // actually expected a local URL and end up with dupe prefixes.
2112 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2113 $url = $wgServer . $url;
2114 }
2115 }
2116 // Avoid PHP 7.1 warning from passing $this by reference
2117 $titleRef = $this;
2118 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2119 return $url;
2120 }
2121
2122 /**
2123 * Get a URL that's the simplest URL that will be valid to link, locally,
2124 * to the current Title. It includes the fragment, but does not include
2125 * the server unless action=render is used (or the link is external). If
2126 * there's a fragment but the prefixed text is empty, we just return a link
2127 * to the fragment.
2128 *
2129 * The result obviously should not be URL-escaped, but does need to be
2130 * HTML-escaped if it's being output in HTML.
2131 *
2132 * @param string|string[] $query
2133 * @param bool $query2
2134 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2135 * or false (default) for no expansion
2136 * @see self::getLocalURL for the arguments.
2137 * @return string The URL
2138 */
2139 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2140 if ( $this->isExternal() || $proto !== false ) {
2141 $ret = $this->getFullURL( $query, $query2, $proto );
2142 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2143 $ret = $this->getFragmentForURL();
2144 } else {
2145 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2146 }
2147 return $ret;
2148 }
2149
2150 /**
2151 * Get the URL form for an internal link.
2152 * - Used in various CDN-related code, in case we have a different
2153 * internal hostname for the server from the exposed one.
2154 *
2155 * This uses $wgInternalServer to qualify the path, or $wgServer
2156 * if $wgInternalServer is not set. If the server variable used is
2157 * protocol-relative, the URL will be expanded to http://
2158 *
2159 * @see self::getLocalURL for the arguments.
2160 * @param string|string[] $query
2161 * @param string|bool $query2 Deprecated
2162 * @return string The URL
2163 */
2164 public function getInternalURL( $query = '', $query2 = false ) {
2165 global $wgInternalServer, $wgServer;
2166 $query = self::fixUrlQueryArgs( $query, $query2 );
2167 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2168 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2169 // Avoid PHP 7.1 warning from passing $this by reference
2170 $titleRef = $this;
2171 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2172 return $url;
2173 }
2174
2175 /**
2176 * Get the URL for a canonical link, for use in things like IRC and
2177 * e-mail notifications. Uses $wgCanonicalServer and the
2178 * GetCanonicalURL hook.
2179 *
2180 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2181 *
2182 * @see self::getLocalURL for the arguments.
2183 * @param string|string[] $query
2184 * @param string|bool $query2 Deprecated
2185 * @return string The URL
2186 * @since 1.18
2187 */
2188 public function getCanonicalURL( $query = '', $query2 = false ) {
2189 $query = self::fixUrlQueryArgs( $query, $query2 );
2190 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2191 // Avoid PHP 7.1 warning from passing $this by reference
2192 $titleRef = $this;
2193 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2194 return $url;
2195 }
2196
2197 /**
2198 * Get the edit URL for this Title
2199 *
2200 * @return string The URL, or a null string if this is an interwiki link
2201 */
2202 public function getEditURL() {
2203 if ( $this->isExternal() ) {
2204 return '';
2205 }
2206 $s = $this->getLocalURL( 'action=edit' );
2207
2208 return $s;
2209 }
2210
2211 /**
2212 * Can $user perform $action on this page?
2213 * This skips potentially expensive cascading permission checks
2214 * as well as avoids expensive error formatting
2215 *
2216 * Suitable for use for nonessential UI controls in common cases, but
2217 * _not_ for functional access control.
2218 *
2219 * May provide false positives, but should never provide a false negative.
2220 *
2221 * @param string $action Action that permission needs to be checked for
2222 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2223 *
2224 * @return bool
2225 * @throws Exception
2226 *
2227 * @deprecated since 1.33,
2228 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2229 *
2230 */
2231 public function quickUserCan( $action, $user = null ) {
2232 return $this->userCan( $action, $user, false );
2233 }
2234
2235 /**
2236 * Can $user perform $action on this page?
2237 *
2238 * @param string $action Action that permission needs to be checked for
2239 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2240 * provided.
2241 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2242 *
2243 * @return bool
2244 * @throws Exception
2245 *
2246 * @deprecated since 1.33,
2247 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2248 *
2249 */
2250 public function userCan( $action, $user = null, $rigor = PermissionManager::RIGOR_SECURE ) {
2251 if ( !$user instanceof User ) {
2252 global $wgUser;
2253 $user = $wgUser;
2254 }
2255
2256 // TODO: this is for b/c, eventually will be removed
2257 if ( $rigor === true ) {
2258 $rigor = PermissionManager::RIGOR_SECURE; // b/c
2259 } elseif ( $rigor === false ) {
2260 $rigor = PermissionManager::RIGOR_QUICK; // b/c
2261 }
2262
2263 return MediaWikiServices::getInstance()->getPermissionManager()
2264 ->userCan( $action, $user, $this, $rigor );
2265 }
2266
2267 /**
2268 * Can $user perform $action on this page?
2269 *
2270 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2271 *
2272 * @param string $action Action that permission needs to be checked for
2273 * @param User $user User to check
2274 * @param string $rigor One of (quick,full,secure)
2275 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2276 * - full : does cheap and expensive checks possibly from a replica DB
2277 * - secure : does cheap and expensive checks, using the master as needed
2278 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2279 * whose corresponding errors may be ignored.
2280 *
2281 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2282 * @throws Exception
2283 *
2284 * @deprecated since 1.33,
2285 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2286 *
2287 */
2288 public function getUserPermissionsErrors(
2289 $action, $user, $rigor = PermissionManager::RIGOR_SECURE, $ignoreErrors = []
2290 ) {
2291 // TODO: this is for b/c, eventually will be removed
2292 if ( $rigor === true ) {
2293 $rigor = PermissionManager::RIGOR_SECURE; // b/c
2294 } elseif ( $rigor === false ) {
2295 $rigor = PermissionManager::RIGOR_QUICK; // b/c
2296 }
2297
2298 return MediaWikiServices::getInstance()->getPermissionManager()
2299 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2300 }
2301
2302 /**
2303 * Get a filtered list of all restriction types supported by this wiki.
2304 * @param bool $exists True to get all restriction types that apply to
2305 * titles that do exist, False for all restriction types that apply to
2306 * titles that do not exist
2307 * @return array
2308 */
2309 public static function getFilteredRestrictionTypes( $exists = true ) {
2310 global $wgRestrictionTypes;
2311 $types = $wgRestrictionTypes;
2312 if ( $exists ) {
2313 # Remove the create restriction for existing titles
2314 $types = array_diff( $types, [ 'create' ] );
2315 } else {
2316 # Only the create and upload restrictions apply to non-existing titles
2317 $types = array_intersect( $types, [ 'create', 'upload' ] );
2318 }
2319 return $types;
2320 }
2321
2322 /**
2323 * Returns restriction types for the current Title
2324 *
2325 * @return array Applicable restriction types
2326 */
2327 public function getRestrictionTypes() {
2328 if ( $this->isSpecialPage() ) {
2329 return [];
2330 }
2331
2332 $types = self::getFilteredRestrictionTypes( $this->exists() );
2333
2334 if ( $this->mNamespace != NS_FILE ) {
2335 # Remove the upload restriction for non-file titles
2336 $types = array_diff( $types, [ 'upload' ] );
2337 }
2338
2339 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2340
2341 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2342 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2343
2344 return $types;
2345 }
2346
2347 /**
2348 * Is this title subject to title protection?
2349 * Title protection is the one applied against creation of such title.
2350 *
2351 * @return array|bool An associative array representing any existent title
2352 * protection, or false if there's none.
2353 */
2354 public function getTitleProtection() {
2355 $protection = $this->getTitleProtectionInternal();
2356 if ( $protection ) {
2357 if ( $protection['permission'] == 'sysop' ) {
2358 $protection['permission'] = 'editprotected'; // B/C
2359 }
2360 if ( $protection['permission'] == 'autoconfirmed' ) {
2361 $protection['permission'] = 'editsemiprotected'; // B/C
2362 }
2363 }
2364 return $protection;
2365 }
2366
2367 /**
2368 * Fetch title protection settings
2369 *
2370 * To work correctly, $this->loadRestrictions() needs to have access to the
2371 * actual protections in the database without munging 'sysop' =>
2372 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2373 * callers probably want $this->getTitleProtection() instead.
2374 *
2375 * @return array|bool
2376 */
2377 protected function getTitleProtectionInternal() {
2378 // Can't protect pages in special namespaces
2379 if ( $this->mNamespace < 0 ) {
2380 return false;
2381 }
2382
2383 // Can't protect pages that exist.
2384 if ( $this->exists() ) {
2385 return false;
2386 }
2387
2388 if ( $this->mTitleProtection === null ) {
2389 $dbr = wfGetDB( DB_REPLICA );
2390 $commentStore = CommentStore::getStore();
2391 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2392 $res = $dbr->select(
2393 [ 'protected_titles' ] + $commentQuery['tables'],
2394 [
2395 'user' => 'pt_user',
2396 'expiry' => 'pt_expiry',
2397 'permission' => 'pt_create_perm'
2398 ] + $commentQuery['fields'],
2399 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2400 __METHOD__,
2401 [],
2402 $commentQuery['joins']
2403 );
2404
2405 // fetchRow returns false if there are no rows.
2406 $row = $dbr->fetchRow( $res );
2407 if ( $row ) {
2408 $this->mTitleProtection = [
2409 'user' => $row['user'],
2410 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2411 'permission' => $row['permission'],
2412 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
2413 ];
2414 } else {
2415 $this->mTitleProtection = false;
2416 }
2417 }
2418 return $this->mTitleProtection;
2419 }
2420
2421 /**
2422 * Remove any title protection due to page existing
2423 */
2424 public function deleteTitleProtection() {
2425 $dbw = wfGetDB( DB_MASTER );
2426
2427 $dbw->delete(
2428 'protected_titles',
2429 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2430 __METHOD__
2431 );
2432 $this->mTitleProtection = false;
2433 }
2434
2435 /**
2436 * Is this page "semi-protected" - the *only* protection levels are listed
2437 * in $wgSemiprotectedRestrictionLevels?
2438 *
2439 * @param string $action Action to check (default: edit)
2440 * @return bool
2441 */
2442 public function isSemiProtected( $action = 'edit' ) {
2443 global $wgSemiprotectedRestrictionLevels;
2444
2445 $restrictions = $this->getRestrictions( $action );
2446 $semi = $wgSemiprotectedRestrictionLevels;
2447 if ( !$restrictions || !$semi ) {
2448 // Not protected, or all protection is full protection
2449 return false;
2450 }
2451
2452 // Remap autoconfirmed to editsemiprotected for BC
2453 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2454 $semi[$key] = 'editsemiprotected';
2455 }
2456 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2457 $restrictions[$key] = 'editsemiprotected';
2458 }
2459
2460 return !array_diff( $restrictions, $semi );
2461 }
2462
2463 /**
2464 * Does the title correspond to a protected article?
2465 *
2466 * @param string $action The action the page is protected from,
2467 * by default checks all actions.
2468 * @return bool
2469 */
2470 public function isProtected( $action = '' ) {
2471 global $wgRestrictionLevels;
2472
2473 $restrictionTypes = $this->getRestrictionTypes();
2474
2475 # Special pages have inherent protection
2476 if ( $this->isSpecialPage() ) {
2477 return true;
2478 }
2479
2480 # Check regular protection levels
2481 foreach ( $restrictionTypes as $type ) {
2482 if ( $action == $type || $action == '' ) {
2483 $r = $this->getRestrictions( $type );
2484 foreach ( $wgRestrictionLevels as $level ) {
2485 if ( in_array( $level, $r ) && $level != '' ) {
2486 return true;
2487 }
2488 }
2489 }
2490 }
2491
2492 return false;
2493 }
2494
2495 /**
2496 * Determines if $user is unable to edit this page because it has been protected
2497 * by $wgNamespaceProtection.
2498 *
2499 * @param User $user User object to check permissions
2500 * @return bool
2501 */
2502 public function isNamespaceProtected( User $user ) {
2503 global $wgNamespaceProtection;
2504
2505 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2506 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2507 if ( $right != '' && !$user->isAllowed( $right ) ) {
2508 return true;
2509 }
2510 }
2511 }
2512 return false;
2513 }
2514
2515 /**
2516 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2517 *
2518 * @return bool If the page is subject to cascading restrictions.
2519 */
2520 public function isCascadeProtected() {
2521 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2522 return ( $sources > 0 );
2523 }
2524
2525 /**
2526 * Determines whether cascading protection sources have already been loaded from
2527 * the database.
2528 *
2529 * @param bool $getPages True to check if the pages are loaded, or false to check
2530 * if the status is loaded.
2531 * @return bool Whether or not the specified information has been loaded
2532 * @since 1.23
2533 */
2534 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2535 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2536 }
2537
2538 /**
2539 * Cascading protection: Get the source of any cascading restrictions on this page.
2540 *
2541 * @param bool $getPages Whether or not to retrieve the actual pages
2542 * that the restrictions have come from and the actual restrictions
2543 * themselves.
2544 * @return array Two elements: First is an array of Title objects of the
2545 * pages from which cascading restrictions have come, false for
2546 * none, or true if such restrictions exist but $getPages was not
2547 * set. Second is an array like that returned by
2548 * Title::getAllRestrictions(), or an empty array if $getPages is
2549 * false.
2550 */
2551 public function getCascadeProtectionSources( $getPages = true ) {
2552 $pagerestrictions = [];
2553
2554 if ( $this->mCascadeSources !== null && $getPages ) {
2555 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2556 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2557 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2558 }
2559
2560 $dbr = wfGetDB( DB_REPLICA );
2561
2562 if ( $this->mNamespace == NS_FILE ) {
2563 $tables = [ 'imagelinks', 'page_restrictions' ];
2564 $where_clauses = [
2565 'il_to' => $this->mDbkeyform,
2566 'il_from=pr_page',
2567 'pr_cascade' => 1
2568 ];
2569 } else {
2570 $tables = [ 'templatelinks', 'page_restrictions' ];
2571 $where_clauses = [
2572 'tl_namespace' => $this->mNamespace,
2573 'tl_title' => $this->mDbkeyform,
2574 'tl_from=pr_page',
2575 'pr_cascade' => 1
2576 ];
2577 }
2578
2579 if ( $getPages ) {
2580 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2581 'pr_expiry', 'pr_type', 'pr_level' ];
2582 $where_clauses[] = 'page_id=pr_page';
2583 $tables[] = 'page';
2584 } else {
2585 $cols = [ 'pr_expiry' ];
2586 }
2587
2588 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2589
2590 $sources = $getPages ? [] : false;
2591 $now = wfTimestampNow();
2592
2593 foreach ( $res as $row ) {
2594 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2595 if ( $expiry > $now ) {
2596 if ( $getPages ) {
2597 $page_id = $row->pr_page;
2598 $page_ns = $row->page_namespace;
2599 $page_title = $row->page_title;
2600 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
2601 # Add groups needed for each restriction type if its not already there
2602 # Make sure this restriction type still exists
2603
2604 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2605 $pagerestrictions[$row->pr_type] = [];
2606 }
2607
2608 if (
2609 isset( $pagerestrictions[$row->pr_type] )
2610 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2611 ) {
2612 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2613 }
2614 } else {
2615 $sources = true;
2616 }
2617 }
2618 }
2619
2620 if ( $getPages ) {
2621 $this->mCascadeSources = $sources;
2622 $this->mCascadingRestrictions = $pagerestrictions;
2623 } else {
2624 $this->mHasCascadingRestrictions = $sources;
2625 }
2626
2627 return [ $sources, $pagerestrictions ];
2628 }
2629
2630 /**
2631 * Accessor for mRestrictionsLoaded
2632 *
2633 * @return bool Whether or not the page's restrictions have already been
2634 * loaded from the database
2635 * @since 1.23
2636 */
2637 public function areRestrictionsLoaded() {
2638 return $this->mRestrictionsLoaded;
2639 }
2640
2641 /**
2642 * Accessor/initialisation for mRestrictions
2643 *
2644 * @param string $action Action that permission needs to be checked for
2645 * @return array Restriction levels needed to take the action. All levels are
2646 * required. Note that restriction levels are normally user rights, but 'sysop'
2647 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2648 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2649 */
2650 public function getRestrictions( $action ) {
2651 if ( !$this->mRestrictionsLoaded ) {
2652 $this->loadRestrictions();
2653 }
2654 return $this->mRestrictions[$action] ?? [];
2655 }
2656
2657 /**
2658 * Accessor/initialisation for mRestrictions
2659 *
2660 * @return array Keys are actions, values are arrays as returned by
2661 * Title::getRestrictions()
2662 * @since 1.23
2663 */
2664 public function getAllRestrictions() {
2665 if ( !$this->mRestrictionsLoaded ) {
2666 $this->loadRestrictions();
2667 }
2668 return $this->mRestrictions;
2669 }
2670
2671 /**
2672 * Get the expiry time for the restriction against a given action
2673 *
2674 * @param string $action
2675 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2676 * or not protected at all, or false if the action is not recognised.
2677 */
2678 public function getRestrictionExpiry( $action ) {
2679 if ( !$this->mRestrictionsLoaded ) {
2680 $this->loadRestrictions();
2681 }
2682 return $this->mRestrictionsExpiry[$action] ?? false;
2683 }
2684
2685 /**
2686 * Returns cascading restrictions for the current article
2687 *
2688 * @return bool
2689 */
2690 function areRestrictionsCascading() {
2691 if ( !$this->mRestrictionsLoaded ) {
2692 $this->loadRestrictions();
2693 }
2694
2695 return $this->mCascadeRestriction;
2696 }
2697
2698 /**
2699 * Compiles list of active page restrictions from both page table (pre 1.10)
2700 * and page_restrictions table for this existing page.
2701 * Public for usage by LiquidThreads.
2702 *
2703 * @param array $rows Array of db result objects
2704 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2705 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2706 * Edit and move sections are separated by a colon
2707 * Example: "edit=autoconfirmed,sysop:move=sysop"
2708 */
2709 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2710 // This function will only read rows from a table that we migrated away
2711 // from before adding READ_LATEST support to loadRestrictions, so we
2712 // don't need to support reading from DB_MASTER here.
2713 $dbr = wfGetDB( DB_REPLICA );
2714
2715 $restrictionTypes = $this->getRestrictionTypes();
2716
2717 foreach ( $restrictionTypes as $type ) {
2718 $this->mRestrictions[$type] = [];
2719 $this->mRestrictionsExpiry[$type] = 'infinity';
2720 }
2721
2722 $this->mCascadeRestriction = false;
2723
2724 # Backwards-compatibility: also load the restrictions from the page record (old format).
2725 if ( $oldFashionedRestrictions !== null ) {
2726 $this->mOldRestrictions = $oldFashionedRestrictions;
2727 }
2728
2729 if ( $this->mOldRestrictions === false ) {
2730 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2731 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2732 $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2733 }
2734
2735 if ( $this->mOldRestrictions != '' ) {
2736 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2737 $temp = explode( '=', trim( $restrict ) );
2738 if ( count( $temp ) == 1 ) {
2739 // old old format should be treated as edit/move restriction
2740 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2741 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2742 } else {
2743 $restriction = trim( $temp[1] );
2744 if ( $restriction != '' ) { // some old entries are empty
2745 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2746 }
2747 }
2748 }
2749 }
2750
2751 if ( count( $rows ) ) {
2752 # Current system - load second to make them override.
2753 $now = wfTimestampNow();
2754
2755 # Cycle through all the restrictions.
2756 foreach ( $rows as $row ) {
2757 // Don't take care of restrictions types that aren't allowed
2758 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2759 continue;
2760 }
2761
2762 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2763
2764 // Only apply the restrictions if they haven't expired!
2765 if ( !$expiry || $expiry > $now ) {
2766 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2767 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2768
2769 $this->mCascadeRestriction |= $row->pr_cascade;
2770 }
2771 }
2772 }
2773
2774 $this->mRestrictionsLoaded = true;
2775 }
2776
2777 /**
2778 * Load restrictions from the page_restrictions table
2779 *
2780 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2781 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2782 * Edit and move sections are separated by a colon
2783 * Example: "edit=autoconfirmed,sysop:move=sysop"
2784 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2785 * from the master DB.
2786 */
2787 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2788 $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
2789 if ( $this->mRestrictionsLoaded && !$readLatest ) {
2790 return;
2791 }
2792
2793 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2794 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2795 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2796 $id = $this->getArticleID();
2797 if ( $id ) {
2798 $fname = __METHOD__;
2799 $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
2800 return iterator_to_array(
2801 $dbr->select(
2802 'page_restrictions',
2803 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2804 [ 'pr_page' => $id ],
2805 $fname
2806 )
2807 );
2808 };
2809
2810 if ( $readLatest ) {
2811 $dbr = wfGetDB( DB_MASTER );
2812 $rows = $loadRestrictionsFromDb( $dbr );
2813 } else {
2814 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2815 $rows = $cache->getWithSetCallback(
2816 // Page protections always leave a new null revision
2817 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2818 $cache::TTL_DAY,
2819 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2820 $dbr = wfGetDB( DB_REPLICA );
2821
2822 $setOpts += Database::getCacheSetOptions( $dbr );
2823 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2824 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2825 // @TODO: cleanup Title cache and caller assumption mess in general
2826 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2827 }
2828
2829 return $loadRestrictionsFromDb( $dbr );
2830 }
2831 );
2832 }
2833
2834 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2835 } else {
2836 $title_protection = $this->getTitleProtectionInternal();
2837
2838 if ( $title_protection ) {
2839 $now = wfTimestampNow();
2840 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
2841
2842 if ( !$expiry || $expiry > $now ) {
2843 // Apply the restrictions
2844 $this->mRestrictionsExpiry['create'] = $expiry;
2845 $this->mRestrictions['create'] =
2846 explode( ',', trim( $title_protection['permission'] ) );
2847 } else { // Get rid of the old restrictions
2848 $this->mTitleProtection = false;
2849 }
2850 } else {
2851 $this->mRestrictionsExpiry['create'] = 'infinity';
2852 }
2853 $this->mRestrictionsLoaded = true;
2854 }
2855 }
2856
2857 /**
2858 * Flush the protection cache in this object and force reload from the database.
2859 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2860 */
2861 public function flushRestrictions() {
2862 $this->mRestrictionsLoaded = false;
2863 $this->mTitleProtection = null;
2864 }
2865
2866 /**
2867 * Purge expired restrictions from the page_restrictions table
2868 *
2869 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2870 */
2871 static function purgeExpiredRestrictions() {
2872 if ( wfReadOnly() ) {
2873 return;
2874 }
2875
2876 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2877 wfGetDB( DB_MASTER ),
2878 __METHOD__,
2879 function ( IDatabase $dbw, $fname ) {
2880 $config = MediaWikiServices::getInstance()->getMainConfig();
2881 $ids = $dbw->selectFieldValues(
2882 'page_restrictions',
2883 'pr_id',
2884 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2885 $fname,
2886 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2887 );
2888 if ( $ids ) {
2889 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2890 }
2891 }
2892 ) );
2893
2894 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2895 wfGetDB( DB_MASTER ),
2896 __METHOD__,
2897 function ( IDatabase $dbw, $fname ) {
2898 $dbw->delete(
2899 'protected_titles',
2900 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2901 $fname
2902 );
2903 }
2904 ) );
2905 }
2906
2907 /**
2908 * Does this have subpages? (Warning, usually requires an extra DB query.)
2909 *
2910 * @return bool
2911 */
2912 public function hasSubpages() {
2913 if (
2914 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2915 hasSubpages( $this->mNamespace )
2916 ) {
2917 # Duh
2918 return false;
2919 }
2920
2921 # We dynamically add a member variable for the purpose of this method
2922 # alone to cache the result. There's no point in having it hanging
2923 # around uninitialized in every Title object; therefore we only add it
2924 # if needed and don't declare it statically.
2925 if ( $this->mHasSubpages === null ) {
2926 $this->mHasSubpages = false;
2927 $subpages = $this->getSubpages( 1 );
2928 if ( $subpages instanceof TitleArray ) {
2929 $this->mHasSubpages = (bool)$subpages->current();
2930 }
2931 }
2932
2933 return $this->mHasSubpages;
2934 }
2935
2936 /**
2937 * Get all subpages of this page.
2938 *
2939 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2940 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2941 * doesn't allow subpages
2942 */
2943 public function getSubpages( $limit = -1 ) {
2944 if (
2945 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2946 hasSubpages( $this->mNamespace )
2947 ) {
2948 return [];
2949 }
2950
2951 $dbr = wfGetDB( DB_REPLICA );
2952 $conds['page_namespace'] = $this->mNamespace;
2953 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
2954 $options = [];
2955 if ( $limit > -1 ) {
2956 $options['LIMIT'] = $limit;
2957 }
2958 return TitleArray::newFromResult(
2959 $dbr->select( 'page',
2960 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2961 $conds,
2962 __METHOD__,
2963 $options
2964 )
2965 );
2966 }
2967
2968 /**
2969 * Is there a version of this page in the deletion archive?
2970 *
2971 * @return int The number of archived revisions
2972 */
2973 public function isDeleted() {
2974 if ( $this->mNamespace < 0 ) {
2975 $n = 0;
2976 } else {
2977 $dbr = wfGetDB( DB_REPLICA );
2978
2979 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2980 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
2981 __METHOD__
2982 );
2983 if ( $this->mNamespace == NS_FILE ) {
2984 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2985 [ 'fa_name' => $this->mDbkeyform ],
2986 __METHOD__
2987 );
2988 }
2989 }
2990 return (int)$n;
2991 }
2992
2993 /**
2994 * Is there a version of this page in the deletion archive?
2995 *
2996 * @return bool
2997 */
2998 public function isDeletedQuick() {
2999 if ( $this->mNamespace < 0 ) {
3000 return false;
3001 }
3002 $dbr = wfGetDB( DB_REPLICA );
3003 $deleted = (bool)$dbr->selectField( 'archive', '1',
3004 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3005 __METHOD__
3006 );
3007 if ( !$deleted && $this->mNamespace == NS_FILE ) {
3008 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3009 [ 'fa_name' => $this->mDbkeyform ],
3010 __METHOD__
3011 );
3012 }
3013 return $deleted;
3014 }
3015
3016 /**
3017 * Get the article ID for this Title from the link cache,
3018 * adding it if necessary
3019 *
3020 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3021 * for update
3022 * @return int The ID
3023 */
3024 public function getArticleID( $flags = 0 ) {
3025 if ( $this->mNamespace < 0 ) {
3026 $this->mArticleID = 0;
3027 return $this->mArticleID;
3028 }
3029 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3030 if ( $flags & self::GAID_FOR_UPDATE ) {
3031 $oldUpdate = $linkCache->forUpdate( true );
3032 $linkCache->clearLink( $this );
3033 $this->mArticleID = $linkCache->addLinkObj( $this );
3034 $linkCache->forUpdate( $oldUpdate );
3035 } elseif ( $this->mArticleID == -1 ) {
3036 $this->mArticleID = $linkCache->addLinkObj( $this );
3037 }
3038 return $this->mArticleID;
3039 }
3040
3041 /**
3042 * Is this an article that is a redirect page?
3043 * Uses link cache, adding it if necessary
3044 *
3045 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3046 * @return bool
3047 */
3048 public function isRedirect( $flags = 0 ) {
3049 if ( !is_null( $this->mRedirect ) ) {
3050 return $this->mRedirect;
3051 }
3052 if ( !$this->getArticleID( $flags ) ) {
3053 $this->mRedirect = false;
3054 return $this->mRedirect;
3055 }
3056
3057 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3058 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3059 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3060 if ( $cached === null ) {
3061 # Trust LinkCache's state over our own
3062 # LinkCache is telling us that the page doesn't exist, despite there being cached
3063 # data relating to an existing page in $this->mArticleID. Updaters should clear
3064 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3065 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3066 # LinkCache to refresh its data from the master.
3067 $this->mRedirect = false;
3068 return $this->mRedirect;
3069 }
3070
3071 $this->mRedirect = (bool)$cached;
3072
3073 return $this->mRedirect;
3074 }
3075
3076 /**
3077 * What is the length of this page?
3078 * Uses link cache, adding it if necessary
3079 *
3080 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3081 * @return int
3082 */
3083 public function getLength( $flags = 0 ) {
3084 if ( $this->mLength != -1 ) {
3085 return $this->mLength;
3086 }
3087 if ( !$this->getArticleID( $flags ) ) {
3088 $this->mLength = 0;
3089 return $this->mLength;
3090 }
3091 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3092 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3093 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3094 if ( $cached === null ) {
3095 # Trust LinkCache's state over our own, as for isRedirect()
3096 $this->mLength = 0;
3097 return $this->mLength;
3098 }
3099
3100 $this->mLength = intval( $cached );
3101
3102 return $this->mLength;
3103 }
3104
3105 /**
3106 * What is the page_latest field for this page?
3107 *
3108 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3109 * @return int Int or 0 if the page doesn't exist
3110 */
3111 public function getLatestRevID( $flags = 0 ) {
3112 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3113 return intval( $this->mLatestID );
3114 }
3115 if ( !$this->getArticleID( $flags ) ) {
3116 $this->mLatestID = 0;
3117 return $this->mLatestID;
3118 }
3119 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3120 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3121 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3122 if ( $cached === null ) {
3123 # Trust LinkCache's state over our own, as for isRedirect()
3124 $this->mLatestID = 0;
3125 return $this->mLatestID;
3126 }
3127
3128 $this->mLatestID = intval( $cached );
3129
3130 return $this->mLatestID;
3131 }
3132
3133 /**
3134 * This clears some fields in this object, and clears any associated
3135 * keys in the "bad links" section of the link cache.
3136 *
3137 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3138 * loading of the new page_id. It's also called from
3139 * WikiPage::doDeleteArticleReal()
3140 *
3141 * @param int $newid The new Article ID
3142 */
3143 public function resetArticleID( $newid ) {
3144 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3145 $linkCache->clearLink( $this );
3146
3147 if ( $newid === false ) {
3148 $this->mArticleID = -1;
3149 } else {
3150 $this->mArticleID = intval( $newid );
3151 }
3152 $this->mRestrictionsLoaded = false;
3153 $this->mRestrictions = [];
3154 $this->mOldRestrictions = false;
3155 $this->mRedirect = null;
3156 $this->mLength = -1;
3157 $this->mLatestID = false;
3158 $this->mContentModel = false;
3159 $this->mEstimateRevisions = null;
3160 $this->mPageLanguage = false;
3161 $this->mDbPageLanguage = false;
3162 $this->mIsBigDeletion = null;
3163 }
3164
3165 public static function clearCaches() {
3166 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3167 $linkCache->clear();
3168
3169 $titleCache = self::getTitleCache();
3170 $titleCache->clear();
3171 }
3172
3173 /**
3174 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3175 *
3176 * @param string $text Containing title to capitalize
3177 * @param int $ns Namespace index, defaults to NS_MAIN
3178 * @return string Containing capitalized title
3179 */
3180 public static function capitalize( $text, $ns = NS_MAIN ) {
3181 $services = MediaWikiServices::getInstance();
3182 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3183 return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text );
3184 } else {
3185 return $text;
3186