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