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