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