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