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