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