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