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