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