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