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