Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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|string[] $query
2069 * @param string|bool $query2 Deprecated
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|string[] $query
2092 * @param string|bool $query2 Deprecated
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