Merge "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 } elseif ( $this->mArticleID == -1 ) {
3591 $this->mArticleID = $linkCache->addLinkObj( $this );
3592 }
3593 return $this->mArticleID;
3594 }
3595
3596 /**
3597 * Is this an article that is a redirect page?
3598 * Uses link cache, adding it if necessary
3599 *
3600 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3601 * @return bool
3602 */
3603 public function isRedirect( $flags = 0 ) {
3604 if ( !is_null( $this->mRedirect ) ) {
3605 return $this->mRedirect;
3606 }
3607 if ( !$this->getArticleID( $flags ) ) {
3608 $this->mRedirect = false;
3609 return $this->mRedirect;
3610 }
3611
3612 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3613 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3614 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3615 if ( $cached === null ) {
3616 # Trust LinkCache's state over our own
3617 # LinkCache is telling us that the page doesn't exist, despite there being cached
3618 # data relating to an existing page in $this->mArticleID. Updaters should clear
3619 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3620 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3621 # LinkCache to refresh its data from the master.
3622 $this->mRedirect = false;
3623 return $this->mRedirect;
3624 }
3625
3626 $this->mRedirect = (bool)$cached;
3627
3628 return $this->mRedirect;
3629 }
3630
3631 /**
3632 * What is the length of this page?
3633 * Uses link cache, adding it if necessary
3634 *
3635 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3636 * @return int
3637 */
3638 public function getLength( $flags = 0 ) {
3639 if ( $this->mLength != -1 ) {
3640 return $this->mLength;
3641 }
3642 if ( !$this->getArticleID( $flags ) ) {
3643 $this->mLength = 0;
3644 return $this->mLength;
3645 }
3646 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3647 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3648 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3649 if ( $cached === null ) {
3650 # Trust LinkCache's state over our own, as for isRedirect()
3651 $this->mLength = 0;
3652 return $this->mLength;
3653 }
3654
3655 $this->mLength = intval( $cached );
3656
3657 return $this->mLength;
3658 }
3659
3660 /**
3661 * What is the page_latest field for this page?
3662 *
3663 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3664 * @return int Int or 0 if the page doesn't exist
3665 */
3666 public function getLatestRevID( $flags = 0 ) {
3667 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3668 return intval( $this->mLatestID );
3669 }
3670 if ( !$this->getArticleID( $flags ) ) {
3671 $this->mLatestID = 0;
3672 return $this->mLatestID;
3673 }
3674 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3675 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3676 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3677 if ( $cached === null ) {
3678 # Trust LinkCache's state over our own, as for isRedirect()
3679 $this->mLatestID = 0;
3680 return $this->mLatestID;
3681 }
3682
3683 $this->mLatestID = intval( $cached );
3684
3685 return $this->mLatestID;
3686 }
3687
3688 /**
3689 * This clears some fields in this object, and clears any associated
3690 * keys in the "bad links" section of the link cache.
3691 *
3692 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3693 * loading of the new page_id. It's also called from
3694 * WikiPage::doDeleteArticleReal()
3695 *
3696 * @param int $newid The new Article ID
3697 */
3698 public function resetArticleID( $newid ) {
3699 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3700 $linkCache->clearLink( $this );
3701
3702 if ( $newid === false ) {
3703 $this->mArticleID = -1;
3704 } else {
3705 $this->mArticleID = intval( $newid );
3706 }
3707 $this->mRestrictionsLoaded = false;
3708 $this->mRestrictions = [];
3709 $this->mOldRestrictions = false;
3710 $this->mRedirect = null;
3711 $this->mLength = -1;
3712 $this->mLatestID = false;
3713 $this->mContentModel = false;
3714 $this->mEstimateRevisions = null;
3715 $this->mPageLanguage = false;
3716 $this->mDbPageLanguage = false;
3717 $this->mIsBigDeletion = null;
3718 }
3719
3720 public static function clearCaches() {
3721 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3722 $linkCache->clear();
3723
3724 $titleCache = self::getTitleCache();
3725 $titleCache->clear();
3726 }
3727
3728 /**
3729 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3730 *
3731 * @param string $text Containing title to capitalize
3732 * @param int $ns Namespace index, defaults to NS_MAIN
3733 * @return string Containing capitalized title
3734 */
3735 public static function capitalize( $text, $ns = NS_MAIN ) {
3736 if ( MWNamespace::isCapitalized( $ns ) ) {
3737 return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text );
3738 } else {
3739 return $text;
3740 }
3741 }
3742
3743 /**
3744 * Secure and split - main initialisation function for this object
3745 *
3746 * Assumes that mDbkeyform has been set, and is urldecoded
3747 * and uses underscores, but not otherwise munged. This function
3748 * removes illegal characters, splits off the interwiki and
3749 * namespace prefixes, sets the other forms, and canonicalizes
3750 * everything.
3751 *
3752 * @throws MalformedTitleException On invalid titles
3753 * @return bool True on success
3754 */
3755 private function secureAndSplit() {
3756 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3757 // the parsing code with Title, while avoiding massive refactoring.
3758 // @todo: get rid of secureAndSplit, refactor parsing code.
3759 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3760 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3761 /** @var MediaWikiTitleCodec $titleCodec */
3762 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3763 // MalformedTitleException can be thrown here
3764 $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
3765
3766 # Fill fields
3767 $this->setFragment( '#' . $parts['fragment'] );
3768 $this->mInterwiki = $parts['interwiki'];
3769 $this->mLocalInterwiki = $parts['local_interwiki'];
3770 $this->mNamespace = $parts['namespace'];
3771 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3772
3773 $this->mDbkeyform = $parts['dbkey'];
3774 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3775 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3776
3777 # We already know that some pages won't be in the database!
3778 if ( $this->isExternal() || $this->isSpecialPage() ) {
3779 $this->mArticleID = 0;
3780 }
3781
3782 return true;
3783 }
3784
3785 /**
3786 * Get an array of Title objects linking to this Title
3787 * Also stores the IDs in the link cache.
3788 *
3789 * WARNING: do not use this function on arbitrary user-supplied titles!
3790 * On heavily-used templates it will max out the memory.
3791 *
3792 * @param array $options May be FOR UPDATE
3793 * @param string $table Table name
3794 * @param string $prefix Fields prefix
3795 * @return Title[] Array of Title objects linking here
3796 */
3797 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3798 if ( count( $options ) > 0 ) {
3799 $db = wfGetDB( DB_MASTER );
3800 } else {
3801 $db = wfGetDB( DB_REPLICA );
3802 }
3803
3804 $res = $db->select(
3805 [ 'page', $table ],
3806 self::getSelectFields(),
3807 [
3808 "{$prefix}_from=page_id",
3809 "{$prefix}_namespace" => $this->mNamespace,
3810 "{$prefix}_title" => $this->mDbkeyform ],
3811 __METHOD__,
3812 $options
3813 );
3814
3815 $retVal = [];
3816 if ( $res->numRows() ) {
3817 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3818 foreach ( $res as $row ) {
3819 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3820 if ( $titleObj ) {
3821 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3822 $retVal[] = $titleObj;
3823 }
3824 }
3825 }
3826 return $retVal;
3827 }
3828
3829 /**
3830 * Get an array of Title objects using this Title as a template
3831 * Also stores the IDs in the link cache.
3832 *
3833 * WARNING: do not use this function on arbitrary user-supplied titles!
3834 * On heavily-used templates it will max out the memory.
3835 *
3836 * @param array $options Query option to Database::select()
3837 * @return Title[] Array of Title the Title objects linking here
3838 */
3839 public function getTemplateLinksTo( $options = [] ) {
3840 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3841 }
3842
3843 /**
3844 * Get an array of Title objects linked from this Title
3845 * Also stores the IDs in the link cache.
3846 *
3847 * WARNING: do not use this function on arbitrary user-supplied titles!
3848 * On heavily-used templates it will max out the memory.
3849 *
3850 * @param array $options Query option to Database::select()
3851 * @param string $table Table name
3852 * @param string $prefix Fields prefix
3853 * @return array Array of Title objects linking here
3854 */
3855 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3856 $id = $this->getArticleID();
3857
3858 # If the page doesn't exist; there can't be any link from this page
3859 if ( !$id ) {
3860 return [];
3861 }
3862
3863 $db = wfGetDB( DB_REPLICA );
3864
3865 $blNamespace = "{$prefix}_namespace";
3866 $blTitle = "{$prefix}_title";
3867
3868 $pageQuery = WikiPage::getQueryInfo();
3869 $res = $db->select(
3870 [ $table, 'nestpage' => $pageQuery['tables'] ],
3871 array_merge(
3872 [ $blNamespace, $blTitle ],
3873 $pageQuery['fields']
3874 ),
3875 [ "{$prefix}_from" => $id ],
3876 __METHOD__,
3877 $options,
3878 [ 'nestpage' => [
3879 'LEFT JOIN',
3880 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3881 ] ] + $pageQuery['joins']
3882 );
3883
3884 $retVal = [];
3885 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3886 foreach ( $res as $row ) {
3887 if ( $row->page_id ) {
3888 $titleObj = self::newFromRow( $row );
3889 } else {
3890 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3891 $linkCache->addBadLinkObj( $titleObj );
3892 }
3893 $retVal[] = $titleObj;
3894 }
3895
3896 return $retVal;
3897 }
3898
3899 /**
3900 * Get an array of Title objects used on this Title as a template
3901 * Also stores the IDs in the link cache.
3902 *
3903 * WARNING: do not use this function on arbitrary user-supplied titles!
3904 * On heavily-used templates it will max out the memory.
3905 *
3906 * @param array $options May be FOR UPDATE
3907 * @return Title[] Array of Title the Title objects used here
3908 */
3909 public function getTemplateLinksFrom( $options = [] ) {
3910 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3911 }
3912
3913 /**
3914 * Get an array of Title objects referring to non-existent articles linked
3915 * from this page.
3916 *
3917 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3918 * should use redirect table in this case).
3919 * @return Title[] Array of Title the Title objects
3920 */
3921 public function getBrokenLinksFrom() {
3922 if ( $this->getArticleID() == 0 ) {
3923 # All links from article ID 0 are false positives
3924 return [];
3925 }
3926
3927 $dbr = wfGetDB( DB_REPLICA );
3928 $res = $dbr->select(
3929 [ 'page', 'pagelinks' ],
3930 [ 'pl_namespace', 'pl_title' ],
3931 [
3932 'pl_from' => $this->getArticleID(),
3933 'page_namespace IS NULL'
3934 ],
3935 __METHOD__, [],
3936 [
3937 'page' => [
3938 'LEFT JOIN',
3939 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3940 ]
3941 ]
3942 );
3943
3944 $retVal = [];
3945 foreach ( $res as $row ) {
3946 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3947 }
3948 return $retVal;
3949 }
3950
3951 /**
3952 * Get a list of URLs to purge from the CDN cache when this
3953 * page changes
3954 *
3955 * @return string[] Array of String the URLs
3956 */
3957 public function getCdnUrls() {
3958 $urls = [
3959 $this->getInternalURL(),
3960 $this->getInternalURL( 'action=history' )
3961 ];
3962
3963 $pageLang = $this->getPageLanguage();
3964 if ( $pageLang->hasVariants() ) {
3965 $variants = $pageLang->getVariants();
3966 foreach ( $variants as $vCode ) {
3967 $urls[] = $this->getInternalURL( $vCode );
3968 }
3969 }
3970
3971 // If we are looking at a css/js user subpage, purge the action=raw.
3972 if ( $this->isUserJsConfigPage() ) {
3973 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3974 } elseif ( $this->isUserJsonConfigPage() ) {
3975 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3976 } elseif ( $this->isUserCssConfigPage() ) {
3977 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3978 }
3979
3980 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3981 return $urls;
3982 }
3983
3984 /**
3985 * Purge all applicable CDN URLs
3986 */
3987 public function purgeSquid() {
3988 DeferredUpdates::addUpdate(
3989 new CdnCacheUpdate( $this->getCdnUrls() ),
3990 DeferredUpdates::PRESEND
3991 );
3992 }
3993
3994 /**
3995 * Check whether a given move operation would be valid.
3996 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3997 *
3998 * @deprecated since 1.25, use MovePage's methods instead
3999 * @param Title &$nt The new title
4000 * @param bool $auth Whether to check user permissions (uses $wgUser)
4001 * @param string $reason Is the log summary of the move, used for spam checking
4002 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4003 */
4004 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4005 global $wgUser;
4006
4007 if ( !( $nt instanceof Title ) ) {
4008 // Normally we'd add this to $errors, but we'll get
4009 // lots of syntax errors if $nt is not an object
4010 return [ [ 'badtitletext' ] ];
4011 }
4012
4013 $mp = new MovePage( $this, $nt );
4014 $errors = $mp->isValidMove()->getErrorsArray();
4015 if ( $auth ) {
4016 $errors = wfMergeErrorArrays(
4017 $errors,
4018 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4019 );
4020 }
4021
4022 return $errors ?: true;
4023 }
4024
4025 /**
4026 * Move a title to a new location
4027 *
4028 * @deprecated since 1.25, use the MovePage class instead
4029 * @param Title &$nt The new title
4030 * @param bool $auth Indicates whether $wgUser's permissions
4031 * should be checked
4032 * @param string $reason The reason for the move
4033 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4034 * Ignored if the user doesn't have the suppressredirect right.
4035 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4036 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4037 */
4038 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4039 array $changeTags = []
4040 ) {
4041 global $wgUser;
4042 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4043 if ( is_array( $err ) ) {
4044 // Auto-block user's IP if the account was "hard" blocked
4045 $wgUser->spreadAnyEditBlock();
4046 return $err;
4047 }
4048 // Check suppressredirect permission
4049 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4050 $createRedirect = true;
4051 }
4052
4053 $mp = new MovePage( $this, $nt );
4054 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4055 if ( $status->isOK() ) {
4056 return true;
4057 } else {
4058 return $status->getErrorsArray();
4059 }
4060 }
4061
4062 /**
4063 * Move this page's subpages to be subpages of $nt
4064 *
4065 * @param Title $nt Move target
4066 * @param bool $auth Whether $wgUser's permissions should be checked
4067 * @param string $reason The reason for the move
4068 * @param bool $createRedirect Whether to create redirects from the old subpages to
4069 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4070 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4071 * @return array Array with old page titles as keys, and strings (new page titles) or
4072 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4073 * getUserPermissionsErrors()-like error array with numeric indices if
4074 * no pages were moved
4075 */
4076 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4077 array $changeTags = []
4078 ) {
4079 global $wgMaximumMovedPages;
4080 // Check permissions
4081 if ( !$this->userCan( 'move-subpages' ) ) {
4082 return [
4083 [ 'cant-move-subpages' ],
4084 ];
4085 }
4086 // Do the source and target namespaces support subpages?
4087 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
4088 return [
4089 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->mNamespace ) ],
4090 ];
4091 }
4092 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
4093 return [
4094 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
4095 ];
4096 }
4097
4098 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
4099 $retval = [];
4100 $count = 0;
4101 foreach ( $subpages as $oldSubpage ) {
4102 $count++;
4103 if ( $count > $wgMaximumMovedPages ) {
4104 $retval[$oldSubpage->getPrefixedText()] = [
4105 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4106 ];
4107 break;
4108 }
4109
4110 // We don't know whether this function was called before
4111 // or after moving the root page, so check both
4112 // $this and $nt
4113 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4114 || $oldSubpage->getArticleID() == $nt->getArticleID()
4115 ) {
4116 // When moving a page to a subpage of itself,
4117 // don't move it twice
4118 continue;
4119 }
4120 $newPageName = preg_replace(
4121 '#^' . preg_quote( $this->mDbkeyform, '#' ) . '#',
4122 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4123 $oldSubpage->getDBkey() );
4124 if ( $oldSubpage->isTalkPage() ) {
4125 $newNs = $nt->getTalkPage()->getNamespace();
4126 } else {
4127 $newNs = $nt->getSubjectPage()->getNamespace();
4128 }
4129 # T16385: we need makeTitleSafe because the new page names may
4130 # be longer than 255 characters.
4131 $newSubpage = self::makeTitleSafe( $newNs, $newPageName );
4132
4133 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4134 if ( $success === true ) {
4135 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4136 } else {
4137 $retval[$oldSubpage->getPrefixedText()] = $success;
4138 }
4139 }
4140 return $retval;
4141 }
4142
4143 /**
4144 * Checks if this page is just a one-rev redirect.
4145 * Adds lock, so don't use just for light purposes.
4146 *
4147 * @return bool
4148 */
4149 public function isSingleRevRedirect() {
4150 global $wgContentHandlerUseDB;
4151
4152 $dbw = wfGetDB( DB_MASTER );
4153
4154 # Is it a redirect?
4155 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4156 if ( $wgContentHandlerUseDB ) {
4157 $fields[] = 'page_content_model';
4158 }
4159
4160 $row = $dbw->selectRow( 'page',
4161 $fields,
4162 $this->pageCond(),
4163 __METHOD__,
4164 [ 'FOR UPDATE' ]
4165 );
4166 # Cache some fields we may want
4167 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4168 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4169 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4170 $this->mContentModel = $row && isset( $row->page_content_model )
4171 ? strval( $row->page_content_model )
4172 : false;
4173
4174 if ( !$this->mRedirect ) {
4175 return false;
4176 }
4177 # Does the article have a history?
4178 $row = $dbw->selectField( [ 'page', 'revision' ],
4179 'rev_id',
4180 [ 'page_namespace' => $this->mNamespace,
4181 'page_title' => $this->mDbkeyform,
4182 'page_id=rev_page',
4183 'page_latest != rev_id'
4184 ],
4185 __METHOD__,
4186 [ 'FOR UPDATE' ]
4187 );
4188 # Return true if there was no history
4189 return ( $row === false );
4190 }
4191
4192 /**
4193 * Checks if $this can be moved to a given Title
4194 * - Selects for update, so don't call it unless you mean business
4195 *
4196 * @deprecated since 1.25, use MovePage's methods instead
4197 * @param Title $nt The new title to check
4198 * @return bool
4199 */
4200 public function isValidMoveTarget( $nt ) {
4201 # Is it an existing file?
4202 if ( $nt->getNamespace() == NS_FILE ) {
4203 $file = wfLocalFile( $nt );
4204 $file->load( File::READ_LATEST );
4205 if ( $file->exists() ) {
4206 wfDebug( __METHOD__ . ": file exists\n" );
4207 return false;
4208 }
4209 }
4210 # Is it a redirect with no history?
4211 if ( !$nt->isSingleRevRedirect() ) {
4212 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4213 return false;
4214 }
4215 # Get the article text
4216 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4217 if ( !is_object( $rev ) ) {
4218 return false;
4219 }
4220 $content = $rev->getContent();
4221 # Does the redirect point to the source?
4222 # Or is it a broken self-redirect, usually caused by namespace collisions?
4223 $redirTitle = $content ? $content->getRedirectTarget() : null;
4224
4225 if ( $redirTitle ) {
4226 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4227 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4228 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4229 return false;
4230 } else {
4231 return true;
4232 }
4233 } else {
4234 # Fail safe (not a redirect after all. strange.)
4235 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4236 " is a redirect, but it doesn't contain a valid redirect.\n" );
4237 return false;
4238 }
4239 }
4240
4241 /**
4242 * Get categories to which this Title belongs and return an array of
4243 * categories' names.
4244 *
4245 * @return array Array of parents in the form:
4246 * $parent => $currentarticle
4247 */
4248 public function getParentCategories() {
4249 $data = [];
4250
4251 $titleKey = $this->getArticleID();
4252
4253 if ( $titleKey === 0 ) {
4254 return $data;
4255 }
4256
4257 $dbr = wfGetDB( DB_REPLICA );
4258
4259 $res = $dbr->select(
4260 'categorylinks',
4261 'cl_to',
4262 [ 'cl_from' => $titleKey ],
4263 __METHOD__
4264 );
4265
4266 if ( $res->numRows() > 0 ) {
4267 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4268 foreach ( $res as $row ) {
4269 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4270 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
4271 $this->getFullText();
4272 }
4273 }
4274 return $data;
4275 }
4276
4277 /**
4278 * Get a tree of parent categories
4279 *
4280 * @param array $children Array with the children in the keys, to check for circular refs
4281 * @return array Tree of parent categories
4282 */
4283 public function getParentCategoryTree( $children = [] ) {
4284 $stack = [];
4285 $parents = $this->getParentCategories();
4286
4287 if ( $parents ) {
4288 foreach ( $parents as $parent => $current ) {
4289 if ( array_key_exists( $parent, $children ) ) {
4290 # Circular reference
4291 $stack[$parent] = [];
4292 } else {
4293 $nt = self::newFromText( $parent );
4294 if ( $nt ) {
4295 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
4296 }
4297 }
4298 }
4299 }
4300
4301 return $stack;
4302 }
4303
4304 /**
4305 * Get an associative array for selecting this title from
4306 * the "page" table
4307 *
4308 * @return array Array suitable for the $where parameter of DB::select()
4309 */
4310 public function pageCond() {
4311 if ( $this->mArticleID > 0 ) {
4312 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4313 return [ 'page_id' => $this->mArticleID ];
4314 } else {
4315 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
4316 }
4317 }
4318
4319 /**
4320 * Get next/previous revision ID relative to another revision ID
4321 * @param int $revId Revision ID. Get the revision that was before this one.
4322 * @param int $flags Title::GAID_FOR_UPDATE
4323 * @param string $dir 'next' or 'prev'
4324 * @return int|bool New revision ID, or false if none exists
4325 */
4326 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4327 $revId = (int)$revId;
4328 if ( $dir === 'next' ) {
4329 $op = '>';
4330 $sort = 'ASC';
4331 } elseif ( $dir === 'prev' ) {
4332 $op = '<';
4333 $sort = 'DESC';
4334 } else {
4335 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4336 }
4337
4338 if ( $flags & self::GAID_FOR_UPDATE ) {
4339 $db = wfGetDB( DB_MASTER );
4340 } else {
4341 $db = wfGetDB( DB_REPLICA, 'contributions' );
4342 }
4343
4344 // Intentionally not caring if the specified revision belongs to this
4345 // page. We only care about the timestamp.
4346 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ );
4347 if ( $ts === false ) {
4348 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ );
4349 if ( $ts === false ) {
4350 // Or should this throw an InvalidArgumentException or something?
4351 return false;
4352 }
4353 }
4354 $ts = $db->addQuotes( $ts );
4355
4356 $revId = $db->selectField( 'revision', 'rev_id',
4357 [
4358 'rev_page' => $this->getArticleID( $flags ),
4359 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4360 ],
4361 __METHOD__,
4362 [
4363 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4364 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4365 ]
4366 );
4367
4368 if ( $revId === false ) {
4369 return false;
4370 } else {
4371 return intval( $revId );
4372 }
4373 }
4374
4375 /**
4376 * Get the revision ID of the previous revision
4377 *
4378 * @param int $revId Revision ID. Get the revision that was before this one.
4379 * @param int $flags Title::GAID_FOR_UPDATE
4380 * @return int|bool Old revision ID, or false if none exists
4381 */
4382 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4383 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4384 }
4385
4386 /**
4387 * Get the revision ID of the next revision
4388 *
4389 * @param int $revId Revision ID. Get the revision that was after this one.
4390 * @param int $flags Title::GAID_FOR_UPDATE
4391 * @return int|bool Next revision ID, or false if none exists
4392 */
4393 public function getNextRevisionID( $revId, $flags = 0 ) {
4394 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4395 }
4396
4397 /**
4398 * Get the first revision of the page
4399 *
4400 * @param int $flags Title::GAID_FOR_UPDATE
4401 * @return Revision|null If page doesn't exist
4402 */
4403 public function getFirstRevision( $flags = 0 ) {
4404 $pageId = $this->getArticleID( $flags );
4405 if ( $pageId ) {
4406 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4407 $revQuery = Revision::getQueryInfo();
4408 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4409 [ 'rev_page' => $pageId ],
4410 __METHOD__,
4411 [
4412 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4413 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4414 ],
4415 $revQuery['joins']
4416 );
4417 if ( $row ) {
4418 return new Revision( $row, 0, $this );
4419 }
4420 }
4421 return null;
4422 }
4423
4424 /**
4425 * Get the oldest revision timestamp of this page
4426 *
4427 * @param int $flags Title::GAID_FOR_UPDATE
4428 * @return string|null MW timestamp
4429 */
4430 public function getEarliestRevTime( $flags = 0 ) {
4431 $rev = $this->getFirstRevision( $flags );
4432 return $rev ? $rev->getTimestamp() : null;
4433 }
4434
4435 /**
4436 * Check if this is a new page
4437 *
4438 * @return bool
4439 */
4440 public function isNewPage() {
4441 $dbr = wfGetDB( DB_REPLICA );
4442 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4443 }
4444
4445 /**
4446 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4447 *
4448 * @return bool
4449 */
4450 public function isBigDeletion() {
4451 global $wgDeleteRevisionsLimit;
4452
4453 if ( !$wgDeleteRevisionsLimit ) {
4454 return false;
4455 }
4456
4457 if ( $this->mIsBigDeletion === null ) {
4458 $dbr = wfGetDB( DB_REPLICA );
4459
4460 $revCount = $dbr->selectRowCount(
4461 'revision',
4462 '1',
4463 [ 'rev_page' => $this->getArticleID() ],
4464 __METHOD__,
4465 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4466 );
4467
4468 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4469 }
4470
4471 return $this->mIsBigDeletion;
4472 }
4473
4474 /**
4475 * Get the approximate revision count of this page.
4476 *
4477 * @return int
4478 */
4479 public function estimateRevisionCount() {
4480 if ( !$this->exists() ) {
4481 return 0;
4482 }
4483
4484 if ( $this->mEstimateRevisions === null ) {
4485 $dbr = wfGetDB( DB_REPLICA );
4486 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4487 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4488 }
4489
4490 return $this->mEstimateRevisions;
4491 }
4492
4493 /**
4494 * Get the number of revisions between the given revision.
4495 * Used for diffs and other things that really need it.
4496 *
4497 * @param int|Revision $old Old revision or rev ID (first before range)
4498 * @param int|Revision $new New revision or rev ID (first after range)
4499 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4500 * @return int Number of revisions between these revisions.
4501 */
4502 public function countRevisionsBetween( $old, $new, $max = null ) {
4503 if ( !( $old instanceof Revision ) ) {
4504 $old = Revision::newFromTitle( $this, (int)$old );
4505 }
4506 if ( !( $new instanceof Revision ) ) {
4507 $new = Revision::newFromTitle( $this, (int)$new );
4508 }
4509 if ( !$old || !$new ) {
4510 return 0; // nothing to compare
4511 }
4512 $dbr = wfGetDB( DB_REPLICA );
4513 $conds = [
4514 'rev_page' => $this->getArticleID(),
4515 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4516 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4517 ];
4518 if ( $max !== null ) {
4519 return $dbr->selectRowCount( 'revision', '1',
4520 $conds,
4521 __METHOD__,
4522 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4523 );
4524 } else {
4525 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4526 }
4527 }
4528
4529 /**
4530 * Get the authors between the given revisions or revision IDs.
4531 * Used for diffs and other things that really need it.
4532 *
4533 * @since 1.23
4534 *
4535 * @param int|Revision $old Old revision or rev ID (first before range by default)
4536 * @param int|Revision $new New revision or rev ID (first after range by default)
4537 * @param int $limit Maximum number of authors
4538 * @param string|array $options (Optional): Single option, or an array of options:
4539 * 'include_old' Include $old in the range; $new is excluded.
4540 * 'include_new' Include $new in the range; $old is excluded.
4541 * 'include_both' Include both $old and $new in the range.
4542 * Unknown option values are ignored.
4543 * @return array|null Names of revision authors in the range; null if not both revisions exist
4544 */
4545 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4546 if ( !( $old instanceof Revision ) ) {
4547 $old = Revision::newFromTitle( $this, (int)$old );
4548 }
4549 if ( !( $new instanceof Revision ) ) {
4550 $new = Revision::newFromTitle( $this, (int)$new );
4551 }
4552 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4553 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4554 // in the sanity check below?
4555 if ( !$old || !$new ) {
4556 return null; // nothing to compare
4557 }
4558 $authors = [];
4559 $old_cmp = '>';
4560 $new_cmp = '<';
4561 $options = (array)$options;
4562 if ( in_array( 'include_old', $options ) ) {
4563 $old_cmp = '>=';
4564 }
4565 if ( in_array( 'include_new', $options ) ) {
4566 $new_cmp = '<=';
4567 }
4568 if ( in_array( 'include_both', $options ) ) {
4569 $old_cmp = '>=';
4570 $new_cmp = '<=';
4571 }
4572 // No DB query needed if $old and $new are the same or successive revisions:
4573 if ( $old->getId() === $new->getId() ) {
4574 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4575 [] :
4576 [ $old->getUserText( Revision::RAW ) ];
4577 } elseif ( $old->getId() === $new->getParentId() ) {
4578 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4579 $authors[] = $old->getUserText( Revision::RAW );
4580 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4581 $authors[] = $new->getUserText( Revision::RAW );
4582 }
4583 } elseif ( $old_cmp === '>=' ) {
4584 $authors[] = $old->getUserText( Revision::RAW );
4585 } elseif ( $new_cmp === '<=' ) {
4586 $authors[] = $new->getUserText( Revision::RAW );
4587 }
4588 return $authors;
4589 }
4590 $dbr = wfGetDB( DB_REPLICA );
4591 $revQuery = Revision::getQueryInfo();
4592 $authors = $dbr->selectFieldValues(
4593 $revQuery['tables'],
4594 $revQuery['fields']['rev_user_text'],
4595 [
4596 'rev_page' => $this->getArticleID(),
4597 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4598 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4599 ], __METHOD__,
4600 [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
4601 $revQuery['joins']
4602 );
4603 return $authors;
4604 }
4605
4606 /**
4607 * Get the number of authors between the given revisions or revision IDs.
4608 * Used for diffs and other things that really need it.
4609 *
4610 * @param int|Revision $old Old revision or rev ID (first before range by default)
4611 * @param int|Revision $new New revision or rev ID (first after range by default)
4612 * @param int $limit Maximum number of authors
4613 * @param string|array $options (Optional): Single option, or an array of options:
4614 * 'include_old' Include $old in the range; $new is excluded.
4615 * 'include_new' Include $new in the range; $old is excluded.
4616 * 'include_both' Include both $old and $new in the range.
4617 * Unknown option values are ignored.
4618 * @return int Number of revision authors in the range; zero if not both revisions exist
4619 */
4620 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4621 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4622 return $authors ? count( $authors ) : 0;
4623 }
4624
4625 /**
4626 * Compare with another title.
4627 *
4628 * @param Title $title
4629 * @return bool
4630 */
4631 public function equals( Title $title ) {
4632 // Note: === is necessary for proper matching of number-like titles.
4633 return $this->mInterwiki === $title->mInterwiki
4634 && $this->mNamespace == $title->mNamespace
4635 && $this->mDbkeyform === $title->mDbkeyform;
4636 }
4637
4638 /**
4639 * Check if this title is a subpage of another title
4640 *
4641 * @param Title $title
4642 * @return bool
4643 */
4644 public function isSubpageOf( Title $title ) {
4645 return $this->mInterwiki === $title->mInterwiki
4646 && $this->mNamespace == $title->mNamespace
4647 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
4648 }
4649
4650 /**
4651 * Check if page exists. For historical reasons, this function simply
4652 * checks for the existence of the title in the page table, and will
4653 * thus return false for interwiki links, special pages and the like.
4654 * If you want to know if a title can be meaningfully viewed, you should
4655 * probably call the isKnown() method instead.
4656 *
4657 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4658 * from master/for update
4659 * @return bool
4660 */
4661 public function exists( $flags = 0 ) {
4662 $exists = $this->getArticleID( $flags ) != 0;
4663 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4664 return $exists;
4665 }
4666
4667 /**
4668 * Should links to this title be shown as potentially viewable (i.e. as
4669 * "bluelinks"), even if there's no record by this title in the page
4670 * table?
4671 *
4672 * This function is semi-deprecated for public use, as well as somewhat
4673 * misleadingly named. You probably just want to call isKnown(), which
4674 * calls this function internally.
4675 *
4676 * (ISSUE: Most of these checks are cheap, but the file existence check
4677 * can potentially be quite expensive. Including it here fixes a lot of
4678 * existing code, but we might want to add an optional parameter to skip
4679 * it and any other expensive checks.)
4680 *
4681 * @return bool
4682 */
4683 public function isAlwaysKnown() {
4684 $isKnown = null;
4685
4686 /**
4687 * Allows overriding default behavior for determining if a page exists.
4688 * If $isKnown is kept as null, regular checks happen. If it's
4689 * a boolean, this value is returned by the isKnown method.
4690 *
4691 * @since 1.20
4692 *
4693 * @param Title $title
4694 * @param bool|null $isKnown
4695 */
4696 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4697
4698 if ( !is_null( $isKnown ) ) {
4699 return $isKnown;
4700 }
4701
4702 if ( $this->isExternal() ) {
4703 return true; // any interwiki link might be viewable, for all we know
4704 }
4705
4706 switch ( $this->mNamespace ) {
4707 case NS_MEDIA:
4708 case NS_FILE:
4709 // file exists, possibly in a foreign repo
4710 return (bool)wfFindFile( $this );
4711 case NS_SPECIAL:
4712 // valid special page
4713 return MediaWikiServices::getInstance()->getSpecialPageFactory()->
4714 exists( $this->mDbkeyform );
4715 case NS_MAIN:
4716 // selflink, possibly with fragment
4717 return $this->mDbkeyform == '';
4718 case NS_MEDIAWIKI:
4719 // known system message
4720 return $this->hasSourceText() !== false;
4721 default:
4722 return false;
4723 }
4724 }
4725
4726 /**
4727 * Does this title refer to a page that can (or might) be meaningfully
4728 * viewed? In particular, this function may be used to determine if
4729 * links to the title should be rendered as "bluelinks" (as opposed to
4730 * "redlinks" to non-existent pages).
4731 * Adding something else to this function will cause inconsistency
4732 * since LinkHolderArray calls isAlwaysKnown() and does its own
4733 * page existence check.
4734 *
4735 * @return bool
4736 */
4737 public function isKnown() {
4738 return $this->isAlwaysKnown() || $this->exists();
4739 }
4740
4741 /**
4742 * Does this page have source text?
4743 *
4744 * @return bool
4745 */
4746 public function hasSourceText() {
4747 if ( $this->exists() ) {
4748 return true;
4749 }
4750
4751 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4752 // If the page doesn't exist but is a known system message, default
4753 // message content will be displayed, same for language subpages-
4754 // Use always content language to avoid loading hundreds of languages
4755 // to get the link color.
4756 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4757 list( $name, ) = MessageCache::singleton()->figureMessage(
4758 $contLang->lcfirst( $this->getText() )
4759 );
4760 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4761 return $message->exists();
4762 }
4763
4764 return false;
4765 }
4766
4767 /**
4768 * Get the default (plain) message contents for an page that overrides an
4769 * interface message key.
4770 *
4771 * Primary use cases:
4772 *
4773 * - Article:
4774 * - Show default when viewing the page. The Article::getSubstituteContent
4775 * method displays the default message content, instead of the
4776 * 'noarticletext' placeholder message normally used.
4777 *
4778 * - EditPage:
4779 * - Title of edit page. When creating an interface message override,
4780 * the editor is told they are "Editing the page", instead of
4781 * "Creating the page". (EditPage::setHeaders)
4782 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4783 * or editing a an interface message override. (EditPage::showIntro)
4784 * - Opening the editor. The contents of the localisation message are used
4785 * as contents of the editor when creating a new page in the MediaWiki
4786 * namespace. This simplifies the process for editors when "changing"
4787 * an interface message by creating an override. (EditPage::getContentObject)
4788 * - Showing a diff. The left-hand side of a diff when an editor is
4789 * previewing their changes before saving the creation of a page in the
4790 * MediaWiki namespace. (EditPage::showDiff)
4791 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4792 * page with the proposed content matching the interface message default,
4793 * the save is rejected, the same way we disallow blank pages from being
4794 * created. (EditPage::internalAttemptSave)
4795 *
4796 * - ApiEditPage:
4797 * - Default content, when using the 'prepend' or 'append' feature.
4798 *
4799 * - SkinTemplate:
4800 * - Label the create action as "Edit", if the page can be an override.
4801 *
4802 * @return string|bool
4803 */
4804 public function getDefaultMessageText() {
4805 if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
4806 return false;
4807 }
4808
4809 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4810 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4811 );
4812 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4813
4814 if ( $message->exists() ) {
4815 return $message->plain();
4816 } else {
4817 return false;
4818 }
4819 }
4820
4821 /**
4822 * Updates page_touched for this page; called from LinksUpdate.php
4823 *
4824 * @param string|null $purgeTime [optional] TS_MW timestamp
4825 * @return bool True if the update succeeded
4826 */
4827 public function invalidateCache( $purgeTime = null ) {
4828 if ( wfReadOnly() ) {
4829 return false;
4830 } elseif ( $this->mArticleID === 0 ) {
4831 return true; // avoid gap locking if we know it's not there
4832 }
4833
4834 $dbw = wfGetDB( DB_MASTER );
4835 $dbw->onTransactionPreCommitOrIdle(
4836 function () use ( $dbw ) {
4837 ResourceLoaderWikiModule::invalidateModuleCache(
4838 $this, null, null, $dbw->getDomainID() );
4839 },
4840 __METHOD__
4841 );
4842
4843 $conds = $this->pageCond();
4844 DeferredUpdates::addUpdate(
4845 new AutoCommitUpdate(
4846 $dbw,
4847 __METHOD__,
4848 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4849 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4850 $dbw->update(
4851 'page',
4852 [ 'page_touched' => $dbTimestamp ],
4853 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4854 $fname
4855 );
4856 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4857 }
4858 ),
4859 DeferredUpdates::PRESEND
4860 );
4861
4862 return true;
4863 }
4864
4865 /**
4866 * Update page_touched timestamps and send CDN purge messages for
4867 * pages linking to this title. May be sent to the job queue depending
4868 * on the number of links. Typically called on create and delete.
4869 */
4870 public function touchLinks() {
4871 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4872 if ( $this->mNamespace == NS_CATEGORY ) {
4873 DeferredUpdates::addUpdate(
4874 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4875 );
4876 }
4877 }
4878
4879 /**
4880 * Get the last touched timestamp
4881 *
4882 * @param IDatabase|null $db
4883 * @return string|false Last-touched timestamp
4884 */
4885 public function getTouched( $db = null ) {
4886 if ( $db === null ) {
4887 $db = wfGetDB( DB_REPLICA );
4888 }
4889 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4890 return $touched;
4891 }
4892
4893 /**
4894 * Get the timestamp when this page was updated since the user last saw it.
4895 *
4896 * @param User|null $user
4897 * @return string|null
4898 */
4899 public function getNotificationTimestamp( $user = null ) {
4900 global $wgUser;
4901
4902 // Assume current user if none given
4903 if ( !$user ) {
4904 $user = $wgUser;
4905 }
4906 // Check cache first
4907 $uid = $user->getId();
4908 if ( !$uid ) {
4909 return false;
4910 }
4911 // avoid isset here, as it'll return false for null entries
4912 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4913 return $this->mNotificationTimestamp[$uid];
4914 }
4915 // Don't cache too much!
4916 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4917 $this->mNotificationTimestamp = [];
4918 }
4919
4920 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4921 $watchedItem = $store->getWatchedItem( $user, $this );
4922 if ( $watchedItem ) {
4923 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4924 } else {
4925 $this->mNotificationTimestamp[$uid] = false;
4926 }
4927
4928 return $this->mNotificationTimestamp[$uid];
4929 }
4930
4931 /**
4932 * Generate strings used for xml 'id' names in monobook tabs
4933 *
4934 * @param string $prepend Defaults to 'nstab-'
4935 * @return string XML 'id' name
4936 */
4937 public function getNamespaceKey( $prepend = 'nstab-' ) {
4938 // Gets the subject namespace of this title
4939 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
4940 // Prefer canonical namespace name for HTML IDs
4941 $namespaceKey = MWNamespace::getCanonicalName( $subjectNS );
4942 if ( $namespaceKey === false ) {
4943 // Fallback to localised text
4944 $namespaceKey = $this->getSubjectNsText();
4945 }
4946 // Makes namespace key lowercase
4947 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4948 // Uses main
4949 if ( $namespaceKey == '' ) {
4950 $namespaceKey = 'main';
4951 }
4952 // Changes file to image for backwards compatibility
4953 if ( $namespaceKey == 'file' ) {
4954 $namespaceKey = 'image';
4955 }
4956 return $prepend . $namespaceKey;
4957 }
4958
4959 /**
4960 * Get all extant redirects to this Title
4961 *
4962 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4963 * @return Title[] Array of Title redirects to this title
4964 */
4965 public function getRedirectsHere( $ns = null ) {
4966 $redirs = [];
4967
4968 $dbr = wfGetDB( DB_REPLICA );
4969 $where = [
4970 'rd_namespace' => $this->mNamespace,
4971 'rd_title' => $this->mDbkeyform,
4972 'rd_from = page_id'
4973 ];
4974 if ( $this->isExternal() ) {
4975 $where['rd_interwiki'] = $this->mInterwiki;
4976 } else {
4977 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4978 }
4979 if ( !is_null( $ns ) ) {
4980 $where['page_namespace'] = $ns;
4981 }
4982
4983 $res = $dbr->select(
4984 [ 'redirect', 'page' ],
4985 [ 'page_namespace', 'page_title' ],
4986 $where,
4987 __METHOD__
4988 );
4989
4990 foreach ( $res as $row ) {
4991 $redirs[] = self::newFromRow( $row );
4992 }
4993 return $redirs;
4994 }
4995
4996 /**
4997 * Check if this Title is a valid redirect target
4998 *
4999 * @return bool
5000 */
5001 public function isValidRedirectTarget() {
5002 global $wgInvalidRedirectTargets;
5003
5004 if ( $this->isSpecialPage() ) {
5005 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5006 if ( $this->isSpecial( 'Userlogout' ) ) {
5007 return false;
5008 }
5009
5010 foreach ( $wgInvalidRedirectTargets as $target ) {
5011 if ( $this->isSpecial( $target ) ) {
5012 return false;
5013 }
5014 }
5015 }
5016
5017 return true;
5018 }
5019
5020 /**
5021 * Get a backlink cache object
5022 *
5023 * @return BacklinkCache
5024 */
5025 public function getBacklinkCache() {
5026 return BacklinkCache::get( $this );
5027 }
5028
5029 /**
5030 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5031 *
5032 * @return bool
5033 */
5034 public function canUseNoindex() {
5035 global $wgExemptFromUserRobotsControl;
5036
5037 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace::getContentNamespaces();
5038
5039 return !in_array( $this->mNamespace, $bannedNamespaces );
5040 }
5041
5042 /**
5043 * Returns the raw sort key to be used for categories, with the specified
5044 * prefix. This will be fed to Collation::getSortKey() to get a
5045 * binary sortkey that can be used for actual sorting.
5046 *
5047 * @param string $prefix The prefix to be used, specified using
5048 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5049 * prefix.
5050 * @return string
5051 */
5052 public function getCategorySortkey( $prefix = '' ) {
5053 $unprefixed = $this->getText();
5054
5055 // Anything that uses this hook should only depend
5056 // on the Title object passed in, and should probably
5057 // tell the users to run updateCollations.php --force
5058 // in order to re-sort existing category relations.
5059 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5060 if ( $prefix !== '' ) {
5061 # Separate with a line feed, so the unprefixed part is only used as
5062 # a tiebreaker when two pages have the exact same prefix.
5063 # In UCA, tab is the only character that can sort above LF
5064 # so we strip both of them from the original prefix.
5065 $prefix = strtr( $prefix, "\n\t", ' ' );
5066 return "$prefix\n$unprefixed";
5067 }
5068 return $unprefixed;
5069 }
5070
5071 /**
5072 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5073 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5074 * the db, it will return NULL.
5075 *
5076 * @return string|null|bool
5077 */
5078 private function getDbPageLanguageCode() {
5079 global $wgPageLanguageUseDB;
5080
5081 // check, if the page language could be saved in the database, and if so and
5082 // the value is not requested already, lookup the page language using LinkCache
5083 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
5084 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
5085 $linkCache->addLinkObj( $this );
5086 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5087 }
5088
5089 return $this->mDbPageLanguage;
5090 }
5091
5092 /**
5093 * Get the language in which the content of this page is written in
5094 * wikitext. Defaults to content language, but in certain cases it can be
5095 * e.g. $wgLang (such as special pages, which are in the user language).
5096 *
5097 * @since 1.18
5098 * @return Language
5099 */
5100 public function getPageLanguage() {
5101 global $wgLang, $wgLanguageCode;
5102 if ( $this->isSpecialPage() ) {
5103 // special pages are in the user language
5104 return $wgLang;
5105 }
5106
5107 // Checking if DB language is set
5108 $dbPageLanguage = $this->getDbPageLanguageCode();
5109 if ( $dbPageLanguage ) {
5110 return wfGetLangObj( $dbPageLanguage );
5111 }
5112
5113 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
5114 // Note that this may depend on user settings, so the cache should
5115 // be only per-request.
5116 // NOTE: ContentHandler::getPageLanguage() may need to load the
5117 // content to determine the page language!
5118 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5119 // tests.
5120 $contentHandler = ContentHandler::getForTitle( $this );
5121 $langObj = $contentHandler->getPageLanguage( $this );
5122 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
5123 } else {
5124 $langObj = Language::factory( $this->mPageLanguage[0] );
5125 }
5126
5127 return $langObj;
5128 }
5129
5130 /**
5131 * Get the language in which the content of this page is written when
5132 * viewed by user. Defaults to content language, but in certain cases it can be
5133 * e.g. $wgLang (such as special pages, which are in the user language).
5134 *
5135 * @since 1.20
5136 * @return Language
5137 */
5138 public function getPageViewLanguage() {
5139 global $wgLang;
5140
5141 if ( $this->isSpecialPage() ) {
5142 // If the user chooses a variant, the content is actually
5143 // in a language whose code is the variant code.
5144 $variant = $wgLang->getPreferredVariant();
5145 if ( $wgLang->getCode() !== $variant ) {
5146 return Language::factory( $variant );
5147 }
5148
5149 return $wgLang;
5150 }
5151
5152 // Checking if DB language is set
5153 $dbPageLanguage = $this->getDbPageLanguageCode();
5154 if ( $dbPageLanguage ) {
5155 $pageLang = wfGetLangObj( $dbPageLanguage );
5156 $variant = $pageLang->getPreferredVariant();
5157 if ( $pageLang->getCode() !== $variant ) {
5158 $pageLang = Language::factory( $variant );
5159 }
5160
5161 return $pageLang;
5162 }
5163
5164 // @note Can't be cached persistently, depends on user settings.
5165 // @note ContentHandler::getPageViewLanguage() may need to load the
5166 // content to determine the page language!
5167 $contentHandler = ContentHandler::getForTitle( $this );
5168 $pageLang = $contentHandler->getPageViewLanguage( $this );
5169 return $pageLang;
5170 }
5171
5172 /**
5173 * Get a list of rendered edit notices for this page.
5174 *
5175 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5176 * they will already be wrapped in paragraphs.
5177 *
5178 * @since 1.21
5179 * @param int $oldid Revision ID that's being edited
5180 * @return array
5181 */
5182 public function getEditNotices( $oldid = 0 ) {
5183 $notices = [];
5184
5185 // Optional notice for the entire namespace
5186 $editnotice_ns = 'editnotice-' . $this->mNamespace;
5187 $msg = wfMessage( $editnotice_ns );
5188 if ( $msg->exists() ) {
5189 $html = $msg->parseAsBlock();
5190 // Edit notices may have complex logic, but output nothing (T91715)
5191 if ( trim( $html ) !== '' ) {
5192 $notices[$editnotice_ns] = Html::rawElement(
5193 'div',
5194 [ 'class' => [
5195 'mw-editnotice',
5196 'mw-editnotice-namespace',
5197 Sanitizer::escapeClass( "mw-$editnotice_ns" )
5198 ] ],
5199 $html
5200 );
5201 }
5202 }
5203
5204 if ( MWNamespace::hasSubpages( $this->mNamespace ) ) {
5205 // Optional notice for page itself and any parent page
5206 $editnotice_base = $editnotice_ns;
5207 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
5208 $editnotice_base .= '-' . $part;
5209 $msg = wfMessage( $editnotice_base );
5210 if ( $msg->exists() ) {
5211 $html = $msg->parseAsBlock();
5212 if ( trim( $html ) !== '' ) {
5213 $notices[$editnotice_base] = Html::rawElement(
5214 'div',
5215 [ 'class' => [
5216 'mw-editnotice',
5217 'mw-editnotice-base',
5218 Sanitizer::escapeClass( "mw-$editnotice_base" )
5219 ] ],
5220 $html
5221 );
5222 }
5223 }
5224 }
5225 } else {
5226 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5227 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
5228 $msg = wfMessage( $editnoticeText );
5229 if ( $msg->exists() ) {
5230 $html = $msg->parseAsBlock();
5231 if ( trim( $html ) !== '' ) {
5232 $notices[$editnoticeText] = Html::rawElement(
5233 'div',
5234 [ 'class' => [
5235 'mw-editnotice',
5236 'mw-editnotice-page',
5237 Sanitizer::escapeClass( "mw-$editnoticeText" )
5238 ] ],
5239 $html
5240 );
5241 }
5242 }
5243 }
5244
5245 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5246 return $notices;
5247 }
5248
5249 /**
5250 * @return array
5251 */
5252 public function __sleep() {
5253 return [
5254 'mNamespace',
5255 'mDbkeyform',
5256 'mFragment',
5257 'mInterwiki',
5258 'mLocalInterwiki',
5259 'mUserCaseDBKey',
5260 'mDefaultNamespace',
5261 ];
5262 }
5263
5264 public function __wakeup() {
5265 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
5266 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
5267 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
5268 }
5269
5270 }