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