0ee57c8b8a84b566ec5939f023c0bfa9e514dd79
[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, IDBAccessObject {
40 /** @var MapCacheLRU */
41 private static $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 * @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 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1614 // so we treat it like a local interwiki.
1615 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1616 if ( $interwiki && !$interwiki->isLocal() ) {
1617 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1618 }
1619 }
1620
1621 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1622 }
1623
1624 /**
1625 * Set the fragment for this title. Removes the first character from the
1626 * specified fragment before setting, so it assumes you're passing it with
1627 * an initial "#".
1628 *
1629 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1630 * or Title::createFragmentTarget().
1631 * Still in active use privately.
1632 *
1633 * @private
1634 * @param string $fragment Text
1635 */
1636 public function setFragment( $fragment ) {
1637 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1638 }
1639
1640 /**
1641 * Creates a new Title for a different fragment of the same page.
1642 *
1643 * @since 1.27
1644 * @param string $fragment
1645 * @return Title
1646 */
1647 public function createFragmentTarget( $fragment ) {
1648 return self::makeTitle(
1649 $this->mNamespace,
1650 $this->getText(),
1651 $fragment,
1652 $this->mInterwiki
1653 );
1654 }
1655
1656 /**
1657 * Prefix some arbitrary text with the namespace or interwiki prefix
1658 * of this object
1659 *
1660 * @param string $name The text
1661 * @return string The prefixed text
1662 */
1663 private function prefix( $name ) {
1664 $p = '';
1665 if ( $this->isExternal() ) {
1666 $p = $this->mInterwiki . ':';
1667 }
1668
1669 if ( $this->mNamespace != 0 ) {
1670 $nsText = $this->getNsText();
1671
1672 if ( $nsText === false ) {
1673 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1674 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1675 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1676 }
1677
1678 $p .= $nsText . ':';
1679 }
1680 return $p . $name;
1681 }
1682
1683 /**
1684 * Get the prefixed database key form
1685 *
1686 * @return string The prefixed title, with underscores and
1687 * any interwiki and namespace prefixes
1688 */
1689 public function getPrefixedDBkey() {
1690 $s = $this->prefix( $this->mDbkeyform );
1691 $s = strtr( $s, ' ', '_' );
1692 return $s;
1693 }
1694
1695 /**
1696 * Get the prefixed title with spaces.
1697 * This is the form usually used for display
1698 *
1699 * @return string The prefixed title, with spaces
1700 */
1701 public function getPrefixedText() {
1702 if ( $this->prefixedText === null ) {
1703 $s = $this->prefix( $this->mTextform );
1704 $s = strtr( $s, '_', ' ' );
1705 $this->prefixedText = $s;
1706 }
1707 return $this->prefixedText;
1708 }
1709
1710 /**
1711 * Return a string representation of this title
1712 *
1713 * @return string Representation of this title
1714 */
1715 public function __toString() {
1716 return $this->getPrefixedText();
1717 }
1718
1719 /**
1720 * Get the prefixed title with spaces, plus any fragment
1721 * (part beginning with '#')
1722 *
1723 * @return string The prefixed title, with spaces and the fragment, including '#'
1724 */
1725 public function getFullText() {
1726 $text = $this->getPrefixedText();
1727 if ( $this->hasFragment() ) {
1728 $text .= '#' . $this->mFragment;
1729 }
1730 return $text;
1731 }
1732
1733 /**
1734 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1735 *
1736 * @par Example:
1737 * @code
1738 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1739 * # returns: 'Foo'
1740 * @endcode
1741 *
1742 * @return string Root name
1743 * @since 1.20
1744 */
1745 public function getRootText() {
1746 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1747 return $this->getText();
1748 }
1749
1750 return strtok( $this->getText(), '/' );
1751 }
1752
1753 /**
1754 * Get the root page name title, i.e. the leftmost part before any slashes
1755 *
1756 * @par Example:
1757 * @code
1758 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1759 * # returns: Title{User:Foo}
1760 * @endcode
1761 *
1762 * @return Title Root title
1763 * @since 1.20
1764 */
1765 public function getRootTitle() {
1766 return self::makeTitle( $this->mNamespace, $this->getRootText() );
1767 }
1768
1769 /**
1770 * Get the base page name without a namespace, i.e. the part before the subpage name
1771 *
1772 * @par Example:
1773 * @code
1774 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1775 * # returns: 'Foo/Bar'
1776 * @endcode
1777 *
1778 * @return string Base name
1779 */
1780 public function getBaseText() {
1781 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1782 return $this->getText();
1783 }
1784
1785 $parts = explode( '/', $this->getText() );
1786 # Don't discard the real title if there's no subpage involved
1787 if ( count( $parts ) > 1 ) {
1788 unset( $parts[count( $parts ) - 1] );
1789 }
1790 return implode( '/', $parts );
1791 }
1792
1793 /**
1794 * Get the base page name title, i.e. the part before the subpage name
1795 *
1796 * @par Example:
1797 * @code
1798 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1799 * # returns: Title{User:Foo/Bar}
1800 * @endcode
1801 *
1802 * @return Title Base title
1803 * @since 1.20
1804 */
1805 public function getBaseTitle() {
1806 return self::makeTitle( $this->mNamespace, $this->getBaseText() );
1807 }
1808
1809 /**
1810 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1811 *
1812 * @par Example:
1813 * @code
1814 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1815 * # returns: "Baz"
1816 * @endcode
1817 *
1818 * @return string Subpage name
1819 */
1820 public function getSubpageText() {
1821 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1822 return $this->mTextform;
1823 }
1824 $parts = explode( '/', $this->mTextform );
1825 return $parts[count( $parts ) - 1];
1826 }
1827
1828 /**
1829 * Get the title for a subpage of the current page
1830 *
1831 * @par Example:
1832 * @code
1833 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1834 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1835 * @endcode
1836 *
1837 * @param string $text The subpage name to add to the title
1838 * @return Title|null Subpage title, or null on an error
1839 * @since 1.20
1840 */
1841 public function getSubpage( $text ) {
1842 return self::makeTitleSafe( $this->mNamespace, $this->getText() . '/' . $text );
1843 }
1844
1845 /**
1846 * Get a URL-encoded form of the subpage text
1847 *
1848 * @return string URL-encoded subpage name
1849 */
1850 public function getSubpageUrlForm() {
1851 $text = $this->getSubpageText();
1852 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1853 return $text;
1854 }
1855
1856 /**
1857 * Get a URL-encoded title (not an actual URL) including interwiki
1858 *
1859 * @return string The URL-encoded form
1860 */
1861 public function getPrefixedURL() {
1862 $s = $this->prefix( $this->mDbkeyform );
1863 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1864 return $s;
1865 }
1866
1867 /**
1868 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1869 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1870 * second argument named variant. This was deprecated in favor
1871 * of passing an array of option with a "variant" key
1872 * Once $query2 is removed for good, this helper can be dropped
1873 * and the wfArrayToCgi moved to getLocalURL();
1874 *
1875 * @since 1.19 (r105919)
1876 * @param array|string $query
1877 * @param string|string[]|bool $query2
1878 * @return string
1879 */
1880 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1881 if ( $query2 !== false ) {
1882 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1883 "method called with a second parameter is deprecated. Add your " .
1884 "parameter to an array passed as the first parameter.", "1.19" );
1885 }
1886 if ( is_array( $query ) ) {
1887 $query = wfArrayToCgi( $query );
1888 }
1889 if ( $query2 ) {
1890 if ( is_string( $query2 ) ) {
1891 // $query2 is a string, we will consider this to be
1892 // a deprecated $variant argument and add it to the query
1893 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1894 } else {
1895 $query2 = wfArrayToCgi( $query2 );
1896 }
1897 // If we have $query content add a & to it first
1898 if ( $query ) {
1899 $query .= '&';
1900 }
1901 // Now append the queries together
1902 $query .= $query2;
1903 }
1904 return $query;
1905 }
1906
1907 /**
1908 * Get a real URL referring to this title, with interwiki link and
1909 * fragment
1910 *
1911 * @see self::getLocalURL for the arguments.
1912 * @see wfExpandUrl
1913 * @param string|string[] $query
1914 * @param string|string[]|bool $query2
1915 * @param string|int|null $proto Protocol type to use in URL
1916 * @return string The URL
1917 */
1918 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1919 $query = self::fixUrlQueryArgs( $query, $query2 );
1920
1921 # Hand off all the decisions on urls to getLocalURL
1922 $url = $this->getLocalURL( $query );
1923
1924 # Expand the url to make it a full url. Note that getLocalURL has the
1925 # potential to output full urls for a variety of reasons, so we use
1926 # wfExpandUrl instead of simply prepending $wgServer
1927 $url = wfExpandUrl( $url, $proto );
1928
1929 # Finally, add the fragment.
1930 $url .= $this->getFragmentForURL();
1931 // Avoid PHP 7.1 warning from passing $this by reference
1932 $titleRef = $this;
1933 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1934 return $url;
1935 }
1936
1937 /**
1938 * Get a url appropriate for making redirects based on an untrusted url arg
1939 *
1940 * This is basically the same as getFullUrl(), but in the case of external
1941 * interwikis, we send the user to a landing page, to prevent possible
1942 * phishing attacks and the like.
1943 *
1944 * @note Uses current protocol by default, since technically relative urls
1945 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1946 * places where the url gets cached, as might pollute between
1947 * https and non-https users.
1948 * @see self::getLocalURL for the arguments.
1949 * @param array|string $query
1950 * @param string $proto Protocol type to use in URL
1951 * @return string A url suitable to use in an HTTP location header.
1952 */
1953 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
1954 $target = $this;
1955 if ( $this->isExternal() ) {
1956 $target = SpecialPage::getTitleFor(
1957 'GoToInterwiki',
1958 $this->getPrefixedDBkey()
1959 );
1960 }
1961 return $target->getFullURL( $query, false, $proto );
1962 }
1963
1964 /**
1965 * Get a URL with no fragment or server name (relative URL) from a Title object.
1966 * If this page is generated with action=render, however,
1967 * $wgServer is prepended to make an absolute URL.
1968 *
1969 * @see self::getFullURL to always get an absolute URL.
1970 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1971 * valid to link, locally, to the current Title.
1972 * @see self::newFromText to produce a Title object.
1973 *
1974 * @param string|string[] $query An optional query string,
1975 * not used for interwiki links. Can be specified as an associative array as well,
1976 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1977 * Some query patterns will trigger various shorturl path replacements.
1978 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1979 * be an array. If a string is passed it will be interpreted as a deprecated
1980 * variant argument and urlencoded into a variant= argument.
1981 * This second query argument will be added to the $query
1982 * The second parameter is deprecated since 1.19. Pass it as a key,value
1983 * pair in the first parameter array instead.
1984 *
1985 * @return string String of the URL.
1986 */
1987 public function getLocalURL( $query = '', $query2 = false ) {
1988 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1989
1990 $query = self::fixUrlQueryArgs( $query, $query2 );
1991
1992 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1993 if ( $interwiki ) {
1994 $namespace = $this->getNsText();
1995 if ( $namespace != '' ) {
1996 # Can this actually happen? Interwikis shouldn't be parsed.
1997 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1998 $namespace .= ':';
1999 }
2000 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2001 $url = wfAppendQuery( $url, $query );
2002 } else {
2003 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2004 if ( $query == '' ) {
2005 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2006 // Avoid PHP 7.1 warning from passing $this by reference
2007 $titleRef = $this;
2008 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2009 } else {
2010 global $wgVariantArticlePath, $wgActionPaths;
2011 $url = false;
2012 $matches = [];
2013
2014 if ( !empty( $wgActionPaths )
2015 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2016 ) {
2017 $action = urldecode( $matches[2] );
2018 if ( isset( $wgActionPaths[$action] ) ) {
2019 $query = $matches[1];
2020 if ( isset( $matches[4] ) ) {
2021 $query .= $matches[4];
2022 }
2023 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2024 if ( $query != '' ) {
2025 $url = wfAppendQuery( $url, $query );
2026 }
2027 }
2028 }
2029
2030 if ( $url === false
2031 && $wgVariantArticlePath
2032 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2033 && $this->getPageLanguage()->equals(
2034 MediaWikiServices::getInstance()->getContentLanguage() )
2035 && $this->getPageLanguage()->hasVariants()
2036 ) {
2037 $variant = urldecode( $matches[1] );
2038 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2039 // Only do the variant replacement if the given variant is a valid
2040 // variant for the page's language.
2041 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2042 $url = str_replace( '$1', $dbkey, $url );
2043 }
2044 }
2045
2046 if ( $url === false ) {
2047 if ( $query == '-' ) {
2048 $query = '';
2049 }
2050 $url = "{$wgScript}?title={$dbkey}&{$query}";
2051 }
2052 }
2053 // Avoid PHP 7.1 warning from passing $this by reference
2054 $titleRef = $this;
2055 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2056
2057 // @todo FIXME: This causes breakage in various places when we
2058 // actually expected a local URL and end up with dupe prefixes.
2059 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2060 $url = $wgServer . $url;
2061 }
2062 }
2063 // Avoid PHP 7.1 warning from passing $this by reference
2064 $titleRef = $this;
2065 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2066 return $url;
2067 }
2068
2069 /**
2070 * Get a URL that's the simplest URL that will be valid to link, locally,
2071 * to the current Title. It includes the fragment, but does not include
2072 * the server unless action=render is used (or the link is external). If
2073 * there's a fragment but the prefixed text is empty, we just return a link
2074 * to the fragment.
2075 *
2076 * The result obviously should not be URL-escaped, but does need to be
2077 * HTML-escaped if it's being output in HTML.
2078 *
2079 * @param string|string[] $query
2080 * @param bool $query2
2081 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2082 * or false (default) for no expansion
2083 * @see self::getLocalURL for the arguments.
2084 * @return string The URL
2085 */
2086 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2087 if ( $this->isExternal() || $proto !== false ) {
2088 $ret = $this->getFullURL( $query, $query2, $proto );
2089 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2090 $ret = $this->getFragmentForURL();
2091 } else {
2092 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2093 }
2094 return $ret;
2095 }
2096
2097 /**
2098 * Get the URL form for an internal link.
2099 * - Used in various CDN-related code, in case we have a different
2100 * internal hostname for the server from the exposed one.
2101 *
2102 * This uses $wgInternalServer to qualify the path, or $wgServer
2103 * if $wgInternalServer is not set. If the server variable used is
2104 * protocol-relative, the URL will be expanded to http://
2105 *
2106 * @see self::getLocalURL for the arguments.
2107 * @param string $query
2108 * @param string|bool $query2
2109 * @return string The URL
2110 */
2111 public function getInternalURL( $query = '', $query2 = false ) {
2112 global $wgInternalServer, $wgServer;
2113 $query = self::fixUrlQueryArgs( $query, $query2 );
2114 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2115 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2116 // Avoid PHP 7.1 warning from passing $this by reference
2117 $titleRef = $this;
2118 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2119 return $url;
2120 }
2121
2122 /**
2123 * Get the URL for a canonical link, for use in things like IRC and
2124 * e-mail notifications. Uses $wgCanonicalServer and the
2125 * GetCanonicalURL hook.
2126 *
2127 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2128 *
2129 * @see self::getLocalURL for the arguments.
2130 * @param string $query
2131 * @param string|bool $query2
2132 * @return string The URL
2133 * @since 1.18
2134 */
2135 public function getCanonicalURL( $query = '', $query2 = false ) {
2136 $query = self::fixUrlQueryArgs( $query, $query2 );
2137 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2138 // Avoid PHP 7.1 warning from passing $this by reference
2139 $titleRef = $this;
2140 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2141 return $url;
2142 }
2143
2144 /**
2145 * Get the edit URL for this Title
2146 *
2147 * @return string The URL, or a null string if this is an interwiki link
2148 */
2149 public function getEditURL() {
2150 if ( $this->isExternal() ) {
2151 return '';
2152 }
2153 $s = $this->getLocalURL( 'action=edit' );
2154
2155 return $s;
2156 }
2157
2158 /**
2159 * Can $user perform $action on this page?
2160 * This skips potentially expensive cascading permission checks
2161 * as well as avoids expensive error formatting
2162 *
2163 * Suitable for use for nonessential UI controls in common cases, but
2164 * _not_ for functional access control.
2165 *
2166 * May provide false positives, but should never provide a false negative.
2167 *
2168 * @param string $action Action that permission needs to be checked for
2169 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2170 * @return bool
2171 */
2172 public function quickUserCan( $action, $user = null ) {
2173 return $this->userCan( $action, $user, false );
2174 }
2175
2176 /**
2177 * Can $user perform $action on this page?
2178 *
2179 * @param string $action Action that permission needs to be checked for
2180 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2181 * provided.
2182 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2183 * @return bool
2184 */
2185 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2186 if ( !$user instanceof User ) {
2187 global $wgUser;
2188 $user = $wgUser;
2189 }
2190
2191 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2192 }
2193
2194 /**
2195 * Can $user perform $action on this page?
2196 *
2197 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2198 *
2199 * @param string $action Action that permission needs to be checked for
2200 * @param User $user User to check
2201 * @param string $rigor One of (quick,full,secure)
2202 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2203 * - full : does cheap and expensive checks possibly from a replica DB
2204 * - secure : does cheap and expensive checks, using the master as needed
2205 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2206 * whose corresponding errors may be ignored.
2207 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2208 */
2209 public function getUserPermissionsErrors(
2210 $action, $user, $rigor = 'secure', $ignoreErrors = []
2211 ) {
2212 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2213
2214 // Remove the errors being ignored.
2215 foreach ( $errors as $index => $error ) {
2216 $errKey = is_array( $error ) ? $error[0] : $error;
2217
2218 if ( in_array( $errKey, $ignoreErrors ) ) {
2219 unset( $errors[$index] );
2220 }
2221 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
2222 unset( $errors[$index] );
2223 }
2224 }
2225
2226 return $errors;
2227 }
2228
2229 /**
2230 * Permissions checks that fail most often, and which are easiest to test.
2231 *
2232 * @param string $action The action to check
2233 * @param User $user User to check
2234 * @param array $errors List of current errors
2235 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2236 * @param bool $short Short circuit on first error
2237 *
2238 * @return array List of errors
2239 */
2240 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2241 if ( !Hooks::run( 'TitleQuickPermissions',
2242 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2243 ) {
2244 return $errors;
2245 }
2246
2247 if ( $action == 'create' ) {
2248 if (
2249 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2250 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2251 ) {
2252 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2253 }
2254 } elseif ( $action == 'move' ) {
2255 if ( !$user->isAllowed( 'move-rootuserpages' )
2256 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2257 // Show user page-specific message only if the user can move other pages
2258 $errors[] = [ 'cant-move-user-page' ];
2259 }
2260
2261 // Check if user is allowed to move files if it's a file
2262 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2263 $errors[] = [ 'movenotallowedfile' ];
2264 }
2265
2266 // Check if user is allowed to move category pages if it's a category page
2267 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2268 $errors[] = [ 'cant-move-category-page' ];
2269 }
2270
2271 if ( !$user->isAllowed( 'move' ) ) {
2272 // User can't move anything
2273 $userCanMove = User::groupHasPermission( 'user', 'move' );
2274 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2275 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2276 // custom message if logged-in users without any special rights can move
2277 $errors[] = [ 'movenologintext' ];
2278 } else {
2279 $errors[] = [ 'movenotallowed' ];
2280 }
2281 }
2282 } elseif ( $action == 'move-target' ) {
2283 if ( !$user->isAllowed( 'move' ) ) {
2284 // User can't move anything
2285 $errors[] = [ 'movenotallowed' ];
2286 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2287 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2288 // Show user page-specific message only if the user can move other pages
2289 $errors[] = [ 'cant-move-to-user-page' ];
2290 } elseif ( !$user->isAllowed( 'move-categorypages' )
2291 && $this->mNamespace == NS_CATEGORY ) {
2292 // Show category page-specific message only if the user can move other pages
2293 $errors[] = [ 'cant-move-to-category-page' ];
2294 }
2295 } elseif ( !$user->isAllowed( $action ) ) {
2296 $errors[] = $this->missingPermissionError( $action, $short );
2297 }
2298
2299 return $errors;
2300 }
2301
2302 /**
2303 * Add the resulting error code to the errors array
2304 *
2305 * @param array $errors List of current errors
2306 * @param array $result Result of errors
2307 *
2308 * @return array List of errors
2309 */
2310 private function resultToError( $errors, $result ) {
2311 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2312 // A single array representing an error
2313 $errors[] = $result;
2314 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2315 // A nested array representing multiple errors
2316 $errors = array_merge( $errors, $result );
2317 } elseif ( $result !== '' && is_string( $result ) ) {
2318 // A string representing a message-id
2319 $errors[] = [ $result ];
2320 } elseif ( $result instanceof MessageSpecifier ) {
2321 // A message specifier representing an error
2322 $errors[] = [ $result ];
2323 } elseif ( $result === false ) {
2324 // a generic "We don't want them to do that"
2325 $errors[] = [ 'badaccess-group0' ];
2326 }
2327 return $errors;
2328 }
2329
2330 /**
2331 * Check various permission hooks
2332 *
2333 * @param string $action The action to check
2334 * @param User $user User to check
2335 * @param array $errors List of current errors
2336 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2337 * @param bool $short Short circuit on first error
2338 *
2339 * @return array List of errors
2340 */
2341 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2342 // Use getUserPermissionsErrors instead
2343 $result = '';
2344 // Avoid PHP 7.1 warning from passing $this by reference
2345 $titleRef = $this;
2346 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2347 return $result ? [] : [ [ 'badaccess-group0' ] ];
2348 }
2349 // Check getUserPermissionsErrors hook
2350 // Avoid PHP 7.1 warning from passing $this by reference
2351 $titleRef = $this;
2352 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2353 $errors = $this->resultToError( $errors, $result );
2354 }
2355 // Check getUserPermissionsErrorsExpensive hook
2356 if (
2357 $rigor !== 'quick'
2358 && !( $short && count( $errors ) > 0 )
2359 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2360 ) {
2361 $errors = $this->resultToError( $errors, $result );
2362 }
2363
2364 return $errors;
2365 }
2366
2367 /**
2368 * Check permissions on special pages & namespaces
2369 *
2370 * @param string $action The action to check
2371 * @param User $user User to check
2372 * @param array $errors List of current errors
2373 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2374 * @param bool $short Short circuit on first error
2375 *
2376 * @return array List of errors
2377 */
2378 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2379 # Only 'createaccount' can be performed on special pages,
2380 # which don't actually exist in the DB.
2381 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2382 $errors[] = [ 'ns-specialprotected' ];
2383 }
2384
2385 # Check $wgNamespaceProtection for restricted namespaces
2386 if ( $this->isNamespaceProtected( $user ) ) {
2387 $ns = $this->mNamespace == NS_MAIN ?
2388 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2389 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2390 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2391 }
2392
2393 return $errors;
2394 }
2395
2396 /**
2397 * Check sitewide CSS/JSON/JS permissions
2398 *
2399 * @param string $action The action to check
2400 * @param User $user User to check
2401 * @param array $errors List of current errors
2402 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2403 * @param bool $short Short circuit on first error
2404 *
2405 * @return array List of errors
2406 */
2407 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2408 if ( $action != 'patrol' ) {
2409 $error = null;
2410 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2411 // editinterface right. That's implemented as a restriction so no check needed here.
2412 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2413 $error = [ 'sitecssprotected', $action ];
2414 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2415 $error = [ 'sitejsonprotected', $action ];
2416 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2417 $error = [ 'sitejsprotected', $action ];
2418 } elseif ( $this->isRawHtmlMessage() ) {
2419 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2420 if ( !$user->isAllowed( 'editsitejs' ) ) {
2421 $error = [ 'sitejsprotected', $action ];
2422 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2423 $error = [ 'sitecssprotected', $action ];
2424 }
2425 }
2426
2427 if ( $error ) {
2428 if ( $user->isAllowed( 'editinterface' ) ) {
2429 // Most users / site admins will probably find out about the new, more restrictive
2430 // permissions by failing to edit something. Give them more info.
2431 // TODO remove this a few release cycles after 1.32
2432 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2433 }
2434 $errors[] = $error;
2435 }
2436 }
2437
2438 return $errors;
2439 }
2440
2441 /**
2442 * Check CSS/JSON/JS sub-page permissions
2443 *
2444 * @param string $action The action to check
2445 * @param User $user User to check
2446 * @param array $errors List of current errors
2447 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2448 * @param bool $short Short circuit on first error
2449 *
2450 * @return array List of errors
2451 */
2452 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2453 # Protect css/json/js subpages of user pages
2454 # XXX: this might be better using restrictions
2455
2456 if ( $action === 'patrol' ) {
2457 return $errors;
2458 }
2459
2460 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2461 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2462 if (
2463 $this->isUserCssConfigPage()
2464 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2465 ) {
2466 $errors[] = [ 'mycustomcssprotected', $action ];
2467 } elseif (
2468 $this->isUserJsonConfigPage()
2469 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2470 ) {
2471 $errors[] = [ 'mycustomjsonprotected', $action ];
2472 } elseif (
2473 $this->isUserJsConfigPage()
2474 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2475 ) {
2476 $errors[] = [ 'mycustomjsprotected', $action ];
2477 }
2478 } else {
2479 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2480 // deletion/suppression which cannot be used for attacks and we want to avoid the
2481 // situation where an unprivileged user can post abusive content on their subpages
2482 // and only very highly privileged users could remove it.
2483 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2484 if (
2485 $this->isUserCssConfigPage()
2486 && !$user->isAllowed( 'editusercss' )
2487 ) {
2488 $errors[] = [ 'customcssprotected', $action ];
2489 } elseif (
2490 $this->isUserJsonConfigPage()
2491 && !$user->isAllowed( 'edituserjson' )
2492 ) {
2493 $errors[] = [ 'customjsonprotected', $action ];
2494 } elseif (
2495 $this->isUserJsConfigPage()
2496 && !$user->isAllowed( 'edituserjs' )
2497 ) {
2498 $errors[] = [ 'customjsprotected', $action ];
2499 }
2500 }
2501 }
2502
2503 return $errors;
2504 }
2505
2506 /**
2507 * Check against page_restrictions table requirements on this
2508 * page. The user must possess all required rights for this
2509 * action.
2510 *
2511 * @param string $action The action to check
2512 * @param User $user User to check
2513 * @param array $errors List of current errors
2514 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2515 * @param bool $short Short circuit on first error
2516 *
2517 * @return array List of errors
2518 */
2519 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2520 foreach ( $this->getRestrictions( $action ) as $right ) {
2521 // Backwards compatibility, rewrite sysop -> editprotected
2522 if ( $right == 'sysop' ) {
2523 $right = 'editprotected';
2524 }
2525 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2526 if ( $right == 'autoconfirmed' ) {
2527 $right = 'editsemiprotected';
2528 }
2529 if ( $right == '' ) {
2530 continue;
2531 }
2532 if ( !$user->isAllowed( $right ) ) {
2533 $errors[] = [ 'protectedpagetext', $right, $action ];
2534 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2535 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2536 }
2537 }
2538
2539 return $errors;
2540 }
2541
2542 /**
2543 * Check restrictions on cascading pages.
2544 *
2545 * @param string $action The action to check
2546 * @param User $user User to check
2547 * @param array $errors List of current errors
2548 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2549 * @param bool $short Short circuit on first error
2550 *
2551 * @return array List of errors
2552 */
2553 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2554 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2555 # We /could/ use the protection level on the source page, but it's
2556 # fairly ugly as we have to establish a precedence hierarchy for pages
2557 # included by multiple cascade-protected pages. So just restrict
2558 # it to people with 'protect' permission, as they could remove the
2559 # protection anyway.
2560 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2561 # Cascading protection depends on more than this page...
2562 # Several cascading protected pages may include this page...
2563 # Check each cascading level
2564 # This is only for protection restrictions, not for all actions
2565 if ( isset( $restrictions[$action] ) ) {
2566 foreach ( $restrictions[$action] as $right ) {
2567 // Backwards compatibility, rewrite sysop -> editprotected
2568 if ( $right == 'sysop' ) {
2569 $right = 'editprotected';
2570 }
2571 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2572 if ( $right == 'autoconfirmed' ) {
2573 $right = 'editsemiprotected';
2574 }
2575 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2576 $pages = '';
2577 foreach ( $cascadingSources as $page ) {
2578 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2579 }
2580 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2581 }
2582 }
2583 }
2584 }
2585
2586 return $errors;
2587 }
2588
2589 /**
2590 * Check action permissions not already checked in checkQuickPermissions
2591 *
2592 * @param string $action The action to check
2593 * @param User $user User to check
2594 * @param array $errors List of current errors
2595 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2596 * @param bool $short Short circuit on first error
2597 *
2598 * @return array List of errors
2599 */
2600 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2601 global $wgDeleteRevisionsLimit, $wgLang;
2602
2603 if ( $action == 'protect' ) {
2604 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2605 // If they can't edit, they shouldn't protect.
2606 $errors[] = [ 'protect-cantedit' ];
2607 }
2608 } elseif ( $action == 'create' ) {
2609 $title_protection = $this->getTitleProtection();
2610 if ( $title_protection ) {
2611 if ( $title_protection['permission'] == ''
2612 || !$user->isAllowed( $title_protection['permission'] )
2613 ) {
2614 $errors[] = [
2615 'titleprotected',
2616 User::whoIs( $title_protection['user'] ),
2617 $title_protection['reason']
2618 ];
2619 }
2620 }
2621 } elseif ( $action == 'move' ) {
2622 // Check for immobile pages
2623 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2624 // Specific message for this case
2625 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2626 } elseif ( !$this->isMovable() ) {
2627 // Less specific message for rarer cases
2628 $errors[] = [ 'immobile-source-page' ];
2629 }
2630 } elseif ( $action == 'move-target' ) {
2631 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2632 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2633 } elseif ( !$this->isMovable() ) {
2634 $errors[] = [ 'immobile-target-page' ];
2635 }
2636 } elseif ( $action == 'delete' ) {
2637 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2638 if ( !$tempErrors ) {
2639 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2640 $user, $tempErrors, $rigor, true );
2641 }
2642 if ( $tempErrors ) {
2643 // If protection keeps them from editing, they shouldn't be able to delete.
2644 $errors[] = [ 'deleteprotected' ];
2645 }
2646 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2647 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2648 ) {
2649 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2650 }
2651 } elseif ( $action === 'undelete' ) {
2652 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2653 // Undeleting implies editing
2654 $errors[] = [ 'undelete-cantedit' ];
2655 }
2656 if ( !$this->exists()
2657 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2658 ) {
2659 // Undeleting where nothing currently exists implies creating
2660 $errors[] = [ 'undelete-cantcreate' ];
2661 }
2662 }
2663 return $errors;
2664 }
2665
2666 /**
2667 * Check that the user isn't blocked from editing.
2668 *
2669 * @param string $action The action to check
2670 * @param User $user User to check
2671 * @param array $errors List of current errors
2672 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2673 * @param bool $short Short circuit on first error
2674 *
2675 * @return array List of errors
2676 */
2677 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2678 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2679 // Account creation blocks handled at userlogin.
2680 // Unblocking handled in SpecialUnblock
2681 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2682 return $errors;
2683 }
2684
2685 // Optimize for a very common case
2686 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2687 return $errors;
2688 }
2689
2690 if ( $wgEmailConfirmToEdit
2691 && !$user->isEmailConfirmed()
2692 && $action === 'edit'
2693 ) {
2694 $errors[] = [ 'confirmedittext' ];
2695 }
2696
2697 $useReplica = ( $rigor !== 'secure' );
2698 $block = $user->getBlock( $useReplica );
2699
2700 // The block may explicitly allow an action (like "read" or "upload").
2701 if ( $block && $block->prevents( $action ) === false ) {
2702 return $errors;
2703 }
2704
2705 // Determine if the user is blocked from this action on this page.
2706 // What gets passed into this method is a user right, not an action name.
2707 // There is no way to instantiate an action by restriction. However, this
2708 // will get the action where the restriction is the same. This may result
2709 // in actions being blocked that shouldn't be.
2710 $actionObj = null;
2711 if ( Action::exists( $action ) ) {
2712 // Clone the title to prevent mutations to this object which is done
2713 // by Title::loadFromRow() in WikiPage::loadFromRow().
2714 $page = WikiPage::factory( clone $this );
2715 // Creating an action will perform several database queries to ensure that
2716 // the action has not been overridden by the content type.
2717 // @todo FIXME: Pass the relevant context into this function.
2718 $actionObj = Action::factory( $action, $page, RequestContext::getMain() );
2719 // Ensure that the retrieved action matches the restriction.
2720 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
2721 $actionObj = null;
2722 }
2723 }
2724
2725 // If no action object is returned, assume that the action requires unblock
2726 // which is the default.
2727 if ( !$actionObj || $actionObj->requiresUnblock() ) {
2728 if ( $user->isBlockedFrom( $this, $useReplica ) ) {
2729 // @todo FIXME: Pass the relevant context into this function.
2730 $errors[] = $block
2731 ? $block->getPermissionsError( RequestContext::getMain() )
2732 : [ 'actionblockedtext' ];
2733 }
2734 }
2735
2736 return $errors;
2737 }
2738
2739 /**
2740 * Check that the user is allowed to read this page.
2741 *
2742 * @param string $action The action to check
2743 * @param User $user User to check
2744 * @param array $errors List of current errors
2745 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2746 * @param bool $short Short circuit on first error
2747 *
2748 * @return array List of errors
2749 */
2750 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2751 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2752
2753 $whitelisted = false;
2754 if ( User::isEveryoneAllowed( 'read' ) ) {
2755 # Shortcut for public wikis, allows skipping quite a bit of code
2756 $whitelisted = true;
2757 } elseif ( $user->isAllowed( 'read' ) ) {
2758 # If the user is allowed to read pages, he is allowed to read all pages
2759 $whitelisted = true;
2760 } elseif ( $this->isSpecial( 'Userlogin' )
2761 || $this->isSpecial( 'PasswordReset' )
2762 || $this->isSpecial( 'Userlogout' )
2763 ) {
2764 # Always grant access to the login page.
2765 # Even anons need to be able to log in.
2766 $whitelisted = true;
2767 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2768 # Time to check the whitelist
2769 # Only do these checks is there's something to check against
2770 $name = $this->getPrefixedText();
2771 $dbName = $this->getPrefixedDBkey();
2772
2773 // Check for explicit whitelisting with and without underscores
2774 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2775 $whitelisted = true;
2776 } elseif ( $this->mNamespace == NS_MAIN ) {
2777 # Old settings might have the title prefixed with
2778 # a colon for main-namespace pages
2779 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2780 $whitelisted = true;
2781 }
2782 } elseif ( $this->isSpecialPage() ) {
2783 # If it's a special page, ditch the subpage bit and check again
2784 $name = $this->mDbkeyform;
2785 list( $name, /* $subpage */ ) =
2786 MediaWikiServices::getInstance()->getSpecialPageFactory()->
2787 resolveAlias( $name );
2788 if ( $name ) {
2789 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2790 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2791 $whitelisted = true;
2792 }
2793 }
2794 }
2795 }
2796
2797 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2798 $name = $this->getPrefixedText();
2799 // Check for regex whitelisting
2800 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2801 if ( preg_match( $listItem, $name ) ) {
2802 $whitelisted = true;
2803 break;
2804 }
2805 }
2806 }
2807
2808 if ( !$whitelisted ) {
2809 # If the title is not whitelisted, give extensions a chance to do so...
2810 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2811 if ( !$whitelisted ) {
2812 $errors[] = $this->missingPermissionError( $action, $short );
2813 }
2814 }
2815
2816 return $errors;
2817 }
2818
2819 /**
2820 * Get a description array when the user doesn't have the right to perform
2821 * $action (i.e. when User::isAllowed() returns false)
2822 *
2823 * @param string $action The action to check
2824 * @param bool $short Short circuit on first error
2825 * @return array Array containing an error message key and any parameters
2826 */
2827 private function missingPermissionError( $action, $short ) {
2828 // We avoid expensive display logic for quickUserCan's and such
2829 if ( $short ) {
2830 return [ 'badaccess-group0' ];
2831 }
2832
2833 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2834 }
2835
2836 /**
2837 * Can $user perform $action on this page? This is an internal function,
2838 * with multiple levels of checks depending on performance needs; see $rigor below.
2839 * It does not check wfReadOnly().
2840 *
2841 * @param string $action Action that permission needs to be checked for
2842 * @param User $user User to check
2843 * @param string $rigor One of (quick,full,secure)
2844 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2845 * - full : does cheap and expensive checks possibly from a replica DB
2846 * - secure : does cheap and expensive checks, using the master as needed
2847 * @param bool $short Set this to true to stop after the first permission error.
2848 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2849 */
2850 protected function getUserPermissionsErrorsInternal(
2851 $action, $user, $rigor = 'secure', $short = false
2852 ) {
2853 if ( $rigor === true ) {
2854 $rigor = 'secure'; // b/c
2855 } elseif ( $rigor === false ) {
2856 $rigor = 'quick'; // b/c
2857 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2858 throw new Exception( "Invalid rigor parameter '$rigor'." );
2859 }
2860
2861 # Read has special handling
2862 if ( $action == 'read' ) {
2863 $checks = [
2864 'checkPermissionHooks',
2865 'checkReadPermissions',
2866 'checkUserBlock', // for wgBlockDisablesLogin
2867 ];
2868 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2869 # or checkUserConfigPermissions here as it will lead to duplicate
2870 # error messages. This is okay to do since anywhere that checks for
2871 # create will also check for edit, and those checks are called for edit.
2872 } elseif ( $action == 'create' ) {
2873 $checks = [
2874 'checkQuickPermissions',
2875 'checkPermissionHooks',
2876 'checkPageRestrictions',
2877 'checkCascadingSourcesRestrictions',
2878 'checkActionPermissions',
2879 'checkUserBlock'
2880 ];
2881 } else {
2882 $checks = [
2883 'checkQuickPermissions',
2884 'checkPermissionHooks',
2885 'checkSpecialsAndNSPermissions',
2886 'checkSiteConfigPermissions',
2887 'checkUserConfigPermissions',
2888 'checkPageRestrictions',
2889 'checkCascadingSourcesRestrictions',
2890 'checkActionPermissions',
2891 'checkUserBlock'
2892 ];
2893 }
2894
2895 $errors = [];
2896 foreach ( $checks as $method ) {
2897 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2898
2899 if ( $short && $errors !== [] ) {
2900 break;
2901 }
2902 }
2903
2904 return $errors;
2905 }
2906
2907 /**
2908 * Get a filtered list of all restriction types supported by this wiki.
2909 * @param bool $exists True to get all restriction types that apply to
2910 * titles that do exist, False for all restriction types that apply to
2911 * titles that do not exist
2912 * @return array
2913 */
2914 public static function getFilteredRestrictionTypes( $exists = true ) {
2915 global $wgRestrictionTypes;
2916 $types = $wgRestrictionTypes;
2917 if ( $exists ) {
2918 # Remove the create restriction for existing titles
2919 $types = array_diff( $types, [ 'create' ] );
2920 } else {
2921 # Only the create and upload restrictions apply to non-existing titles
2922 $types = array_intersect( $types, [ 'create', 'upload' ] );
2923 }
2924 return $types;
2925 }
2926
2927 /**
2928 * Returns restriction types for the current Title
2929 *
2930 * @return array Applicable restriction types
2931 */
2932 public function getRestrictionTypes() {
2933 if ( $this->isSpecialPage() ) {
2934 return [];
2935 }
2936
2937 $types = self::getFilteredRestrictionTypes( $this->exists() );
2938
2939 if ( $this->mNamespace != NS_FILE ) {
2940 # Remove the upload restriction for non-file titles
2941 $types = array_diff( $types, [ 'upload' ] );
2942 }
2943
2944 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2945
2946 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2947 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2948
2949 return $types;
2950 }
2951
2952 /**
2953 * Is this title subject to title protection?
2954 * Title protection is the one applied against creation of such title.
2955 *
2956 * @return array|bool An associative array representing any existent title
2957 * protection, or false if there's none.
2958 */
2959 public function getTitleProtection() {
2960 $protection = $this->getTitleProtectionInternal();
2961 if ( $protection ) {
2962 if ( $protection['permission'] == 'sysop' ) {
2963 $protection['permission'] = 'editprotected'; // B/C
2964 }
2965 if ( $protection['permission'] == 'autoconfirmed' ) {
2966 $protection['permission'] = 'editsemiprotected'; // B/C
2967 }
2968 }
2969 return $protection;
2970 }
2971
2972 /**
2973 * Fetch title protection settings
2974 *
2975 * To work correctly, $this->loadRestrictions() needs to have access to the
2976 * actual protections in the database without munging 'sysop' =>
2977 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2978 * callers probably want $this->getTitleProtection() instead.
2979 *
2980 * @return array|bool
2981 */
2982 protected function getTitleProtectionInternal() {
2983 // Can't protect pages in special namespaces
2984 if ( $this->mNamespace < 0 ) {
2985 return false;
2986 }
2987
2988 // Can't protect pages that exist.
2989 if ( $this->exists() ) {
2990 return false;
2991 }
2992
2993 if ( $this->mTitleProtection === null ) {
2994 $dbr = wfGetDB( DB_REPLICA );
2995 $commentStore = CommentStore::getStore();
2996 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2997 $res = $dbr->select(
2998 [ 'protected_titles' ] + $commentQuery['tables'],
2999 [
3000 'user' => 'pt_user',
3001 'expiry' => 'pt_expiry',
3002 'permission' => 'pt_create_perm'
3003 ] + $commentQuery['fields'],
3004 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
3005 __METHOD__,
3006 [],
3007 $commentQuery['joins']
3008 );
3009
3010 // fetchRow returns false if there are no rows.
3011 $row = $dbr->fetchRow( $res );
3012 if ( $row ) {
3013 $this->mTitleProtection = [
3014 'user' => $row['user'],
3015 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
3016 'permission' => $row['permission'],
3017 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
3018 ];
3019 } else {
3020 $this->mTitleProtection = false;
3021 }
3022 }
3023 return $this->mTitleProtection;
3024 }
3025
3026 /**
3027 * Remove any title protection due to page existing
3028 */
3029 public function deleteTitleProtection() {
3030 $dbw = wfGetDB( DB_MASTER );
3031
3032 $dbw->delete(
3033 'protected_titles',
3034 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
3035 __METHOD__
3036 );
3037 $this->mTitleProtection = false;
3038 }
3039
3040 /**
3041 * Is this page "semi-protected" - the *only* protection levels are listed
3042 * in $wgSemiprotectedRestrictionLevels?
3043 *
3044 * @param string $action Action to check (default: edit)
3045 * @return bool
3046 */
3047 public function isSemiProtected( $action = 'edit' ) {
3048 global $wgSemiprotectedRestrictionLevels;
3049
3050 $restrictions = $this->getRestrictions( $action );
3051 $semi = $wgSemiprotectedRestrictionLevels;
3052 if ( !$restrictions || !$semi ) {
3053 // Not protected, or all protection is full protection
3054 return false;
3055 }
3056
3057 // Remap autoconfirmed to editsemiprotected for BC
3058 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3059 $semi[$key] = 'editsemiprotected';
3060 }
3061 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3062 $restrictions[$key] = 'editsemiprotected';
3063 }
3064
3065 return !array_diff( $restrictions, $semi );
3066 }
3067
3068 /**
3069 * Does the title correspond to a protected article?
3070 *
3071 * @param string $action The action the page is protected from,
3072 * by default checks all actions.
3073 * @return bool
3074 */
3075 public function isProtected( $action = '' ) {
3076 global $wgRestrictionLevels;
3077
3078 $restrictionTypes = $this->getRestrictionTypes();
3079
3080 # Special pages have inherent protection
3081 if ( $this->isSpecialPage() ) {
3082 return true;
3083 }
3084
3085 # Check regular protection levels
3086 foreach ( $restrictionTypes as $type ) {
3087 if ( $action == $type || $action == '' ) {
3088 $r = $this->getRestrictions( $type );
3089 foreach ( $wgRestrictionLevels as $level ) {
3090 if ( in_array( $level, $r ) && $level != '' ) {
3091 return true;
3092 }
3093 }
3094 }
3095 }
3096
3097 return false;
3098 }
3099
3100 /**
3101 * Determines if $user is unable to edit this page because it has been protected
3102 * by $wgNamespaceProtection.
3103 *
3104 * @param User $user User object to check permissions
3105 * @return bool
3106 */
3107 public function isNamespaceProtected( User $user ) {
3108 global $wgNamespaceProtection;
3109
3110 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
3111 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
3112 if ( $right != '' && !$user->isAllowed( $right ) ) {
3113 return true;
3114 }
3115 }
3116 }
3117 return false;
3118 }
3119
3120 /**
3121 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3122 *
3123 * @return bool If the page is subject to cascading restrictions.
3124 */
3125 public function isCascadeProtected() {
3126 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3127 return ( $sources > 0 );
3128 }
3129
3130 /**
3131 * Determines whether cascading protection sources have already been loaded from
3132 * the database.
3133 *
3134 * @param bool $getPages True to check if the pages are loaded, or false to check
3135 * if the status is loaded.
3136 * @return bool Whether or not the specified information has been loaded
3137 * @since 1.23
3138 */
3139 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3140 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
3141 }
3142
3143 /**
3144 * Cascading protection: Get the source of any cascading restrictions on this page.
3145 *
3146 * @param bool $getPages Whether or not to retrieve the actual pages
3147 * that the restrictions have come from and the actual restrictions
3148 * themselves.
3149 * @return array Two elements: First is an array of Title objects of the
3150 * pages from which cascading restrictions have come, false for
3151 * none, or true if such restrictions exist but $getPages was not
3152 * set. Second is an array like that returned by
3153 * Title::getAllRestrictions(), or an empty array if $getPages is
3154 * false.
3155 */
3156 public function getCascadeProtectionSources( $getPages = true ) {
3157 $pagerestrictions = [];
3158
3159 if ( $this->mCascadeSources !== null && $getPages ) {
3160 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
3161 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
3162 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
3163 }
3164
3165 $dbr = wfGetDB( DB_REPLICA );
3166
3167 if ( $this->mNamespace == NS_FILE ) {
3168 $tables = [ 'imagelinks', 'page_restrictions' ];
3169 $where_clauses = [
3170 'il_to' => $this->mDbkeyform,
3171 'il_from=pr_page',
3172 'pr_cascade' => 1
3173 ];
3174 } else {
3175 $tables = [ 'templatelinks', 'page_restrictions' ];
3176 $where_clauses = [
3177 'tl_namespace' => $this->mNamespace,
3178 'tl_title' => $this->mDbkeyform,
3179 'tl_from=pr_page',
3180 'pr_cascade' => 1
3181 ];
3182 }
3183
3184 if ( $getPages ) {
3185 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3186 'pr_expiry', 'pr_type', 'pr_level' ];
3187 $where_clauses[] = 'page_id=pr_page';
3188 $tables[] = 'page';
3189 } else {
3190 $cols = [ 'pr_expiry' ];
3191 }
3192
3193 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
3194
3195 $sources = $getPages ? [] : false;
3196 $now = wfTimestampNow();
3197
3198 foreach ( $res as $row ) {
3199 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3200 if ( $expiry > $now ) {
3201 if ( $getPages ) {
3202 $page_id = $row->pr_page;
3203 $page_ns = $row->page_namespace;
3204 $page_title = $row->page_title;
3205 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
3206 # Add groups needed for each restriction type if its not already there
3207 # Make sure this restriction type still exists
3208
3209 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
3210 $pagerestrictions[$row->pr_type] = [];
3211 }
3212
3213 if (
3214 isset( $pagerestrictions[$row->pr_type] )
3215 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
3216 ) {
3217 $pagerestrictions[$row->pr_type][] = $row->pr_level;
3218 }
3219 } else {
3220 $sources = true;
3221 }
3222 }
3223 }
3224
3225 if ( $getPages ) {
3226 $this->mCascadeSources = $sources;
3227 $this->mCascadingRestrictions = $pagerestrictions;
3228 } else {
3229 $this->mHasCascadingRestrictions = $sources;
3230 }
3231
3232 return [ $sources, $pagerestrictions ];
3233 }
3234
3235 /**
3236 * Accessor for mRestrictionsLoaded
3237 *
3238 * @return bool Whether or not the page's restrictions have already been
3239 * loaded from the database
3240 * @since 1.23
3241 */
3242 public function areRestrictionsLoaded() {
3243 return $this->mRestrictionsLoaded;
3244 }
3245
3246 /**
3247 * Accessor/initialisation for mRestrictions
3248 *
3249 * @param string $action Action that permission needs to be checked for
3250 * @return array Restriction levels needed to take the action. All levels are
3251 * required. Note that restriction levels are normally user rights, but 'sysop'
3252 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3253 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3254 */
3255 public function getRestrictions( $action ) {
3256 if ( !$this->mRestrictionsLoaded ) {
3257 $this->loadRestrictions();
3258 }
3259 return $this->mRestrictions[$action] ?? [];
3260 }
3261
3262 /**
3263 * Accessor/initialisation for mRestrictions
3264 *
3265 * @return array Keys are actions, values are arrays as returned by
3266 * Title::getRestrictions()
3267 * @since 1.23
3268 */
3269 public function getAllRestrictions() {
3270 if ( !$this->mRestrictionsLoaded ) {
3271 $this->loadRestrictions();
3272 }
3273 return $this->mRestrictions;
3274 }
3275
3276 /**
3277 * Get the expiry time for the restriction against a given action
3278 *
3279 * @param string $action
3280 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3281 * or not protected at all, or false if the action is not recognised.
3282 */
3283 public function getRestrictionExpiry( $action ) {
3284 if ( !$this->mRestrictionsLoaded ) {
3285 $this->loadRestrictions();
3286 }
3287 return $this->mRestrictionsExpiry[$action] ?? false;
3288 }
3289
3290 /**
3291 * Returns cascading restrictions for the current article
3292 *
3293 * @return bool
3294 */
3295 function areRestrictionsCascading() {
3296 if ( !$this->mRestrictionsLoaded ) {
3297 $this->loadRestrictions();
3298 }
3299
3300 return $this->mCascadeRestriction;
3301 }
3302
3303 /**
3304 * Compiles list of active page restrictions from both page table (pre 1.10)
3305 * and page_restrictions table for this existing page.
3306 * Public for usage by LiquidThreads.
3307 *
3308 * @param array $rows Array of db result objects
3309 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3310 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3311 * Edit and move sections are separated by a colon
3312 * Example: "edit=autoconfirmed,sysop:move=sysop"
3313 */
3314 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3315 // This function will only read rows from a table that we migrated away
3316 // from before adding READ_LATEST support to loadRestrictions, so we
3317 // don't need to support reading from DB_MASTER here.
3318 $dbr = wfGetDB( DB_REPLICA );
3319
3320 $restrictionTypes = $this->getRestrictionTypes();
3321
3322 foreach ( $restrictionTypes as $type ) {
3323 $this->mRestrictions[$type] = [];
3324 $this->mRestrictionsExpiry[$type] = 'infinity';
3325 }
3326
3327 $this->mCascadeRestriction = false;
3328
3329 # Backwards-compatibility: also load the restrictions from the page record (old format).
3330 if ( $oldFashionedRestrictions !== null ) {
3331 $this->mOldRestrictions = $oldFashionedRestrictions;
3332 }
3333
3334 if ( $this->mOldRestrictions === false ) {
3335 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
3336 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
3337 }
3338
3339 if ( $this->mOldRestrictions != '' ) {
3340 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
3341 $temp = explode( '=', trim( $restrict ) );
3342 if ( count( $temp ) == 1 ) {
3343 // old old format should be treated as edit/move restriction
3344 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
3345 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
3346 } else {
3347 $restriction = trim( $temp[1] );
3348 if ( $restriction != '' ) { // some old entries are empty
3349 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
3350 }
3351 }
3352 }
3353 }
3354
3355 if ( count( $rows ) ) {
3356 # Current system - load second to make them override.
3357 $now = wfTimestampNow();
3358
3359 # Cycle through all the restrictions.
3360 foreach ( $rows as $row ) {
3361 // Don't take care of restrictions types that aren't allowed
3362 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
3363 continue;
3364 }
3365
3366 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3367
3368 // Only apply the restrictions if they haven't expired!
3369 if ( !$expiry || $expiry > $now ) {
3370 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
3371 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
3372
3373 $this->mCascadeRestriction |= $row->pr_cascade;
3374 }
3375 }
3376 }
3377
3378 $this->mRestrictionsLoaded = true;
3379 }
3380
3381 /**
3382 * Load restrictions from the page_restrictions table
3383 *
3384 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3385 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3386 * Edit and move sections are separated by a colon
3387 * Example: "edit=autoconfirmed,sysop:move=sysop"
3388 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3389 * from the master DB.
3390 */
3391 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3392 $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
3393 if ( $this->mRestrictionsLoaded && !$readLatest ) {
3394 return;
3395 }
3396
3397 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3398 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3399 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3400 $id = $this->getArticleID();
3401 if ( $id ) {
3402 $fname = __METHOD__;
3403 $loadRestrictionsFromDb = function ( Database $dbr ) use ( $fname, $id ) {
3404 return iterator_to_array(
3405 $dbr->select(
3406 'page_restrictions',
3407 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3408 [ 'pr_page' => $id ],
3409 $fname
3410 )
3411 );
3412 };
3413
3414 if ( $readLatest ) {
3415 $dbr = wfGetDB( DB_MASTER );
3416 $rows = $loadRestrictionsFromDb( $dbr );
3417 } else {
3418 $cache = ObjectCache::getMainWANInstance();
3419 $rows = $cache->getWithSetCallback(
3420 // Page protections always leave a new null revision
3421 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3422 $cache::TTL_DAY,
3423 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3424 $dbr = wfGetDB( DB_REPLICA );
3425
3426 $setOpts += Database::getCacheSetOptions( $dbr );
3427
3428 return $loadRestrictionsFromDb( $dbr );
3429 }
3430 );
3431 }
3432
3433 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3434 } else {
3435 $title_protection = $this->getTitleProtectionInternal();
3436
3437 if ( $title_protection ) {
3438 $now = wfTimestampNow();
3439 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3440
3441 if ( !$expiry || $expiry > $now ) {
3442 // Apply the restrictions
3443 $this->mRestrictionsExpiry['create'] = $expiry;
3444 $this->mRestrictions['create'] =
3445 explode( ',', trim( $title_protection['permission'] ) );
3446 } else { // Get rid of the old restrictions
3447 $this->mTitleProtection = false;
3448 }
3449 } else {
3450 $this->mRestrictionsExpiry['create'] = 'infinity';
3451 }
3452 $this->mRestrictionsLoaded = true;
3453 }
3454 }
3455
3456 /**
3457 * Flush the protection cache in this object and force reload from the database.
3458 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3459 */
3460 public function flushRestrictions() {
3461 $this->mRestrictionsLoaded = false;
3462 $this->mTitleProtection = null;
3463 }
3464
3465 /**
3466 * Purge expired restrictions from the page_restrictions table
3467 *
3468 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3469 */
3470 static function purgeExpiredRestrictions() {
3471 if ( wfReadOnly() ) {
3472 return;
3473 }
3474
3475 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3476 wfGetDB( DB_MASTER ),
3477 __METHOD__,
3478 function ( IDatabase $dbw, $fname ) {
3479 $config = MediaWikiServices::getInstance()->getMainConfig();
3480 $ids = $dbw->selectFieldValues(
3481 'page_restrictions',
3482 'pr_id',
3483 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3484 $fname,
3485 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3486 );
3487 if ( $ids ) {
3488 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3489 }
3490 }
3491 ) );
3492
3493 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3494 wfGetDB( DB_MASTER ),
3495 __METHOD__,
3496 function ( IDatabase $dbw, $fname ) {
3497 $dbw->delete(
3498 'protected_titles',
3499 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3500 $fname
3501 );
3502 }
3503 ) );
3504 }
3505
3506 /**
3507 * Does this have subpages? (Warning, usually requires an extra DB query.)
3508 *
3509 * @return bool
3510 */
3511 public function hasSubpages() {
3512 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3513 # Duh
3514 return false;
3515 }
3516
3517 # We dynamically add a member variable for the purpose of this method
3518 # alone to cache the result. There's no point in having it hanging
3519 # around uninitialized in every Title object; therefore we only add it
3520 # if needed and don't declare it statically.
3521 if ( $this->mHasSubpages === null ) {
3522 $this->mHasSubpages = false;
3523 $subpages = $this->getSubpages( 1 );
3524 if ( $subpages instanceof TitleArray ) {
3525 $this->mHasSubpages = (bool)$subpages->count();
3526 }
3527 }
3528
3529 return $this->mHasSubpages;
3530 }
3531
3532 /**
3533 * Get all subpages of this page.
3534 *
3535 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3536 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3537 * doesn't allow subpages
3538 */
3539 public function getSubpages( $limit = -1 ) {
3540 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3541 return [];
3542 }
3543
3544 $dbr = wfGetDB( DB_REPLICA );
3545 $conds['page_namespace'] = $this->mNamespace;
3546 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3547 $options = [];
3548 if ( $limit > -1 ) {
3549 $options['LIMIT'] = $limit;
3550 }
3551 return TitleArray::newFromResult(
3552 $dbr->select( 'page',
3553 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3554 $conds,
3555 __METHOD__,
3556 $options
3557 )
3558 );
3559 }
3560
3561 /**
3562 * Is there a version of this page in the deletion archive?
3563 *
3564 * @return int The number of archived revisions
3565 */
3566 public function isDeleted() {
3567 if ( $this->mNamespace < 0 ) {
3568 $n = 0;
3569 } else {
3570 $dbr = wfGetDB( DB_REPLICA );
3571
3572 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3573 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3574 __METHOD__
3575 );
3576 if ( $this->mNamespace == NS_FILE ) {
3577 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3578 [ 'fa_name' => $this->mDbkeyform ],
3579 __METHOD__
3580 );
3581 }
3582 }
3583 return (int)$n;
3584 }
3585
3586 /**
3587 * Is there a version of this page in the deletion archive?
3588 *
3589 * @return bool
3590 */
3591 public function isDeletedQuick() {
3592 if ( $this->mNamespace < 0 ) {
3593 return false;
3594 }
3595 $dbr = wfGetDB( DB_REPLICA );
3596 $deleted = (bool)$dbr->selectField( 'archive', '1',
3597 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3598 __METHOD__
3599 );
3600 if ( !$deleted && $this->mNamespace == NS_FILE ) {
3601 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3602 [ 'fa_name' => $this->mDbkeyform ],
3603 __METHOD__
3604 );
3605 }
3606 return $deleted;
3607 }
3608
3609 /**
3610 * Get the article ID for this Title from the link cache,
3611 * adding it if necessary
3612 *
3613 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3614 * for update
3615 * @return int The ID
3616 */
3617 public function getArticleID( $flags = 0 ) {
3618 if ( $this->mNamespace < 0 ) {
3619 $this->mArticleID = 0;
3620 return $this->mArticleID;
3621 }
3622 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3623 if ( $flags & self::GAID_FOR_UPDATE ) {
3624 $oldUpdate = $linkCache->forUpdate( true );
3625 $linkCache->clearLink( $this );
3626 $this->mArticleID = $linkCache->addLinkObj( $this );
3627 $linkCache->forUpdate( $oldUpdate );
3628 } else {
3629 if ( $this->mArticleID == -1 ) {
3630 $this->mArticleID = $linkCache->addLinkObj( $this );
3631 }
3632 }
3633 return $this->mArticleID;
3634 }
3635
3636 /**
3637 * Is this an article that is a redirect page?
3638 * Uses link cache, adding it if necessary
3639 *
3640 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3641 * @return bool
3642 */
3643 public function isRedirect( $flags = 0 ) {
3644 if ( !is_null( $this->mRedirect ) ) {
3645 return $this->mRedirect;
3646 }
3647 if ( !$this->getArticleID( $flags ) ) {
3648 $this->mRedirect = false;
3649 return $this->mRedirect;
3650 }
3651
3652 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3653 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3654 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3655 if ( $cached === null ) {
3656 # Trust LinkCache's state over our own
3657 # LinkCache is telling us that the page doesn't exist, despite there being cached
3658 # data relating to an existing page in $this->mArticleID. Updaters should clear
3659 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3660 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3661 # LinkCache to refresh its data from the master.
3662 $this->mRedirect = false;
3663 return $this->mRedirect;
3664 }
3665
3666 $this->mRedirect = (bool)$cached;
3667
3668 return $this->mRedirect;
3669 }
3670
3671 /**
3672 * What is the length of this page?
3673 * Uses link cache, adding it if necessary
3674 *
3675 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3676 * @return int
3677 */
3678 public function getLength( $flags = 0 ) {
3679 if ( $this->mLength != -1 ) {
3680 return $this->mLength;
3681 }
3682 if ( !$this->getArticleID( $flags ) ) {
3683 $this->mLength = 0;
3684 return $this->mLength;
3685 }
3686 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3687 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3688 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3689 if ( $cached === null ) {
3690 # Trust LinkCache's state over our own, as for isRedirect()
3691 $this->mLength = 0;
3692 return $this->mLength;
3693 }
3694
3695 $this->mLength = intval( $cached );
3696
3697 return $this->mLength;
3698 }
3699
3700 /**
3701 * What is the page_latest field for this page?
3702 *
3703 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3704 * @return int Int or 0 if the page doesn't exist
3705 */
3706 public function getLatestRevID( $flags = 0 ) {
3707 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3708 return intval( $this->mLatestID );
3709 }
3710 if ( !$this->getArticleID( $flags ) ) {
3711 $this->mLatestID = 0;
3712 return $this->mLatestID;
3713 }
3714 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3715 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3716 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3717 if ( $cached === null ) {
3718 # Trust LinkCache's state over our own, as for isRedirect()
3719 $this->mLatestID = 0;
3720 return $this->mLatestID;
3721 }
3722
3723 $this->mLatestID = intval( $cached );
3724
3725 return $this->mLatestID;
3726 }
3727
3728 /**
3729 * This clears some fields in this object, and clears any associated
3730 * keys in the "bad links" section of the link cache.
3731 *
3732 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3733 * loading of the new page_id. It's also called from
3734 * WikiPage::doDeleteArticleReal()
3735 *
3736 * @param int $newid The new Article ID
3737 */
3738 public function resetArticleID( $newid ) {
3739 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3740 $linkCache->clearLink( $this );
3741
3742 if ( $newid === false ) {
3743 $this->mArticleID = -1;
3744 } else {
3745 $this->mArticleID = intval( $newid );
3746 }
3747 $this->mRestrictionsLoaded = false;
3748 $this->mRestrictions = [];
3749 $this->mOldRestrictions = false;
3750 $this->mRedirect = null;
3751 $this->mLength = -1;
3752 $this->mLatestID = false;
3753 $this->mContentModel = false;
3754 $this->mEstimateRevisions = null;
3755 $this->mPageLanguage = false;
3756 $this->mDbPageLanguage = false;
3757 $this->mIsBigDeletion = null;
3758 }
3759
3760 public static function clearCaches() {
3761 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3762 $linkCache->clear();
3763
3764 $titleCache = self::getTitleCache();
3765 $titleCache->clear();
3766 }
3767
3768 /**
3769 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3770 *
3771 * @param string $text Containing title to capitalize
3772 * @param int $ns Namespace index, defaults to NS_MAIN
3773 * @return string Containing capitalized title
3774 */
3775 public static function capitalize( $text, $ns = NS_MAIN ) {
3776 if ( MWNamespace::isCapitalized( $ns ) ) {
3777 return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text );
3778 } else {
3779 return $text;
3780 }
3781 }
3782
3783 /**
3784 * Secure and split - main initialisation function for this object
3785 *
3786 * Assumes that mDbkeyform has been set, and is urldecoded
3787 * and uses underscores, but not otherwise munged. This function
3788 * removes illegal characters, splits off the interwiki and
3789 * namespace prefixes, sets the other forms, and canonicalizes
3790 * everything.
3791 *
3792 * @throws MalformedTitleException On invalid titles
3793 * @return bool True on success
3794 */
3795 private function secureAndSplit() {
3796 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3797 // the parsing code with Title, while avoiding massive refactoring.
3798 // @todo: get rid of secureAndSplit, refactor parsing code.
3799 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3800 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3801 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3802 // MalformedTitleException can be thrown here
3803 $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
3804
3805 # Fill fields
3806 $this->setFragment( '#' . $parts['fragment'] );
3807 $this->mInterwiki = $parts['interwiki'];
3808 $this->mLocalInterwiki = $parts['local_interwiki'];
3809 $this->mNamespace = $parts['namespace'];
3810 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3811
3812 $this->mDbkeyform = $parts['dbkey'];
3813 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3814 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3815
3816 # We already know that some pages won't be in the database!
3817 if ( $this->isExternal() || $this->isSpecialPage() ) {
3818 $this->mArticleID = 0;
3819 }
3820
3821 return true;
3822 }
3823
3824 /**
3825 * Get an array of Title objects linking to this Title
3826 * Also stores the IDs in the link cache.
3827 *
3828 * WARNING: do not use this function on arbitrary user-supplied titles!
3829 * On heavily-used templates it will max out the memory.
3830 *
3831 * @param array $options May be FOR UPDATE
3832 * @param string $table Table name
3833 * @param string $prefix Fields prefix
3834 * @return Title[] Array of Title objects linking here
3835 */
3836 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3837 if ( count( $options ) > 0 ) {
3838 $db = wfGetDB( DB_MASTER );
3839 } else {
3840 $db = wfGetDB( DB_REPLICA );
3841 }
3842
3843 $res = $db->select(
3844 [ 'page', $table ],
3845 self::getSelectFields(),
3846 [
3847 "{$prefix}_from=page_id",
3848 "{$prefix}_namespace" => $this->mNamespace,
3849 "{$prefix}_title" => $this->mDbkeyform ],
3850 __METHOD__,
3851 $options
3852 );
3853
3854 $retVal = [];
3855 if ( $res->numRows() ) {
3856 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3857 foreach ( $res as $row ) {
3858 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3859 if ( $titleObj ) {
3860 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3861 $retVal[] = $titleObj;
3862 }
3863 }
3864 }
3865 return $retVal;
3866 }
3867
3868 /**
3869 * Get an array of Title objects using this Title as a template
3870 * Also stores the IDs in the link cache.
3871 *
3872 * WARNING: do not use this function on arbitrary user-supplied titles!
3873 * On heavily-used templates it will max out the memory.
3874 *
3875 * @param array $options Query option to Database::select()
3876 * @return Title[] Array of Title the Title objects linking here
3877 */
3878 public function getTemplateLinksTo( $options = [] ) {
3879 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3880 }
3881
3882 /**
3883 * Get an array of Title objects linked from this Title
3884 * Also stores the IDs in the link cache.
3885 *
3886 * WARNING: do not use this function on arbitrary user-supplied titles!
3887 * On heavily-used templates it will max out the memory.
3888 *
3889 * @param array $options Query option to Database::select()
3890 * @param string $table Table name
3891 * @param string $prefix Fields prefix
3892 * @return array Array of Title objects linking here
3893 */
3894 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3895 $id = $this->getArticleID();
3896
3897 # If the page doesn't exist; there can't be any link from this page
3898 if ( !$id ) {
3899 return [];
3900 }
3901
3902 $db = wfGetDB( DB_REPLICA );
3903
3904 $blNamespace = "{$prefix}_namespace";
3905 $blTitle = "{$prefix}_title";
3906
3907 $pageQuery = WikiPage::getQueryInfo();
3908 $res = $db->select(
3909 [ $table, 'nestpage' => $pageQuery['tables'] ],
3910 array_merge(
3911 [ $blNamespace, $blTitle ],
3912 $pageQuery['fields']
3913 ),
3914 [ "{$prefix}_from" => $id ],
3915 __METHOD__,
3916 $options,
3917 [ 'nestpage' => [
3918 'LEFT JOIN',
3919 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3920 ] ] + $pageQuery['joins']
3921 );
3922
3923 $retVal = [];
3924 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3925 foreach ( $res as $row ) {
3926 if ( $row->page_id ) {
3927 $titleObj = self::newFromRow( $row );
3928 } else {
3929 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3930 $linkCache->addBadLinkObj( $titleObj );
3931 }
3932 $retVal[] = $titleObj;
3933 }
3934
3935 return $retVal;
3936 }
3937
3938 /**
3939 * Get an array of Title objects used on this Title as a template
3940 * Also stores the IDs in the link cache.
3941 *
3942 * WARNING: do not use this function on arbitrary user-supplied titles!
3943 * On heavily-used templates it will max out the memory.
3944 *
3945 * @param array $options May be FOR UPDATE
3946 * @return Title[] Array of Title the Title objects used here
3947 */
3948 public function getTemplateLinksFrom( $options = [] ) {
3949 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3950 }
3951
3952 /**
3953 * Get an array of Title objects referring to non-existent articles linked
3954 * from this page.
3955 *
3956 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3957 * should use redirect table in this case).
3958 * @return Title[] Array of Title the Title objects
3959 */
3960 public function getBrokenLinksFrom() {
3961 if ( $this->getArticleID() == 0 ) {
3962 # All links from article ID 0 are false positives
3963 return [];
3964 }
3965
3966 $dbr = wfGetDB( DB_REPLICA );
3967 $res = $dbr->select(
3968 [ 'page', 'pagelinks' ],
3969 [ 'pl_namespace', 'pl_title' ],
3970 [
3971 'pl_from' => $this->getArticleID(),
3972 'page_namespace IS NULL'
3973 ],
3974 __METHOD__, [],
3975 [
3976 'page' => [
3977 'LEFT JOIN',
3978 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3979 ]
3980 ]
3981 );
3982
3983 $retVal = [];
3984 foreach ( $res as $row ) {
3985 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3986 }
3987 return $retVal;
3988 }
3989
3990 /**
3991 * Get a list of URLs to purge from the CDN cache when this
3992 * page changes
3993 *
3994 * @return string[] Array of String the URLs
3995 */
3996 public function getCdnUrls() {
3997 $urls = [
3998 $this->getInternalURL(),
3999 $this->getInternalURL( 'action=history' )
4000 ];
4001
4002 $pageLang = $this->getPageLanguage();
4003 if ( $pageLang->hasVariants() ) {
4004 $variants = $pageLang->getVariants();
4005 foreach ( $variants as $vCode ) {
4006 $urls[] = $this->getInternalURL( $vCode );
4007 }
4008 }
4009
4010 // If we are looking at a css/js user subpage, purge the action=raw.
4011 if ( $this->isUserJsConfigPage() ) {
4012 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
4013 } elseif ( $this->isUserJsonConfigPage() ) {
4014 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
4015 } elseif ( $this->isUserCssConfigPage() ) {
4016 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
4017 }
4018
4019 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
4020 return $urls;
4021 }
4022
4023 /**
4024 * @deprecated since 1.27 use getCdnUrls()
4025 */
4026 public function getSquidURLs() {
4027 return $this->getCdnUrls();
4028 }
4029
4030 /**
4031 * Purge all applicable CDN URLs
4032 */
4033 public function purgeSquid() {
4034 DeferredUpdates::addUpdate(
4035 new CdnCacheUpdate( $this->getCdnUrls() ),
4036 DeferredUpdates::PRESEND
4037 );
4038 }
4039
4040 /**
4041 * Check whether a given move operation would be valid.
4042 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
4043 *
4044 * @deprecated since 1.25, use MovePage's methods instead
4045 * @param Title &$nt The new title
4046 * @param bool $auth Whether to check user permissions (uses $wgUser)
4047 * @param string $reason Is the log summary of the move, used for spam checking
4048 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4049 */
4050 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4051 global $wgUser;
4052
4053 if ( !( $nt instanceof Title ) ) {
4054 // Normally we'd add this to $errors, but we'll get
4055 // lots of syntax errors if $nt is not an object
4056 return [ [ 'badtitletext' ] ];
4057 }
4058
4059 $mp = new MovePage( $this, $nt );
4060 $errors = $mp->isValidMove()->getErrorsArray();
4061 if ( $auth ) {
4062 $errors = wfMergeErrorArrays(
4063 $errors,
4064 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4065 );
4066 }
4067
4068 return $errors ?: true;
4069 }
4070
4071 /**
4072 * Check if the requested move target is a valid file move target
4073 * @todo move this to MovePage
4074 * @param Title $nt Target title
4075 * @return array List of errors
4076 */
4077 protected function validateFileMoveOperation( $nt ) {
4078 global $wgUser;
4079
4080 $errors = [];
4081
4082 $destFile = wfLocalFile( $nt );
4083 $destFile->load( File::READ_LATEST );
4084 if ( !$wgUser->isAllowed( 'reupload-shared' )
4085 && !$destFile->exists() && wfFindFile( $nt )
4086 ) {
4087 $errors[] = [ 'file-exists-sharedrepo' ];
4088 }
4089
4090 return $errors;
4091 }
4092
4093 /**
4094 * Move a title to a new location
4095 *
4096 * @deprecated since 1.25, use the MovePage class instead
4097 * @param Title &$nt The new title
4098 * @param bool $auth Indicates whether $wgUser's permissions
4099 * should be checked
4100 * @param string $reason The reason for the move
4101 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4102 * Ignored if the user doesn't have the suppressredirect right.
4103 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4104 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4105 */
4106 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4107 array $changeTags = []
4108 ) {
4109 global $wgUser;
4110 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4111 if ( is_array( $err ) ) {
4112 // Auto-block user's IP if the account was "hard" blocked
4113 $wgUser->spreadAnyEditBlock();
4114 return $err;
4115 }
4116 // Check suppressredirect permission
4117 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4118 $createRedirect = true;
4119 }
4120
4121 $mp = new MovePage( $this, $nt );
4122 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4123 if ( $status->isOK() ) {
4124 return true;
4125 } else {
4126 return $status->getErrorsArray();
4127 }
4128 }
4129
4130 /**
4131 * Move this page's subpages to be subpages of $nt
4132 *
4133 * @param Title $nt Move target
4134 * @param bool $auth Whether $wgUser's permissions should be checked
4135 * @param string $reason The reason for the move
4136 * @param bool $createRedirect Whether to create redirects from the old subpages to
4137 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4138 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4139 * @return array Array with old page titles as keys, and strings (new page titles) or
4140 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4141 * getUserPermissionsErrors()-like error array with numeric indices if
4142 * no pages were moved
4143 */
4144 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4145 array $changeTags = []
4146 ) {
4147 global $wgMaximumMovedPages;
4148 // Check permissions
4149 if ( !$this->userCan( 'move-subpages' ) ) {
4150 return [
4151 [ 'cant-move-subpages' ],
4152 ];
4153 }
4154 // Do the source and target namespaces support subpages?
4155 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
4156 return [
4157 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->mNamespace ) ],
4158 ];
4159 }
4160 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
4161 return [
4162 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
4163 ];
4164 }
4165
4166 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
4167 $retval = [];
4168 $count = 0;
4169 foreach ( $subpages as $oldSubpage ) {
4170 $count++;
4171 if ( $count > $wgMaximumMovedPages ) {
4172 $retval[$oldSubpage->getPrefixedText()] = [
4173 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4174 ];
4175 break;
4176 }
4177
4178 // We don't know whether this function was called before
4179 // or after moving the root page, so check both
4180 // $this and $nt
4181 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4182 || $oldSubpage->getArticleID() == $nt->getArticleID()
4183 ) {
4184 // When moving a page to a subpage of itself,
4185 // don't move it twice
4186 continue;
4187 }
4188 $newPageName = preg_replace(
4189 '#^' . preg_quote( $this->mDbkeyform, '#' ) . '#',
4190 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4191 $oldSubpage->getDBkey() );
4192 if ( $oldSubpage->isTalkPage() ) {
4193 $newNs = $nt->getTalkPage()->getNamespace();
4194 } else {
4195 $newNs = $nt->getSubjectPage()->getNamespace();
4196 }
4197 # T16385: we need makeTitleSafe because the new page names may
4198 # be longer than 255 characters.
4199 $newSubpage = self::makeTitleSafe( $newNs, $newPageName );
4200
4201 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4202 if ( $success === true ) {
4203 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4204 } else {
4205 $retval[$oldSubpage->getPrefixedText()] = $success;
4206 }
4207 }
4208 return $retval;
4209 }
4210
4211 /**
4212 * Checks if this page is just a one-rev redirect.
4213 * Adds lock, so don't use just for light purposes.
4214 *
4215 * @return bool
4216 */
4217 public function isSingleRevRedirect() {
4218 global $wgContentHandlerUseDB;
4219
4220 $dbw = wfGetDB( DB_MASTER );
4221
4222 # Is it a redirect?
4223 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4224 if ( $wgContentHandlerUseDB ) {
4225 $fields[] = 'page_content_model';
4226 }
4227
4228 $row = $dbw->selectRow( 'page',
4229 $fields,
4230 $this->pageCond(),
4231 __METHOD__,
4232 [ 'FOR UPDATE' ]
4233 );
4234 # Cache some fields we may want
4235 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4236 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4237 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4238 $this->mContentModel = $row && isset( $row->page_content_model )
4239 ? strval( $row->page_content_model )
4240 : false;
4241
4242 if ( !$this->mRedirect ) {
4243 return false;
4244 }
4245 # Does the article have a history?
4246 $row = $dbw->selectField( [ 'page', 'revision' ],
4247 'rev_id',
4248 [ 'page_namespace' => $this->mNamespace,
4249 'page_title' => $this->mDbkeyform,
4250 'page_id=rev_page',
4251 'page_latest != rev_id'
4252 ],
4253 __METHOD__,
4254 [ 'FOR UPDATE' ]
4255 );
4256 # Return true if there was no history
4257 return ( $row === false );
4258 }
4259
4260 /**
4261 * Checks if $this can be moved to a given Title
4262 * - Selects for update, so don't call it unless you mean business
4263 *
4264 * @deprecated since 1.25, use MovePage's methods instead
4265 * @param Title $nt The new title to check
4266 * @return bool
4267 */
4268 public function isValidMoveTarget( $nt ) {
4269 # Is it an existing file?
4270 if ( $nt->getNamespace() == NS_FILE ) {
4271 $file = wfLocalFile( $nt );
4272 $file->load( File::READ_LATEST );
4273 if ( $file->exists() ) {
4274 wfDebug( __METHOD__ . ": file exists\n" );
4275 return false;
4276 }
4277 }
4278 # Is it a redirect with no history?
4279 if ( !$nt->isSingleRevRedirect() ) {
4280 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4281 return false;
4282 }
4283 # Get the article text
4284 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4285 if ( !is_object( $rev ) ) {
4286 return false;
4287 }
4288 $content = $rev->getContent();
4289 # Does the redirect point to the source?
4290 # Or is it a broken self-redirect, usually caused by namespace collisions?
4291 $redirTitle = $content ? $content->getRedirectTarget() : null;
4292
4293 if ( $redirTitle ) {
4294 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4295 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4296 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4297 return false;
4298 } else {
4299 return true;
4300 }
4301 } else {
4302 # Fail safe (not a redirect after all. strange.)
4303 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4304 " is a redirect, but it doesn't contain a valid redirect.\n" );
4305 return false;
4306 }
4307 }
4308
4309 /**
4310 * Get categories to which this Title belongs and return an array of
4311 * categories' names.
4312 *
4313 * @return array Array of parents in the form:
4314 * $parent => $currentarticle
4315 */
4316 public function getParentCategories() {
4317 $data = [];
4318
4319 $titleKey = $this->getArticleID();
4320
4321 if ( $titleKey === 0 ) {
4322 return $data;
4323 }
4324
4325 $dbr = wfGetDB( DB_REPLICA );
4326
4327 $res = $dbr->select(
4328 'categorylinks',
4329 'cl_to',
4330 [ 'cl_from' => $titleKey ],
4331 __METHOD__
4332 );
4333
4334 if ( $res->numRows() > 0 ) {
4335 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4336 foreach ( $res as $row ) {
4337 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4338 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
4339 $this->getFullText();
4340 }
4341 }
4342 return $data;
4343 }
4344
4345 /**
4346 * Get a tree of parent categories
4347 *
4348 * @param array $children Array with the children in the keys, to check for circular refs
4349 * @return array Tree of parent categories
4350 */
4351 public function getParentCategoryTree( $children = [] ) {
4352 $stack = [];
4353 $parents = $this->getParentCategories();
4354
4355 if ( $parents ) {
4356 foreach ( $parents as $parent => $current ) {
4357 if ( array_key_exists( $parent, $children ) ) {
4358 # Circular reference
4359 $stack[$parent] = [];
4360 } else {
4361 $nt = self::newFromText( $parent );
4362 if ( $nt ) {
4363 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
4364 }
4365 }
4366 }
4367 }
4368
4369 return $stack;
4370 }
4371
4372 /**
4373 * Get an associative array for selecting this title from
4374 * the "page" table
4375 *
4376 * @return array Array suitable for the $where parameter of DB::select()
4377 */
4378 public function pageCond() {
4379 if ( $this->mArticleID > 0 ) {
4380 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4381 return [ 'page_id' => $this->mArticleID ];
4382 } else {
4383 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
4384 }
4385 }
4386
4387 /**
4388 * Get next/previous revision ID relative to another revision ID
4389 * @param int $revId Revision ID. Get the revision that was before this one.
4390 * @param int $flags Title::GAID_FOR_UPDATE
4391 * @param string $dir 'next' or 'prev'
4392 * @return int|bool New revision ID, or false if none exists
4393 */
4394 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4395 $revId = (int)$revId;
4396 if ( $dir === 'next' ) {
4397 $op = '>';
4398 $sort = 'ASC';
4399 } elseif ( $dir === 'prev' ) {
4400 $op = '<';
4401 $sort = 'DESC';
4402 } else {
4403 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4404 }
4405
4406 if ( $flags & self::GAID_FOR_UPDATE ) {
4407 $db = wfGetDB( DB_MASTER );
4408 } else {
4409 $db = wfGetDB( DB_REPLICA, 'contributions' );
4410 }
4411
4412 // Intentionally not caring if the specified revision belongs to this
4413 // page. We only care about the timestamp.
4414 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ );
4415 if ( $ts === false ) {
4416 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ );
4417 if ( $ts === false ) {
4418 // Or should this throw an InvalidArgumentException or something?
4419 return false;
4420 }
4421 }
4422 $ts = $db->addQuotes( $ts );
4423
4424 $revId = $db->selectField( 'revision', 'rev_id',
4425 [
4426 'rev_page' => $this->getArticleID( $flags ),
4427 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4428 ],
4429 __METHOD__,
4430 [
4431 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4432 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4433 ]
4434 );
4435
4436 if ( $revId === false ) {
4437 return false;
4438 } else {
4439 return intval( $revId );
4440 }
4441 }
4442
4443 /**
4444 * Get the revision ID of the previous revision
4445 *
4446 * @param int $revId Revision ID. Get the revision that was before this one.
4447 * @param int $flags Title::GAID_FOR_UPDATE
4448 * @return int|bool Old revision ID, or false if none exists
4449 */
4450 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4451 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4452 }
4453
4454 /**
4455 * Get the revision ID of the next revision
4456 *
4457 * @param int $revId Revision ID. Get the revision that was after this one.
4458 * @param int $flags Title::GAID_FOR_UPDATE
4459 * @return int|bool Next revision ID, or false if none exists
4460 */
4461 public function getNextRevisionID( $revId, $flags = 0 ) {
4462 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4463 }
4464
4465 /**
4466 * Get the first revision of the page
4467 *
4468 * @param int $flags Title::GAID_FOR_UPDATE
4469 * @return Revision|null If page doesn't exist
4470 */
4471 public function getFirstRevision( $flags = 0 ) {
4472 $pageId = $this->getArticleID( $flags );
4473 if ( $pageId ) {
4474 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4475 $revQuery = Revision::getQueryInfo();
4476 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4477 [ 'rev_page' => $pageId ],
4478 __METHOD__,
4479 [
4480 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4481 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4482 ],
4483 $revQuery['joins']
4484 );
4485 if ( $row ) {
4486 return new Revision( $row, 0, $this );
4487 }
4488 }
4489 return null;
4490 }
4491
4492 /**
4493 * Get the oldest revision timestamp of this page
4494 *
4495 * @param int $flags Title::GAID_FOR_UPDATE
4496 * @return string|null MW timestamp
4497 */
4498 public function getEarliestRevTime( $flags = 0 ) {
4499 $rev = $this->getFirstRevision( $flags );
4500 return $rev ? $rev->getTimestamp() : null;
4501 }
4502
4503 /**
4504 * Check if this is a new page
4505 *
4506 * @return bool
4507 */
4508 public function isNewPage() {
4509 $dbr = wfGetDB( DB_REPLICA );
4510 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4511 }
4512
4513 /**
4514 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4515 *
4516 * @return bool
4517 */
4518 public function isBigDeletion() {
4519 global $wgDeleteRevisionsLimit;
4520
4521 if ( !$wgDeleteRevisionsLimit ) {
4522 return false;
4523 }
4524
4525 if ( $this->mIsBigDeletion === null ) {
4526 $dbr = wfGetDB( DB_REPLICA );
4527
4528 $revCount = $dbr->selectRowCount(
4529 'revision',
4530 '1',
4531 [ 'rev_page' => $this->getArticleID() ],
4532 __METHOD__,
4533 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4534 );
4535
4536 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4537 }
4538
4539 return $this->mIsBigDeletion;
4540 }
4541
4542 /**
4543 * Get the approximate revision count of this page.
4544 *
4545 * @return int
4546 */
4547 public function estimateRevisionCount() {
4548 if ( !$this->exists() ) {
4549 return 0;
4550 }
4551
4552 if ( $this->mEstimateRevisions === null ) {
4553 $dbr = wfGetDB( DB_REPLICA );
4554 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4555 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4556 }
4557
4558 return $this->mEstimateRevisions;
4559 }
4560
4561 /**
4562 * Get the number of revisions between the given revision.
4563 * Used for diffs and other things that really need it.
4564 *
4565 * @param int|Revision $old Old revision or rev ID (first before range)
4566 * @param int|Revision $new New revision or rev ID (first after range)
4567 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4568 * @return int Number of revisions between these revisions.
4569 */
4570 public function countRevisionsBetween( $old, $new, $max = null ) {
4571 if ( !( $old instanceof Revision ) ) {
4572 $old = Revision::newFromTitle( $this, (int)$old );
4573 }
4574 if ( !( $new instanceof Revision ) ) {
4575 $new = Revision::newFromTitle( $this, (int)$new );
4576 }
4577 if ( !$old || !$new ) {
4578 return 0; // nothing to compare
4579 }
4580 $dbr = wfGetDB( DB_REPLICA );
4581 $conds = [
4582 'rev_page' => $this->getArticleID(),
4583 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4584 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4585 ];
4586 if ( $max !== null ) {
4587 return $dbr->selectRowCount( 'revision', '1',
4588 $conds,
4589 __METHOD__,
4590 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4591 );
4592 } else {
4593 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4594 }
4595 }
4596
4597 /**
4598 * Get the authors between the given revisions or revision IDs.
4599 * Used for diffs and other things that really need it.
4600 *
4601 * @since 1.23
4602 *
4603 * @param int|Revision $old Old revision or rev ID (first before range by default)
4604 * @param int|Revision $new New revision or rev ID (first after range by default)
4605 * @param int $limit Maximum number of authors
4606 * @param string|array $options (Optional): Single option, or an array of options:
4607 * 'include_old' Include $old in the range; $new is excluded.
4608 * 'include_new' Include $new in the range; $old is excluded.
4609 * 'include_both' Include both $old and $new in the range.
4610 * Unknown option values are ignored.
4611 * @return array|null Names of revision authors in the range; null if not both revisions exist
4612 */
4613 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4614 if ( !( $old instanceof Revision ) ) {
4615 $old = Revision::newFromTitle( $this, (int)$old );
4616 }
4617 if ( !( $new instanceof Revision ) ) {
4618 $new = Revision::newFromTitle( $this, (int)$new );
4619 }
4620 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4621 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4622 // in the sanity check below?
4623 if ( !$old || !$new ) {
4624 return null; // nothing to compare
4625 }
4626 $authors = [];
4627 $old_cmp = '>';
4628 $new_cmp = '<';
4629 $options = (array)$options;
4630 if ( in_array( 'include_old', $options ) ) {
4631 $old_cmp = '>=';
4632 }
4633 if ( in_array( 'include_new', $options ) ) {
4634 $new_cmp = '<=';
4635 }
4636 if ( in_array( 'include_both', $options ) ) {
4637 $old_cmp = '>=';
4638 $new_cmp = '<=';
4639 }
4640 // No DB query needed if $old and $new are the same or successive revisions:
4641 if ( $old->getId() === $new->getId() ) {
4642 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4643 [] :
4644 [ $old->getUserText( Revision::RAW ) ];
4645 } elseif ( $old->getId() === $new->getParentId() ) {
4646 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4647 $authors[] = $old->getUserText( Revision::RAW );
4648 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4649 $authors[] = $new->getUserText( Revision::RAW );
4650 }
4651 } elseif ( $old_cmp === '>=' ) {
4652 $authors[] = $old->getUserText( Revision::RAW );
4653 } elseif ( $new_cmp === '<=' ) {
4654 $authors[] = $new->getUserText( Revision::RAW );
4655 }
4656 return $authors;
4657 }
4658 $dbr = wfGetDB( DB_REPLICA );
4659 $revQuery = Revision::getQueryInfo();
4660 $authors = $dbr->selectFieldValues(
4661 $revQuery['tables'],
4662 $revQuery['fields']['rev_user_text'],
4663 [
4664 'rev_page' => $this->getArticleID(),
4665 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4666 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4667 ], __METHOD__,
4668 [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
4669 $revQuery['joins']
4670 );
4671 return $authors;
4672 }
4673
4674 /**
4675 * Get the number of authors between the given revisions or revision IDs.
4676 * Used for diffs and other things that really need it.
4677 *
4678 * @param int|Revision $old Old revision or rev ID (first before range by default)
4679 * @param int|Revision $new New revision or rev ID (first after range by default)
4680 * @param int $limit Maximum number of authors
4681 * @param string|array $options (Optional): Single option, or an array of options:
4682 * 'include_old' Include $old in the range; $new is excluded.
4683 * 'include_new' Include $new in the range; $old is excluded.
4684 * 'include_both' Include both $old and $new in the range.
4685 * Unknown option values are ignored.
4686 * @return int Number of revision authors in the range; zero if not both revisions exist
4687 */
4688 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4689 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4690 return $authors ? count( $authors ) : 0;
4691 }
4692
4693 /**
4694 * Compare with another title.
4695 *
4696 * @param Title $title
4697 * @return bool
4698 */
4699 public function equals( Title $title ) {
4700 // Note: === is necessary for proper matching of number-like titles.
4701 return $this->mInterwiki === $title->mInterwiki
4702 && $this->mNamespace == $title->mNamespace
4703 && $this->mDbkeyform === $title->mDbkeyform;
4704 }
4705
4706 /**
4707 * Check if this title is a subpage of another title
4708 *
4709 * @param Title $title
4710 * @return bool
4711 */
4712 public function isSubpageOf( Title $title ) {
4713 return $this->mInterwiki === $title->mInterwiki
4714 && $this->mNamespace == $title->mNamespace
4715 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
4716 }
4717
4718 /**
4719 * Check if page exists. For historical reasons, this function simply
4720 * checks for the existence of the title in the page table, and will
4721 * thus return false for interwiki links, special pages and the like.
4722 * If you want to know if a title can be meaningfully viewed, you should
4723 * probably call the isKnown() method instead.
4724 *
4725 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4726 * from master/for update
4727 * @return bool
4728 */
4729 public function exists( $flags = 0 ) {
4730 $exists = $this->getArticleID( $flags ) != 0;
4731 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4732 return $exists;
4733 }
4734
4735 /**
4736 * Should links to this title be shown as potentially viewable (i.e. as
4737 * "bluelinks"), even if there's no record by this title in the page
4738 * table?
4739 *
4740 * This function is semi-deprecated for public use, as well as somewhat
4741 * misleadingly named. You probably just want to call isKnown(), which
4742 * calls this function internally.
4743 *
4744 * (ISSUE: Most of these checks are cheap, but the file existence check
4745 * can potentially be quite expensive. Including it here fixes a lot of
4746 * existing code, but we might want to add an optional parameter to skip
4747 * it and any other expensive checks.)
4748 *
4749 * @return bool
4750 */
4751 public function isAlwaysKnown() {
4752 $isKnown = null;
4753
4754 /**
4755 * Allows overriding default behavior for determining if a page exists.
4756 * If $isKnown is kept as null, regular checks happen. If it's
4757 * a boolean, this value is returned by the isKnown method.
4758 *
4759 * @since 1.20
4760 *
4761 * @param Title $title
4762 * @param bool|null $isKnown
4763 */
4764 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4765
4766 if ( !is_null( $isKnown ) ) {
4767 return $isKnown;
4768 }
4769
4770 if ( $this->isExternal() ) {
4771 return true; // any interwiki link might be viewable, for all we know
4772 }
4773
4774 switch ( $this->mNamespace ) {
4775 case NS_MEDIA:
4776 case NS_FILE:
4777 // file exists, possibly in a foreign repo
4778 return (bool)wfFindFile( $this );
4779 case NS_SPECIAL:
4780 // valid special page
4781 return MediaWikiServices::getInstance()->getSpecialPageFactory()->
4782 exists( $this->mDbkeyform );
4783 case NS_MAIN:
4784 // selflink, possibly with fragment
4785 return $this->mDbkeyform == '';
4786 case NS_MEDIAWIKI:
4787 // known system message
4788 return $this->hasSourceText() !== false;
4789 default:
4790 return false;
4791 }
4792 }
4793
4794 /**
4795 * Does this title refer to a page that can (or might) be meaningfully
4796 * viewed? In particular, this function may be used to determine if
4797 * links to the title should be rendered as "bluelinks" (as opposed to
4798 * "redlinks" to non-existent pages).
4799 * Adding something else to this function will cause inconsistency
4800 * since LinkHolderArray calls isAlwaysKnown() and does its own
4801 * page existence check.
4802 *
4803 * @return bool
4804 */
4805 public function isKnown() {
4806 return $this->isAlwaysKnown() || $this->exists();
4807 }
4808
4809 /**
4810 * Does this page have source text?
4811 *
4812 * @return bool
4813 */
4814 public function hasSourceText() {
4815 if ( $this->exists() ) {
4816 return true;
4817 }
4818
4819 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4820 // If the page doesn't exist but is a known system message, default
4821 // message content will be displayed, same for language subpages-
4822 // Use always content language to avoid loading hundreds of languages
4823 // to get the link color.
4824 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4825 list( $name, ) = MessageCache::singleton()->figureMessage(
4826 $contLang->lcfirst( $this->getText() )
4827 );
4828 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4829 return $message->exists();
4830 }
4831
4832 return false;
4833 }
4834
4835 /**
4836 * Get the default (plain) message contents for an page that overrides an
4837 * interface message key.
4838 *
4839 * Primary use cases:
4840 *
4841 * - Article:
4842 * - Show default when viewing the page. The Article::getSubstituteContent
4843 * method displays the default message content, instead of the
4844 * 'noarticletext' placeholder message normally used.
4845 *
4846 * - EditPage:
4847 * - Title of edit page. When creating an interface message override,
4848 * the editor is told they are "Editing the page", instead of
4849 * "Creating the page". (EditPage::setHeaders)
4850 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4851 * or editing a an interface message override. (EditPage::showIntro)
4852 * - Opening the editor. The contents of the localisation message are used
4853 * as contents of the editor when creating a new page in the MediaWiki
4854 * namespace. This simplifies the process for editors when "changing"
4855 * an interface message by creating an override. (EditPage::getContentObject)
4856 * - Showing a diff. The left-hand side of a diff when an editor is
4857 * previewing their changes before saving the creation of a page in the
4858 * MediaWiki namespace. (EditPage::showDiff)
4859 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4860 * page with the proposed content matching the interface message default,
4861 * the save is rejected, the same way we disallow blank pages from being
4862 * created. (EditPage::internalAttemptSave)
4863 *
4864 * - ApiEditPage:
4865 * - Default content, when using the 'prepend' or 'append' feature.
4866 *
4867 * - SkinTemplate:
4868 * - Label the create action as "Edit", if the page can be an override.
4869 *
4870 * @return string|bool
4871 */
4872 public function getDefaultMessageText() {
4873 if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
4874 return false;
4875 }
4876
4877 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4878 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4879 );
4880 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4881
4882 if ( $message->exists() ) {
4883 return $message->plain();
4884 } else {
4885 return false;
4886 }
4887 }
4888
4889 /**
4890 * Updates page_touched for this page; called from LinksUpdate.php
4891 *
4892 * @param string|null $purgeTime [optional] TS_MW timestamp
4893 * @return bool True if the update succeeded
4894 */
4895 public function invalidateCache( $purgeTime = null ) {
4896 if ( wfReadOnly() ) {
4897 return false;
4898 } elseif ( $this->mArticleID === 0 ) {
4899 return true; // avoid gap locking if we know it's not there
4900 }
4901
4902 $dbw = wfGetDB( DB_MASTER );
4903 $dbw->onTransactionPreCommitOrIdle(
4904 function () use ( $dbw ) {
4905 ResourceLoaderWikiModule::invalidateModuleCache(
4906 $this, null, null, $dbw->getDomainId() );
4907 },
4908 __METHOD__
4909 );
4910
4911 $conds = $this->pageCond();
4912 DeferredUpdates::addUpdate(
4913 new AutoCommitUpdate(
4914 $dbw,
4915 __METHOD__,
4916 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4917 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4918 $dbw->update(
4919 'page',
4920 [ 'page_touched' => $dbTimestamp ],
4921 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4922 $fname
4923 );
4924 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4925 }
4926 ),
4927 DeferredUpdates::PRESEND
4928 );
4929
4930 return true;
4931 }
4932
4933 /**
4934 * Update page_touched timestamps and send CDN purge messages for
4935 * pages linking to this title. May be sent to the job queue depending
4936 * on the number of links. Typically called on create and delete.
4937 */
4938 public function touchLinks() {
4939 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4940 if ( $this->mNamespace == NS_CATEGORY ) {
4941 DeferredUpdates::addUpdate(
4942 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4943 );
4944 }
4945 }
4946
4947 /**
4948 * Get the last touched timestamp
4949 *
4950 * @param IDatabase|null $db
4951 * @return string|false Last-touched timestamp
4952 */
4953 public function getTouched( $db = null ) {
4954 if ( $db === null ) {
4955 $db = wfGetDB( DB_REPLICA );
4956 }
4957 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4958 return $touched;
4959 }
4960
4961 /**
4962 * Get the timestamp when this page was updated since the user last saw it.
4963 *
4964 * @param User|null $user
4965 * @return string|null
4966 */
4967 public function getNotificationTimestamp( $user = null ) {
4968 global $wgUser;
4969
4970 // Assume current user if none given
4971 if ( !$user ) {
4972 $user = $wgUser;
4973 }
4974 // Check cache first
4975 $uid = $user->getId();
4976 if ( !$uid ) {
4977 return false;
4978 }
4979 // avoid isset here, as it'll return false for null entries
4980 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4981 return $this->mNotificationTimestamp[$uid];
4982 }
4983 // Don't cache too much!
4984 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4985 $this->mNotificationTimestamp = [];
4986 }
4987
4988 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4989 $watchedItem = $store->getWatchedItem( $user, $this );
4990 if ( $watchedItem ) {
4991 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4992 } else {
4993 $this->mNotificationTimestamp[$uid] = false;
4994 }
4995
4996 return $this->mNotificationTimestamp[$uid];
4997 }
4998
4999 /**
5000 * Generate strings used for xml 'id' names in monobook tabs
5001 *
5002 * @param string $prepend Defaults to 'nstab-'
5003 * @return string XML 'id' name
5004 */
5005 public function getNamespaceKey( $prepend = 'nstab-' ) {
5006 // Gets the subject namespace of this title
5007 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
5008 // Prefer canonical namespace name for HTML IDs
5009 $namespaceKey = MWNamespace::getCanonicalName( $subjectNS );
5010 if ( $namespaceKey === false ) {
5011 // Fallback to localised text
5012 $namespaceKey = $this->getSubjectNsText();
5013 }
5014 // Makes namespace key lowercase
5015 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
5016 // Uses main
5017 if ( $namespaceKey == '' ) {
5018 $namespaceKey = 'main';
5019 }
5020 // Changes file to image for backwards compatibility
5021 if ( $namespaceKey == 'file' ) {
5022 $namespaceKey = 'image';
5023 }
5024 return $prepend . $namespaceKey;
5025 }
5026
5027 /**
5028 * Get all extant redirects to this Title
5029 *
5030 * @param int|null $ns Single namespace to consider; null to consider all namespaces
5031 * @return Title[] Array of Title redirects to this title
5032 */
5033 public function getRedirectsHere( $ns = null ) {
5034 $redirs = [];
5035
5036 $dbr = wfGetDB( DB_REPLICA );
5037 $where = [
5038 'rd_namespace' => $this->mNamespace,
5039 'rd_title' => $this->mDbkeyform,
5040 'rd_from = page_id'
5041 ];
5042 if ( $this->isExternal() ) {
5043 $where['rd_interwiki'] = $this->mInterwiki;
5044 } else {
5045 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
5046 }
5047 if ( !is_null( $ns ) ) {
5048 $where['page_namespace'] = $ns;
5049 }
5050
5051 $res = $dbr->select(
5052 [ 'redirect', 'page' ],
5053 [ 'page_namespace', 'page_title' ],
5054 $where,
5055 __METHOD__
5056 );
5057
5058 foreach ( $res as $row ) {
5059 $redirs[] = self::newFromRow( $row );
5060 }
5061 return $redirs;
5062 }
5063
5064 /**
5065 * Check if this Title is a valid redirect target
5066 *
5067 * @return bool
5068 */
5069 public function isValidRedirectTarget() {
5070 global $wgInvalidRedirectTargets;
5071
5072 if ( $this->isSpecialPage() ) {
5073 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5074 if ( $this->isSpecial( 'Userlogout' ) ) {
5075 return false;
5076 }
5077
5078 foreach ( $wgInvalidRedirectTargets as $target ) {
5079 if ( $this->isSpecial( $target ) ) {
5080 return false;
5081 }
5082 }
5083 }
5084
5085 return true;
5086 }
5087
5088 /**
5089 * Get a backlink cache object
5090 *
5091 * @return BacklinkCache
5092 */
5093 public function getBacklinkCache() {
5094 return BacklinkCache::get( $this );
5095 }
5096
5097 /**
5098 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5099 *
5100 * @return bool
5101 */
5102 public function canUseNoindex() {
5103 global $wgExemptFromUserRobotsControl;
5104
5105 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
5106 ? MWNamespace::getContentNamespaces()
5107 : $wgExemptFromUserRobotsControl;
5108
5109 return !in_array( $this->mNamespace, $bannedNamespaces );
5110 }
5111
5112 /**
5113 * Returns the raw sort key to be used for categories, with the specified
5114 * prefix. This will be fed to Collation::getSortKey() to get a
5115 * binary sortkey that can be used for actual sorting.
5116 *
5117 * @param string $prefix The prefix to be used, specified using
5118 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5119 * prefix.
5120 * @return string
5121 */
5122 public function getCategorySortkey( $prefix = '' ) {
5123 $unprefixed = $this->getText();
5124
5125 // Anything that uses this hook should only depend
5126 // on the Title object passed in, and should probably
5127 // tell the users to run updateCollations.php --force
5128 // in order to re-sort existing category relations.
5129 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5130 if ( $prefix !== '' ) {
5131 # Separate with a line feed, so the unprefixed part is only used as
5132 # a tiebreaker when two pages have the exact same prefix.
5133 # In UCA, tab is the only character that can sort above LF
5134 # so we strip both of them from the original prefix.
5135 $prefix = strtr( $prefix, "\n\t", ' ' );
5136 return "$prefix\n$unprefixed";
5137 }
5138 return $unprefixed;
5139 }
5140
5141 /**
5142 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5143 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5144 * the db, it will return NULL.
5145 *
5146 * @return string|null|bool
5147 */
5148 private function getDbPageLanguageCode() {
5149 global $wgPageLanguageUseDB;
5150
5151 // check, if the page language could be saved in the database, and if so and
5152 // the value is not requested already, lookup the page language using LinkCache
5153 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
5154 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
5155 $linkCache->addLinkObj( $this );
5156 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5157 }
5158
5159 return $this->mDbPageLanguage;
5160 }
5161
5162 /**
5163 * Get the language in which the content of this page is written in
5164 * wikitext. Defaults to content language, but in certain cases it can be
5165 * e.g. $wgLang (such as special pages, which are in the user language).
5166 *
5167 * @since 1.18
5168 * @return Language
5169 */
5170 public function getPageLanguage() {
5171 global $wgLang, $wgLanguageCode;
5172 if ( $this->isSpecialPage() ) {
5173 // special pages are in the user language
5174 return $wgLang;
5175 }
5176
5177 // Checking if DB language is set
5178 $dbPageLanguage = $this->getDbPageLanguageCode();
5179 if ( $dbPageLanguage ) {
5180 return wfGetLangObj( $dbPageLanguage );
5181 }
5182
5183 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
5184 // Note that this may depend on user settings, so the cache should
5185 // be only per-request.
5186 // NOTE: ContentHandler::getPageLanguage() may need to load the
5187 // content to determine the page language!
5188 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5189 // tests.
5190 $contentHandler = ContentHandler::getForTitle( $this );
5191 $langObj = $contentHandler->getPageLanguage( $this );
5192 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
5193 } else {
5194 $langObj = Language::factory( $this->mPageLanguage[0] );
5195 }
5196
5197 return $langObj;
5198 }
5199
5200 /**
5201 * Get the language in which the content of this page is written when
5202 * viewed by user. Defaults to content language, but in certain cases it can be
5203 * e.g. $wgLang (such as special pages, which are in the user language).
5204 *
5205 * @since 1.20
5206 * @return Language
5207 */
5208 public function getPageViewLanguage() {
5209 global $wgLang;
5210
5211 if ( $this->isSpecialPage() ) {
5212 // If the user chooses a variant, the content is actually
5213 // in a language whose code is the variant code.
5214 $variant = $wgLang->getPreferredVariant();
5215 if ( $wgLang->getCode() !== $variant ) {
5216 return Language::factory( $variant );
5217 }
5218
5219 return $wgLang;
5220 }
5221
5222 // Checking if DB language is set
5223 $dbPageLanguage = $this->getDbPageLanguageCode();
5224 if ( $dbPageLanguage ) {
5225 $pageLang = wfGetLangObj( $dbPageLanguage );
5226 $variant = $pageLang->getPreferredVariant();
5227 if ( $pageLang->getCode() !== $variant ) {
5228 $pageLang = Language::factory( $variant );
5229 }
5230
5231 return $pageLang;
5232 }
5233
5234 // @note Can't be cached persistently, depends on user settings.
5235 // @note ContentHandler::getPageViewLanguage() may need to load the
5236 // content to determine the page language!
5237 $contentHandler = ContentHandler::getForTitle( $this );
5238 $pageLang = $contentHandler->getPageViewLanguage( $this );
5239 return $pageLang;
5240 }
5241
5242 /**
5243 * Get a list of rendered edit notices for this page.
5244 *
5245 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5246 * they will already be wrapped in paragraphs.
5247 *
5248 * @since 1.21
5249 * @param int $oldid Revision ID that's being edited
5250 * @return array
5251 */
5252 public function getEditNotices( $oldid = 0 ) {
5253 $notices = [];
5254
5255 // Optional notice for the entire namespace
5256 $editnotice_ns = 'editnotice-' . $this->mNamespace;
5257 $msg = wfMessage( $editnotice_ns );
5258 if ( $msg->exists() ) {
5259 $html = $msg->parseAsBlock();
5260 // Edit notices may have complex logic, but output nothing (T91715)
5261 if ( trim( $html ) !== '' ) {
5262 $notices[$editnotice_ns] = Html::rawElement(
5263 'div',
5264 [ 'class' => [
5265 'mw-editnotice',
5266 'mw-editnotice-namespace',
5267 Sanitizer::escapeClass( "mw-$editnotice_ns" )
5268 ] ],
5269 $html
5270 );
5271 }
5272 }
5273
5274 if ( MWNamespace::hasSubpages( $this->mNamespace ) ) {
5275 // Optional notice for page itself and any parent page
5276 $editnotice_base = $editnotice_ns;
5277 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
5278 $editnotice_base .= '-' . $part;
5279 $msg = wfMessage( $editnotice_base );
5280 if ( $msg->exists() ) {
5281 $html = $msg->parseAsBlock();
5282 if ( trim( $html ) !== '' ) {
5283 $notices[$editnotice_base] = Html::rawElement(
5284 'div',
5285 [ 'class' => [
5286 'mw-editnotice',
5287 'mw-editnotice-base',
5288 Sanitizer::escapeClass( "mw-$editnotice_base" )
5289 ] ],
5290 $html
5291 );
5292 }
5293 }
5294 }
5295 } else {
5296 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5297 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
5298 $msg = wfMessage( $editnoticeText );
5299 if ( $msg->exists() ) {
5300 $html = $msg->parseAsBlock();
5301 if ( trim( $html ) !== '' ) {
5302 $notices[$editnoticeText] = Html::rawElement(
5303 'div',
5304 [ 'class' => [
5305 'mw-editnotice',
5306 'mw-editnotice-page',
5307 Sanitizer::escapeClass( "mw-$editnoticeText" )
5308 ] ],
5309 $html
5310 );
5311 }
5312 }
5313 }
5314
5315 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5316 return $notices;
5317 }
5318
5319 /**
5320 * @return array
5321 */
5322 public function __sleep() {
5323 return [
5324 'mNamespace',
5325 'mDbkeyform',
5326 'mFragment',
5327 'mInterwiki',
5328 'mLocalInterwiki',
5329 'mUserCaseDBKey',
5330 'mDefaultNamespace',
5331 ];
5332 }
5333
5334 public function __wakeup() {
5335 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
5336 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
5337 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
5338 }
5339
5340 }