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