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