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