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