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