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