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