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