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