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