Optimize TitleFormatter::getPrefixedText() to Title performance
[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 talk page of some sort?
1485 *
1486 * @return bool
1487 */
1488 public function isTalkPage() {
1489 return MWNamespace::isTalk( $this->mNamespace );
1490 }
1491
1492 /**
1493 * Get a Title object associated with the talk page of this article
1494 *
1495 * @return Title The object for the talk page
1496 */
1497 public function getTalkPage() {
1498 return self::makeTitle( MWNamespace::getTalk( $this->mNamespace ), $this->mDbkeyform );
1499 }
1500
1501 /**
1502 * Get a Title object associated with the talk page of this article,
1503 * if such a talk page can exist.
1504 *
1505 * @since 1.30
1506 *
1507 * @return Title|null The object for the talk page,
1508 * or null if no associated talk page can exist, according to canHaveTalkPage().
1509 */
1510 public function getTalkPageIfDefined() {
1511 if ( !$this->canHaveTalkPage() ) {
1512 return null;
1513 }
1514
1515 return $this->getTalkPage();
1516 }
1517
1518 /**
1519 * Get a title object associated with the subject page of this
1520 * talk page
1521 *
1522 * @return Title The object for the subject page
1523 */
1524 public function getSubjectPage() {
1525 // Is this the same title?
1526 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
1527 if ( $this->mNamespace == $subjectNS ) {
1528 return $this;
1529 }
1530 return self::makeTitle( $subjectNS, $this->mDbkeyform );
1531 }
1532
1533 /**
1534 * Get the other title for this page, if this is a subject page
1535 * get the talk page, if it is a subject page get the talk page
1536 *
1537 * @since 1.25
1538 * @throws MWException If the page doesn't have an other page
1539 * @return Title
1540 */
1541 public function getOtherPage() {
1542 if ( $this->isSpecialPage() ) {
1543 throw new MWException( 'Special pages cannot have other pages' );
1544 }
1545 if ( $this->isTalkPage() ) {
1546 return $this->getSubjectPage();
1547 } else {
1548 if ( !$this->canHaveTalkPage() ) {
1549 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1550 }
1551 return $this->getTalkPage();
1552 }
1553 }
1554
1555 /**
1556 * Get the default namespace index, for when there is no namespace
1557 *
1558 * @return int Default namespace index
1559 */
1560 public function getDefaultNamespace() {
1561 return $this->mDefaultNamespace;
1562 }
1563
1564 /**
1565 * Get the Title fragment (i.e.\ the bit after the #) in text form
1566 *
1567 * Use Title::hasFragment to check for a fragment
1568 *
1569 * @return string Title fragment
1570 */
1571 public function getFragment() {
1572 return $this->mFragment;
1573 }
1574
1575 /**
1576 * Check if a Title fragment is set
1577 *
1578 * @return bool
1579 * @since 1.23
1580 */
1581 public function hasFragment() {
1582 return $this->mFragment !== '';
1583 }
1584
1585 /**
1586 * Get the fragment in URL form, including the "#" character if there is one
1587 *
1588 * @return string Fragment in URL form
1589 */
1590 public function getFragmentForURL() {
1591 if ( !$this->hasFragment() ) {
1592 return '';
1593 } elseif ( $this->isExternal()
1594 && !self::getInterwikiLookup()->fetch( $this->mInterwiki )->isLocal()
1595 ) {
1596 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1597 }
1598 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1599 }
1600
1601 /**
1602 * Set the fragment for this title. Removes the first character from the
1603 * specified fragment before setting, so it assumes you're passing it with
1604 * an initial "#".
1605 *
1606 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1607 * or Title::createFragmentTarget().
1608 * Still in active use privately.
1609 *
1610 * @private
1611 * @param string $fragment Text
1612 */
1613 public function setFragment( $fragment ) {
1614 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1615 }
1616
1617 /**
1618 * Creates a new Title for a different fragment of the same page.
1619 *
1620 * @since 1.27
1621 * @param string $fragment
1622 * @return Title
1623 */
1624 public function createFragmentTarget( $fragment ) {
1625 return self::makeTitle(
1626 $this->mNamespace,
1627 $this->getText(),
1628 $fragment,
1629 $this->mInterwiki
1630 );
1631 }
1632
1633 /**
1634 * Prefix some arbitrary text with the namespace or interwiki prefix
1635 * of this object
1636 *
1637 * @param string $name The text
1638 * @return string The prefixed text
1639 */
1640 private function prefix( $name ) {
1641 $p = '';
1642 if ( $this->isExternal() ) {
1643 $p = $this->mInterwiki . ':';
1644 }
1645
1646 if ( 0 != $this->mNamespace ) {
1647 $nsText = $this->getNsText();
1648
1649 if ( $nsText === false ) {
1650 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1651 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1652 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1653 }
1654
1655 $p .= $nsText . ':';
1656 }
1657 return $p . $name;
1658 }
1659
1660 /**
1661 * Get the prefixed database key form
1662 *
1663 * @return string The prefixed title, with underscores and
1664 * any interwiki and namespace prefixes
1665 */
1666 public function getPrefixedDBkey() {
1667 $s = $this->prefix( $this->mDbkeyform );
1668 $s = strtr( $s, ' ', '_' );
1669 return $s;
1670 }
1671
1672 /**
1673 * Get the prefixed title with spaces.
1674 * This is the form usually used for display
1675 *
1676 * @return string The prefixed title, with spaces
1677 */
1678 public function getPrefixedText() {
1679 if ( $this->prefixedText === null ) {
1680 $s = $this->prefix( $this->mTextform );
1681 $s = strtr( $s, '_', ' ' );
1682 $this->prefixedText = $s;
1683 }
1684 return $this->prefixedText;
1685 }
1686
1687 /**
1688 * Return a string representation of this title
1689 *
1690 * @return string Representation of this title
1691 */
1692 public function __toString() {
1693 return $this->getPrefixedText();
1694 }
1695
1696 /**
1697 * Get the prefixed title with spaces, plus any fragment
1698 * (part beginning with '#')
1699 *
1700 * @return string The prefixed title, with spaces and the fragment, including '#'
1701 */
1702 public function getFullText() {
1703 $text = $this->getPrefixedText();
1704 if ( $this->hasFragment() ) {
1705 $text .= '#' . $this->mFragment;
1706 }
1707 return $text;
1708 }
1709
1710 /**
1711 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1712 *
1713 * @par Example:
1714 * @code
1715 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1716 * # returns: 'Foo'
1717 * @endcode
1718 *
1719 * @return string Root name
1720 * @since 1.20
1721 */
1722 public function getRootText() {
1723 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1724 return $this->getText();
1725 }
1726
1727 return strtok( $this->getText(), '/' );
1728 }
1729
1730 /**
1731 * Get the root page name title, i.e. the leftmost part before any slashes
1732 *
1733 * @par Example:
1734 * @code
1735 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1736 * # returns: Title{User:Foo}
1737 * @endcode
1738 *
1739 * @return Title Root title
1740 * @since 1.20
1741 */
1742 public function getRootTitle() {
1743 return self::makeTitle( $this->mNamespace, $this->getRootText() );
1744 }
1745
1746 /**
1747 * Get the base page name without a namespace, i.e. the part before the subpage name
1748 *
1749 * @par Example:
1750 * @code
1751 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1752 * # returns: 'Foo/Bar'
1753 * @endcode
1754 *
1755 * @return string Base name
1756 */
1757 public function getBaseText() {
1758 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1759 return $this->getText();
1760 }
1761
1762 $parts = explode( '/', $this->getText() );
1763 # Don't discard the real title if there's no subpage involved
1764 if ( count( $parts ) > 1 ) {
1765 unset( $parts[count( $parts ) - 1] );
1766 }
1767 return implode( '/', $parts );
1768 }
1769
1770 /**
1771 * Get the base page name title, i.e. the part before the subpage name
1772 *
1773 * @par Example:
1774 * @code
1775 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1776 * # returns: Title{User:Foo/Bar}
1777 * @endcode
1778 *
1779 * @return Title Base title
1780 * @since 1.20
1781 */
1782 public function getBaseTitle() {
1783 return self::makeTitle( $this->mNamespace, $this->getBaseText() );
1784 }
1785
1786 /**
1787 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1788 *
1789 * @par Example:
1790 * @code
1791 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1792 * # returns: "Baz"
1793 * @endcode
1794 *
1795 * @return string Subpage name
1796 */
1797 public function getSubpageText() {
1798 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1799 return $this->mTextform;
1800 }
1801 $parts = explode( '/', $this->mTextform );
1802 return $parts[count( $parts ) - 1];
1803 }
1804
1805 /**
1806 * Get the title for a subpage of the current page
1807 *
1808 * @par Example:
1809 * @code
1810 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1811 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1812 * @endcode
1813 *
1814 * @param string $text The subpage name to add to the title
1815 * @return Title Subpage title
1816 * @since 1.20
1817 */
1818 public function getSubpage( $text ) {
1819 return self::makeTitleSafe( $this->mNamespace, $this->getText() . '/' . $text );
1820 }
1821
1822 /**
1823 * Get a URL-encoded form of the subpage text
1824 *
1825 * @return string URL-encoded subpage name
1826 */
1827 public function getSubpageUrlForm() {
1828 $text = $this->getSubpageText();
1829 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1830 return $text;
1831 }
1832
1833 /**
1834 * Get a URL-encoded title (not an actual URL) including interwiki
1835 *
1836 * @return string The URL-encoded form
1837 */
1838 public function getPrefixedURL() {
1839 $s = $this->prefix( $this->mDbkeyform );
1840 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1841 return $s;
1842 }
1843
1844 /**
1845 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1846 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1847 * second argument named variant. This was deprecated in favor
1848 * of passing an array of option with a "variant" key
1849 * Once $query2 is removed for good, this helper can be dropped
1850 * and the wfArrayToCgi moved to getLocalURL();
1851 *
1852 * @since 1.19 (r105919)
1853 * @param array|string $query
1854 * @param string|string[]|bool $query2
1855 * @return string
1856 */
1857 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1858 if ( $query2 !== false ) {
1859 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1860 "method called with a second parameter is deprecated. Add your " .
1861 "parameter to an array passed as the first parameter.", "1.19" );
1862 }
1863 if ( is_array( $query ) ) {
1864 $query = wfArrayToCgi( $query );
1865 }
1866 if ( $query2 ) {
1867 if ( is_string( $query2 ) ) {
1868 // $query2 is a string, we will consider this to be
1869 // a deprecated $variant argument and add it to the query
1870 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1871 } else {
1872 $query2 = wfArrayToCgi( $query2 );
1873 }
1874 // If we have $query content add a & to it first
1875 if ( $query ) {
1876 $query .= '&';
1877 }
1878 // Now append the queries together
1879 $query .= $query2;
1880 }
1881 return $query;
1882 }
1883
1884 /**
1885 * Get a real URL referring to this title, with interwiki link and
1886 * fragment
1887 *
1888 * @see self::getLocalURL for the arguments.
1889 * @see wfExpandUrl
1890 * @param string|string[] $query
1891 * @param string|string[]|bool $query2
1892 * @param string|int|null $proto Protocol type to use in URL
1893 * @return string The URL
1894 */
1895 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1896 $query = self::fixUrlQueryArgs( $query, $query2 );
1897
1898 # Hand off all the decisions on urls to getLocalURL
1899 $url = $this->getLocalURL( $query );
1900
1901 # Expand the url to make it a full url. Note that getLocalURL has the
1902 # potential to output full urls for a variety of reasons, so we use
1903 # wfExpandUrl instead of simply prepending $wgServer
1904 $url = wfExpandUrl( $url, $proto );
1905
1906 # Finally, add the fragment.
1907 $url .= $this->getFragmentForURL();
1908 // Avoid PHP 7.1 warning from passing $this by reference
1909 $titleRef = $this;
1910 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1911 return $url;
1912 }
1913
1914 /**
1915 * Get a url appropriate for making redirects based on an untrusted url arg
1916 *
1917 * This is basically the same as getFullUrl(), but in the case of external
1918 * interwikis, we send the user to a landing page, to prevent possible
1919 * phishing attacks and the like.
1920 *
1921 * @note Uses current protocol by default, since technically relative urls
1922 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1923 * places where the url gets cached, as might pollute between
1924 * https and non-https users.
1925 * @see self::getLocalURL for the arguments.
1926 * @param array|string $query
1927 * @param string $proto Protocol type to use in URL
1928 * @return string A url suitable to use in an HTTP location header.
1929 */
1930 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
1931 $target = $this;
1932 if ( $this->isExternal() ) {
1933 $target = SpecialPage::getTitleFor(
1934 'GoToInterwiki',
1935 $this->getPrefixedDBkey()
1936 );
1937 }
1938 return $target->getFullURL( $query, false, $proto );
1939 }
1940
1941 /**
1942 * Get a URL with no fragment or server name (relative URL) from a Title object.
1943 * If this page is generated with action=render, however,
1944 * $wgServer is prepended to make an absolute URL.
1945 *
1946 * @see self::getFullURL to always get an absolute URL.
1947 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1948 * valid to link, locally, to the current Title.
1949 * @see self::newFromText to produce a Title object.
1950 *
1951 * @param string|string[] $query An optional query string,
1952 * not used for interwiki links. Can be specified as an associative array as well,
1953 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1954 * Some query patterns will trigger various shorturl path replacements.
1955 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1956 * be an array. If a string is passed it will be interpreted as a deprecated
1957 * variant argument and urlencoded into a variant= argument.
1958 * This second query argument will be added to the $query
1959 * The second parameter is deprecated since 1.19. Pass it as a key,value
1960 * pair in the first parameter array instead.
1961 *
1962 * @return string String of the URL.
1963 */
1964 public function getLocalURL( $query = '', $query2 = false ) {
1965 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1966
1967 $query = self::fixUrlQueryArgs( $query, $query2 );
1968
1969 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1970 if ( $interwiki ) {
1971 $namespace = $this->getNsText();
1972 if ( $namespace != '' ) {
1973 # Can this actually happen? Interwikis shouldn't be parsed.
1974 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1975 $namespace .= ':';
1976 }
1977 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
1978 $url = wfAppendQuery( $url, $query );
1979 } else {
1980 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1981 if ( $query == '' ) {
1982 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1983 // Avoid PHP 7.1 warning from passing $this by reference
1984 $titleRef = $this;
1985 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1986 } else {
1987 global $wgVariantArticlePath, $wgActionPaths;
1988 $url = false;
1989 $matches = [];
1990
1991 if ( !empty( $wgActionPaths )
1992 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1993 ) {
1994 $action = urldecode( $matches[2] );
1995 if ( isset( $wgActionPaths[$action] ) ) {
1996 $query = $matches[1];
1997 if ( isset( $matches[4] ) ) {
1998 $query .= $matches[4];
1999 }
2000 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2001 if ( $query != '' ) {
2002 $url = wfAppendQuery( $url, $query );
2003 }
2004 }
2005 }
2006
2007 if ( $url === false
2008 && $wgVariantArticlePath
2009 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2010 && $this->getPageLanguage()->equals(
2011 MediaWikiServices::getInstance()->getContentLanguage() )
2012 && $this->getPageLanguage()->hasVariants()
2013 ) {
2014 $variant = urldecode( $matches[1] );
2015 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2016 // Only do the variant replacement if the given variant is a valid
2017 // variant for the page's language.
2018 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2019 $url = str_replace( '$1', $dbkey, $url );
2020 }
2021 }
2022
2023 if ( $url === false ) {
2024 if ( $query == '-' ) {
2025 $query = '';
2026 }
2027 $url = "{$wgScript}?title={$dbkey}&{$query}";
2028 }
2029 }
2030 // Avoid PHP 7.1 warning from passing $this by reference
2031 $titleRef = $this;
2032 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2033
2034 // @todo FIXME: This causes breakage in various places when we
2035 // actually expected a local URL and end up with dupe prefixes.
2036 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2037 $url = $wgServer . $url;
2038 }
2039 }
2040 // Avoid PHP 7.1 warning from passing $this by reference
2041 $titleRef = $this;
2042 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2043 return $url;
2044 }
2045
2046 /**
2047 * Get a URL that's the simplest URL that will be valid to link, locally,
2048 * to the current Title. It includes the fragment, but does not include
2049 * the server unless action=render is used (or the link is external). If
2050 * there's a fragment but the prefixed text is empty, we just return a link
2051 * to the fragment.
2052 *
2053 * The result obviously should not be URL-escaped, but does need to be
2054 * HTML-escaped if it's being output in HTML.
2055 *
2056 * @param string|string[] $query
2057 * @param bool $query2
2058 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2059 * or false (default) for no expansion
2060 * @see self::getLocalURL for the arguments.
2061 * @return string The URL
2062 */
2063 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2064 if ( $this->isExternal() || $proto !== false ) {
2065 $ret = $this->getFullURL( $query, $query2, $proto );
2066 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2067 $ret = $this->getFragmentForURL();
2068 } else {
2069 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2070 }
2071 return $ret;
2072 }
2073
2074 /**
2075 * Get the URL form for an internal link.
2076 * - Used in various CDN-related code, in case we have a different
2077 * internal hostname for the server from the exposed one.
2078 *
2079 * This uses $wgInternalServer to qualify the path, or $wgServer
2080 * if $wgInternalServer is not set. If the server variable used is
2081 * protocol-relative, the URL will be expanded to http://
2082 *
2083 * @see self::getLocalURL for the arguments.
2084 * @param string $query
2085 * @param string|bool $query2
2086 * @return string The URL
2087 */
2088 public function getInternalURL( $query = '', $query2 = false ) {
2089 global $wgInternalServer, $wgServer;
2090 $query = self::fixUrlQueryArgs( $query, $query2 );
2091 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2092 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2093 // Avoid PHP 7.1 warning from passing $this by reference
2094 $titleRef = $this;
2095 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2096 return $url;
2097 }
2098
2099 /**
2100 * Get the URL for a canonical link, for use in things like IRC and
2101 * e-mail notifications. Uses $wgCanonicalServer and the
2102 * GetCanonicalURL hook.
2103 *
2104 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2105 *
2106 * @see self::getLocalURL for the arguments.
2107 * @param string $query
2108 * @param string|bool $query2
2109 * @return string The URL
2110 * @since 1.18
2111 */
2112 public function getCanonicalURL( $query = '', $query2 = false ) {
2113 $query = self::fixUrlQueryArgs( $query, $query2 );
2114 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2115 // Avoid PHP 7.1 warning from passing $this by reference
2116 $titleRef = $this;
2117 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2118 return $url;
2119 }
2120
2121 /**
2122 * Get the edit URL for this Title
2123 *
2124 * @return string The URL, or a null string if this is an interwiki link
2125 */
2126 public function getEditURL() {
2127 if ( $this->isExternal() ) {
2128 return '';
2129 }
2130 $s = $this->getLocalURL( 'action=edit' );
2131
2132 return $s;
2133 }
2134
2135 /**
2136 * Can $user perform $action on this page?
2137 * This skips potentially expensive cascading permission checks
2138 * as well as avoids expensive error formatting
2139 *
2140 * Suitable for use for nonessential UI controls in common cases, but
2141 * _not_ for functional access control.
2142 *
2143 * May provide false positives, but should never provide a false negative.
2144 *
2145 * @param string $action Action that permission needs to be checked for
2146 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2147 * @return bool
2148 */
2149 public function quickUserCan( $action, $user = null ) {
2150 return $this->userCan( $action, $user, false );
2151 }
2152
2153 /**
2154 * Can $user perform $action on this page?
2155 *
2156 * @param string $action Action that permission needs to be checked for
2157 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2158 * provided.
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @return bool
2161 */
2162 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2163 if ( !$user instanceof User ) {
2164 global $wgUser;
2165 $user = $wgUser;
2166 }
2167
2168 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2169 }
2170
2171 /**
2172 * Can $user perform $action on this page?
2173 *
2174 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2175 *
2176 * @param string $action Action that permission needs to be checked for
2177 * @param User $user User to check
2178 * @param string $rigor One of (quick,full,secure)
2179 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2180 * - full : does cheap and expensive checks possibly from a replica DB
2181 * - secure : does cheap and expensive checks, using the master as needed
2182 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2183 * whose corresponding errors may be ignored.
2184 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2185 */
2186 public function getUserPermissionsErrors(
2187 $action, $user, $rigor = 'secure', $ignoreErrors = []
2188 ) {
2189 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2190
2191 // Remove the errors being ignored.
2192 foreach ( $errors as $index => $error ) {
2193 $errKey = is_array( $error ) ? $error[0] : $error;
2194
2195 if ( in_array( $errKey, $ignoreErrors ) ) {
2196 unset( $errors[$index] );
2197 }
2198 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
2199 unset( $errors[$index] );
2200 }
2201 }
2202
2203 return $errors;
2204 }
2205
2206 /**
2207 * Permissions checks that fail most often, and which are easiest to test.
2208 *
2209 * @param string $action The action to check
2210 * @param User $user User to check
2211 * @param array $errors List of current errors
2212 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2213 * @param bool $short Short circuit on first error
2214 *
2215 * @return array List of errors
2216 */
2217 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2218 if ( !Hooks::run( 'TitleQuickPermissions',
2219 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2220 ) {
2221 return $errors;
2222 }
2223
2224 if ( $action == 'create' ) {
2225 if (
2226 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2227 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2228 ) {
2229 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2230 }
2231 } elseif ( $action == 'move' ) {
2232 if ( !$user->isAllowed( 'move-rootuserpages' )
2233 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2234 // Show user page-specific message only if the user can move other pages
2235 $errors[] = [ 'cant-move-user-page' ];
2236 }
2237
2238 // Check if user is allowed to move files if it's a file
2239 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2240 $errors[] = [ 'movenotallowedfile' ];
2241 }
2242
2243 // Check if user is allowed to move category pages if it's a category page
2244 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2245 $errors[] = [ 'cant-move-category-page' ];
2246 }
2247
2248 if ( !$user->isAllowed( 'move' ) ) {
2249 // User can't move anything
2250 $userCanMove = User::groupHasPermission( 'user', 'move' );
2251 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2252 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2253 // custom message if logged-in users without any special rights can move
2254 $errors[] = [ 'movenologintext' ];
2255 } else {
2256 $errors[] = [ 'movenotallowed' ];
2257 }
2258 }
2259 } elseif ( $action == 'move-target' ) {
2260 if ( !$user->isAllowed( 'move' ) ) {
2261 // User can't move anything
2262 $errors[] = [ 'movenotallowed' ];
2263 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2264 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2265 // Show user page-specific message only if the user can move other pages
2266 $errors[] = [ 'cant-move-to-user-page' ];
2267 } elseif ( !$user->isAllowed( 'move-categorypages' )
2268 && $this->mNamespace == NS_CATEGORY ) {
2269 // Show category page-specific message only if the user can move other pages
2270 $errors[] = [ 'cant-move-to-category-page' ];
2271 }
2272 } elseif ( !$user->isAllowed( $action ) ) {
2273 $errors[] = $this->missingPermissionError( $action, $short );
2274 }
2275
2276 return $errors;
2277 }
2278
2279 /**
2280 * Add the resulting error code to the errors array
2281 *
2282 * @param array $errors List of current errors
2283 * @param array $result Result of errors
2284 *
2285 * @return array List of errors
2286 */
2287 private function resultToError( $errors, $result ) {
2288 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2289 // A single array representing an error
2290 $errors[] = $result;
2291 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2292 // A nested array representing multiple errors
2293 $errors = array_merge( $errors, $result );
2294 } elseif ( $result !== '' && is_string( $result ) ) {
2295 // A string representing a message-id
2296 $errors[] = [ $result ];
2297 } elseif ( $result instanceof MessageSpecifier ) {
2298 // A message specifier representing an error
2299 $errors[] = [ $result ];
2300 } elseif ( $result === false ) {
2301 // a generic "We don't want them to do that"
2302 $errors[] = [ 'badaccess-group0' ];
2303 }
2304 return $errors;
2305 }
2306
2307 /**
2308 * Check various permission hooks
2309 *
2310 * @param string $action The action to check
2311 * @param User $user User to check
2312 * @param array $errors List of current errors
2313 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2314 * @param bool $short Short circuit on first error
2315 *
2316 * @return array List of errors
2317 */
2318 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2319 // Use getUserPermissionsErrors instead
2320 $result = '';
2321 // Avoid PHP 7.1 warning from passing $this by reference
2322 $titleRef = $this;
2323 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2324 return $result ? [] : [ [ 'badaccess-group0' ] ];
2325 }
2326 // Check getUserPermissionsErrors hook
2327 // Avoid PHP 7.1 warning from passing $this by reference
2328 $titleRef = $this;
2329 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2330 $errors = $this->resultToError( $errors, $result );
2331 }
2332 // Check getUserPermissionsErrorsExpensive hook
2333 if (
2334 $rigor !== 'quick'
2335 && !( $short && count( $errors ) > 0 )
2336 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2337 ) {
2338 $errors = $this->resultToError( $errors, $result );
2339 }
2340
2341 return $errors;
2342 }
2343
2344 /**
2345 * Check permissions on special pages & namespaces
2346 *
2347 * @param string $action The action to check
2348 * @param User $user User to check
2349 * @param array $errors List of current errors
2350 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2351 * @param bool $short Short circuit on first error
2352 *
2353 * @return array List of errors
2354 */
2355 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2356 # Only 'createaccount' can be performed on special pages,
2357 # which don't actually exist in the DB.
2358 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2359 $errors[] = [ 'ns-specialprotected' ];
2360 }
2361
2362 # Check $wgNamespaceProtection for restricted namespaces
2363 if ( $this->isNamespaceProtected( $user ) ) {
2364 $ns = $this->mNamespace == NS_MAIN ?
2365 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2366 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2367 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2368 }
2369
2370 return $errors;
2371 }
2372
2373 /**
2374 * Check sitewide CSS/JSON/JS permissions
2375 *
2376 * @param string $action The action to check
2377 * @param User $user User to check
2378 * @param array $errors List of current errors
2379 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2380 * @param bool $short Short circuit on first error
2381 *
2382 * @return array List of errors
2383 */
2384 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2385 if ( $action != 'patrol' ) {
2386 $error = null;
2387 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2388 // editinterface right. That's implemented as a restriction so no check needed here.
2389 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2390 $error = [ 'sitecssprotected', $action ];
2391 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2392 $error = [ 'sitejsonprotected', $action ];
2393 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2394 $error = [ 'sitejsprotected', $action ];
2395 }
2396
2397 if ( $error ) {
2398 if ( $user->isAllowed( 'editinterface' ) ) {
2399 // Most users / site admins will probably find out about the new, more restrictive
2400 // permissions by failing to edit something. Give them more info.
2401 // TODO remove this a few release cycles after 1.32
2402 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2403 }
2404 $errors[] = $error;
2405 }
2406 }
2407
2408 return $errors;
2409 }
2410
2411 /**
2412 * Check CSS/JSON/JS sub-page permissions
2413 *
2414 * @param string $action The action to check
2415 * @param User $user User to check
2416 * @param array $errors List of current errors
2417 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2418 * @param bool $short Short circuit on first error
2419 *
2420 * @return array List of errors
2421 */
2422 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2423 # Protect css/json/js subpages of user pages
2424 # XXX: this might be better using restrictions
2425
2426 if ( $action != 'patrol' ) {
2427 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2428 if (
2429 $this->isUserCssConfigPage()
2430 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2431 ) {
2432 $errors[] = [ 'mycustomcssprotected', $action ];
2433 } elseif (
2434 $this->isUserJsonConfigPage()
2435 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2436 ) {
2437 $errors[] = [ 'mycustomjsonprotected', $action ];
2438 } elseif (
2439 $this->isUserJsConfigPage()
2440 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2441 ) {
2442 $errors[] = [ 'mycustomjsprotected', $action ];
2443 }
2444 } else {
2445 if (
2446 $this->isUserCssConfigPage()
2447 && !$user->isAllowed( 'editusercss' )
2448 ) {
2449 $errors[] = [ 'customcssprotected', $action ];
2450 } elseif (
2451 $this->isUserJsonConfigPage()
2452 && !$user->isAllowed( 'edituserjson' )
2453 ) {
2454 $errors[] = [ 'customjsonprotected', $action ];
2455 } elseif (
2456 $this->isUserJsConfigPage()
2457 && !$user->isAllowed( 'edituserjs' )
2458 ) {
2459 $errors[] = [ 'customjsprotected', $action ];
2460 }
2461 }
2462 }
2463
2464 return $errors;
2465 }
2466
2467 /**
2468 * Check against page_restrictions table requirements on this
2469 * page. The user must possess all required rights for this
2470 * action.
2471 *
2472 * @param string $action The action to check
2473 * @param User $user User to check
2474 * @param array $errors List of current errors
2475 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2476 * @param bool $short Short circuit on first error
2477 *
2478 * @return array List of errors
2479 */
2480 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2481 foreach ( $this->getRestrictions( $action ) as $right ) {
2482 // Backwards compatibility, rewrite sysop -> editprotected
2483 if ( $right == 'sysop' ) {
2484 $right = 'editprotected';
2485 }
2486 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2487 if ( $right == 'autoconfirmed' ) {
2488 $right = 'editsemiprotected';
2489 }
2490 if ( $right == '' ) {
2491 continue;
2492 }
2493 if ( !$user->isAllowed( $right ) ) {
2494 $errors[] = [ 'protectedpagetext', $right, $action ];
2495 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2496 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2497 }
2498 }
2499
2500 return $errors;
2501 }
2502
2503 /**
2504 * Check restrictions on cascading pages.
2505 *
2506 * @param string $action The action to check
2507 * @param User $user User to check
2508 * @param array $errors List of current errors
2509 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2510 * @param bool $short Short circuit on first error
2511 *
2512 * @return array List of errors
2513 */
2514 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2515 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2516 # We /could/ use the protection level on the source page, but it's
2517 # fairly ugly as we have to establish a precedence hierarchy for pages
2518 # included by multiple cascade-protected pages. So just restrict
2519 # it to people with 'protect' permission, as they could remove the
2520 # protection anyway.
2521 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2522 # Cascading protection depends on more than this page...
2523 # Several cascading protected pages may include this page...
2524 # Check each cascading level
2525 # This is only for protection restrictions, not for all actions
2526 if ( isset( $restrictions[$action] ) ) {
2527 foreach ( $restrictions[$action] as $right ) {
2528 // Backwards compatibility, rewrite sysop -> editprotected
2529 if ( $right == 'sysop' ) {
2530 $right = 'editprotected';
2531 }
2532 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2533 if ( $right == 'autoconfirmed' ) {
2534 $right = 'editsemiprotected';
2535 }
2536 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2537 $pages = '';
2538 foreach ( $cascadingSources as $page ) {
2539 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2540 }
2541 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2542 }
2543 }
2544 }
2545 }
2546
2547 return $errors;
2548 }
2549
2550 /**
2551 * Check action permissions not already checked in checkQuickPermissions
2552 *
2553 * @param string $action The action to check
2554 * @param User $user User to check
2555 * @param array $errors List of current errors
2556 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2557 * @param bool $short Short circuit on first error
2558 *
2559 * @return array List of errors
2560 */
2561 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2562 global $wgDeleteRevisionsLimit, $wgLang;
2563
2564 if ( $action == 'protect' ) {
2565 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2566 // If they can't edit, they shouldn't protect.
2567 $errors[] = [ 'protect-cantedit' ];
2568 }
2569 } elseif ( $action == 'create' ) {
2570 $title_protection = $this->getTitleProtection();
2571 if ( $title_protection ) {
2572 if ( $title_protection['permission'] == ''
2573 || !$user->isAllowed( $title_protection['permission'] )
2574 ) {
2575 $errors[] = [
2576 'titleprotected',
2577 User::whoIs( $title_protection['user'] ),
2578 $title_protection['reason']
2579 ];
2580 }
2581 }
2582 } elseif ( $action == 'move' ) {
2583 // Check for immobile pages
2584 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2585 // Specific message for this case
2586 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2587 } elseif ( !$this->isMovable() ) {
2588 // Less specific message for rarer cases
2589 $errors[] = [ 'immobile-source-page' ];
2590 }
2591 } elseif ( $action == 'move-target' ) {
2592 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2593 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2594 } elseif ( !$this->isMovable() ) {
2595 $errors[] = [ 'immobile-target-page' ];
2596 }
2597 } elseif ( $action == 'delete' ) {
2598 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2599 if ( !$tempErrors ) {
2600 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2601 $user, $tempErrors, $rigor, true );
2602 }
2603 if ( $tempErrors ) {
2604 // If protection keeps them from editing, they shouldn't be able to delete.
2605 $errors[] = [ 'deleteprotected' ];
2606 }
2607 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2608 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2609 ) {
2610 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2611 }
2612 } elseif ( $action === 'undelete' ) {
2613 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2614 // Undeleting implies editing
2615 $errors[] = [ 'undelete-cantedit' ];
2616 }
2617 if ( !$this->exists()
2618 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2619 ) {
2620 // Undeleting where nothing currently exists implies creating
2621 $errors[] = [ 'undelete-cantcreate' ];
2622 }
2623 }
2624 return $errors;
2625 }
2626
2627 /**
2628 * Check that the user isn't blocked from editing.
2629 *
2630 * @param string $action The action to check
2631 * @param User $user User to check
2632 * @param array $errors List of current errors
2633 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2634 * @param bool $short Short circuit on first error
2635 *
2636 * @return array List of errors
2637 */
2638 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2639 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2640 // Account creation blocks handled at userlogin.
2641 // Unblocking handled in SpecialUnblock
2642 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2643 return $errors;
2644 }
2645
2646 // Optimize for a very common case
2647 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2648 return $errors;
2649 }
2650
2651 if ( $wgEmailConfirmToEdit
2652 && !$user->isEmailConfirmed()
2653 && $action === 'edit'
2654 ) {
2655 $errors[] = [ 'confirmedittext' ];
2656 }
2657
2658 $useSlave = ( $rigor !== 'secure' );
2659 if ( ( $action == 'edit' || $action == 'create' )
2660 && !$user->isBlockedFrom( $this, $useSlave )
2661 ) {
2662 // Don't block the user from editing their own talk page unless they've been
2663 // explicitly blocked from that too.
2664 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2665 // @todo FIXME: Pass the relevant context into this function.
2666 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2667 }
2668
2669 return $errors;
2670 }
2671
2672 /**
2673 * Check that the user is allowed to read this page.
2674 *
2675 * @param string $action The action to check
2676 * @param User $user User to check
2677 * @param array $errors List of current errors
2678 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2679 * @param bool $short Short circuit on first error
2680 *
2681 * @return array List of errors
2682 */
2683 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2684 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2685
2686 $whitelisted = false;
2687 if ( User::isEveryoneAllowed( 'read' ) ) {
2688 # Shortcut for public wikis, allows skipping quite a bit of code
2689 $whitelisted = true;
2690 } elseif ( $user->isAllowed( 'read' ) ) {
2691 # If the user is allowed to read pages, he is allowed to read all pages
2692 $whitelisted = true;
2693 } elseif ( $this->isSpecial( 'Userlogin' )
2694 || $this->isSpecial( 'PasswordReset' )
2695 || $this->isSpecial( 'Userlogout' )
2696 ) {
2697 # Always grant access to the login page.
2698 # Even anons need to be able to log in.
2699 $whitelisted = true;
2700 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2701 # Time to check the whitelist
2702 # Only do these checks is there's something to check against
2703 $name = $this->getPrefixedText();
2704 $dbName = $this->getPrefixedDBkey();
2705
2706 // Check for explicit whitelisting with and without underscores
2707 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2708 $whitelisted = true;
2709 } elseif ( $this->mNamespace == NS_MAIN ) {
2710 # Old settings might have the title prefixed with
2711 # a colon for main-namespace pages
2712 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2713 $whitelisted = true;
2714 }
2715 } elseif ( $this->isSpecialPage() ) {
2716 # If it's a special page, ditch the subpage bit and check again
2717 $name = $this->mDbkeyform;
2718 list( $name, /* $subpage */ ) =
2719 MediaWikiServices::getInstance()->getSpecialPageFactory()->
2720 resolveAlias( $name );
2721 if ( $name ) {
2722 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2723 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2724 $whitelisted = true;
2725 }
2726 }
2727 }
2728 }
2729
2730 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2731 $name = $this->getPrefixedText();
2732 // Check for regex whitelisting
2733 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2734 if ( preg_match( $listItem, $name ) ) {
2735 $whitelisted = true;
2736 break;
2737 }
2738 }
2739 }
2740
2741 if ( !$whitelisted ) {
2742 # If the title is not whitelisted, give extensions a chance to do so...
2743 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2744 if ( !$whitelisted ) {
2745 $errors[] = $this->missingPermissionError( $action, $short );
2746 }
2747 }
2748
2749 return $errors;
2750 }
2751
2752 /**
2753 * Get a description array when the user doesn't have the right to perform
2754 * $action (i.e. when User::isAllowed() returns false)
2755 *
2756 * @param string $action The action to check
2757 * @param bool $short Short circuit on first error
2758 * @return array Array containing an error message key and any parameters
2759 */
2760 private function missingPermissionError( $action, $short ) {
2761 // We avoid expensive display logic for quickUserCan's and such
2762 if ( $short ) {
2763 return [ 'badaccess-group0' ];
2764 }
2765
2766 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2767 }
2768
2769 /**
2770 * Can $user perform $action on this page? This is an internal function,
2771 * with multiple levels of checks depending on performance needs; see $rigor below.
2772 * It does not check wfReadOnly().
2773 *
2774 * @param string $action Action that permission needs to be checked for
2775 * @param User $user User to check
2776 * @param string $rigor One of (quick,full,secure)
2777 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2778 * - full : does cheap and expensive checks possibly from a replica DB
2779 * - secure : does cheap and expensive checks, using the master as needed
2780 * @param bool $short Set this to true to stop after the first permission error.
2781 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2782 */
2783 protected function getUserPermissionsErrorsInternal(
2784 $action, $user, $rigor = 'secure', $short = false
2785 ) {
2786 if ( $rigor === true ) {
2787 $rigor = 'secure'; // b/c
2788 } elseif ( $rigor === false ) {
2789 $rigor = 'quick'; // b/c
2790 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2791 throw new Exception( "Invalid rigor parameter '$rigor'." );
2792 }
2793
2794 # Read has special handling
2795 if ( $action == 'read' ) {
2796 $checks = [
2797 'checkPermissionHooks',
2798 'checkReadPermissions',
2799 'checkUserBlock', // for wgBlockDisablesLogin
2800 ];
2801 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2802 # or checkUserConfigPermissions here as it will lead to duplicate
2803 # error messages. This is okay to do since anywhere that checks for
2804 # create will also check for edit, and those checks are called for edit.
2805 } elseif ( $action == 'create' ) {
2806 $checks = [
2807 'checkQuickPermissions',
2808 'checkPermissionHooks',
2809 'checkPageRestrictions',
2810 'checkCascadingSourcesRestrictions',
2811 'checkActionPermissions',
2812 'checkUserBlock'
2813 ];
2814 } else {
2815 $checks = [
2816 'checkQuickPermissions',
2817 'checkPermissionHooks',
2818 'checkSpecialsAndNSPermissions',
2819 'checkSiteConfigPermissions',
2820 'checkUserConfigPermissions',
2821 'checkPageRestrictions',
2822 'checkCascadingSourcesRestrictions',
2823 'checkActionPermissions',
2824 'checkUserBlock'
2825 ];
2826 }
2827
2828 $errors = [];
2829 while ( count( $checks ) > 0 &&
2830 !( $short && count( $errors ) > 0 ) ) {
2831 $method = array_shift( $checks );
2832 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2833 }
2834
2835 return $errors;
2836 }
2837
2838 /**
2839 * Get a filtered list of all restriction types supported by this wiki.
2840 * @param bool $exists True to get all restriction types that apply to
2841 * titles that do exist, False for all restriction types that apply to
2842 * titles that do not exist
2843 * @return array
2844 */
2845 public static function getFilteredRestrictionTypes( $exists = true ) {
2846 global $wgRestrictionTypes;
2847 $types = $wgRestrictionTypes;
2848 if ( $exists ) {
2849 # Remove the create restriction for existing titles
2850 $types = array_diff( $types, [ 'create' ] );
2851 } else {
2852 # Only the create and upload restrictions apply to non-existing titles
2853 $types = array_intersect( $types, [ 'create', 'upload' ] );
2854 }
2855 return $types;
2856 }
2857
2858 /**
2859 * Returns restriction types for the current Title
2860 *
2861 * @return array Applicable restriction types
2862 */
2863 public function getRestrictionTypes() {
2864 if ( $this->isSpecialPage() ) {
2865 return [];
2866 }
2867
2868 $types = self::getFilteredRestrictionTypes( $this->exists() );
2869
2870 if ( $this->mNamespace != NS_FILE ) {
2871 # Remove the upload restriction for non-file titles
2872 $types = array_diff( $types, [ 'upload' ] );
2873 }
2874
2875 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2876
2877 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2878 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2879
2880 return $types;
2881 }
2882
2883 /**
2884 * Is this title subject to title protection?
2885 * Title protection is the one applied against creation of such title.
2886 *
2887 * @return array|bool An associative array representing any existent title
2888 * protection, or false if there's none.
2889 */
2890 public function getTitleProtection() {
2891 $protection = $this->getTitleProtectionInternal();
2892 if ( $protection ) {
2893 if ( $protection['permission'] == 'sysop' ) {
2894 $protection['permission'] = 'editprotected'; // B/C
2895 }
2896 if ( $protection['permission'] == 'autoconfirmed' ) {
2897 $protection['permission'] = 'editsemiprotected'; // B/C
2898 }
2899 }
2900 return $protection;
2901 }
2902
2903 /**
2904 * Fetch title protection settings
2905 *
2906 * To work correctly, $this->loadRestrictions() needs to have access to the
2907 * actual protections in the database without munging 'sysop' =>
2908 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2909 * callers probably want $this->getTitleProtection() instead.
2910 *
2911 * @return array|bool
2912 */
2913 protected function getTitleProtectionInternal() {
2914 // Can't protect pages in special namespaces
2915 if ( $this->mNamespace < 0 ) {
2916 return false;
2917 }
2918
2919 // Can't protect pages that exist.
2920 if ( $this->exists() ) {
2921 return false;
2922 }
2923
2924 if ( $this->mTitleProtection === null ) {
2925 $dbr = wfGetDB( DB_REPLICA );
2926 $commentStore = CommentStore::getStore();
2927 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2928 $res = $dbr->select(
2929 [ 'protected_titles' ] + $commentQuery['tables'],
2930 [
2931 'user' => 'pt_user',
2932 'expiry' => 'pt_expiry',
2933 'permission' => 'pt_create_perm'
2934 ] + $commentQuery['fields'],
2935 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2936 __METHOD__,
2937 [],
2938 $commentQuery['joins']
2939 );
2940
2941 // fetchRow returns false if there are no rows.
2942 $row = $dbr->fetchRow( $res );
2943 if ( $row ) {
2944 $this->mTitleProtection = [
2945 'user' => $row['user'],
2946 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2947 'permission' => $row['permission'],
2948 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
2949 ];
2950 } else {
2951 $this->mTitleProtection = false;
2952 }
2953 }
2954 return $this->mTitleProtection;
2955 }
2956
2957 /**
2958 * Remove any title protection due to page existing
2959 */
2960 public function deleteTitleProtection() {
2961 $dbw = wfGetDB( DB_MASTER );
2962
2963 $dbw->delete(
2964 'protected_titles',
2965 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2966 __METHOD__
2967 );
2968 $this->mTitleProtection = false;
2969 }
2970
2971 /**
2972 * Is this page "semi-protected" - the *only* protection levels are listed
2973 * in $wgSemiprotectedRestrictionLevels?
2974 *
2975 * @param string $action Action to check (default: edit)
2976 * @return bool
2977 */
2978 public function isSemiProtected( $action = 'edit' ) {
2979 global $wgSemiprotectedRestrictionLevels;
2980
2981 $restrictions = $this->getRestrictions( $action );
2982 $semi = $wgSemiprotectedRestrictionLevels;
2983 if ( !$restrictions || !$semi ) {
2984 // Not protected, or all protection is full protection
2985 return false;
2986 }
2987
2988 // Remap autoconfirmed to editsemiprotected for BC
2989 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2990 $semi[$key] = 'editsemiprotected';
2991 }
2992 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2993 $restrictions[$key] = 'editsemiprotected';
2994 }
2995
2996 return !array_diff( $restrictions, $semi );
2997 }
2998
2999 /**
3000 * Does the title correspond to a protected article?
3001 *
3002 * @param string $action The action the page is protected from,
3003 * by default checks all actions.
3004 * @return bool
3005 */
3006 public function isProtected( $action = '' ) {
3007 global $wgRestrictionLevels;
3008
3009 $restrictionTypes = $this->getRestrictionTypes();
3010
3011 # Special pages have inherent protection
3012 if ( $this->isSpecialPage() ) {
3013 return true;
3014 }
3015
3016 # Check regular protection levels
3017 foreach ( $restrictionTypes as $type ) {
3018 if ( $action == $type || $action == '' ) {
3019 $r = $this->getRestrictions( $type );
3020 foreach ( $wgRestrictionLevels as $level ) {
3021 if ( in_array( $level, $r ) && $level != '' ) {
3022 return true;
3023 }
3024 }
3025 }
3026 }
3027
3028 return false;
3029 }
3030
3031 /**
3032 * Determines if $user is unable to edit this page because it has been protected
3033 * by $wgNamespaceProtection.
3034 *
3035 * @param User $user User object to check permissions
3036 * @return bool
3037 */
3038 public function isNamespaceProtected( User $user ) {
3039 global $wgNamespaceProtection;
3040
3041 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
3042 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
3043 if ( $right != '' && !$user->isAllowed( $right ) ) {
3044 return true;
3045 }
3046 }
3047 }
3048 return false;
3049 }
3050
3051 /**
3052 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3053 *
3054 * @return bool If the page is subject to cascading restrictions.
3055 */
3056 public function isCascadeProtected() {
3057 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3058 return ( $sources > 0 );
3059 }
3060
3061 /**
3062 * Determines whether cascading protection sources have already been loaded from
3063 * the database.
3064 *
3065 * @param bool $getPages True to check if the pages are loaded, or false to check
3066 * if the status is loaded.
3067 * @return bool Whether or not the specified information has been loaded
3068 * @since 1.23
3069 */
3070 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3071 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
3072 }
3073
3074 /**
3075 * Cascading protection: Get the source of any cascading restrictions on this page.
3076 *
3077 * @param bool $getPages Whether or not to retrieve the actual pages
3078 * that the restrictions have come from and the actual restrictions
3079 * themselves.
3080 * @return array Two elements: First is an array of Title objects of the
3081 * pages from which cascading restrictions have come, false for
3082 * none, or true if such restrictions exist but $getPages was not
3083 * set. Second is an array like that returned by
3084 * Title::getAllRestrictions(), or an empty array if $getPages is
3085 * false.
3086 */
3087 public function getCascadeProtectionSources( $getPages = true ) {
3088 $pagerestrictions = [];
3089
3090 if ( $this->mCascadeSources !== null && $getPages ) {
3091 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
3092 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
3093 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
3094 }
3095
3096 $dbr = wfGetDB( DB_REPLICA );
3097
3098 if ( $this->mNamespace == NS_FILE ) {
3099 $tables = [ 'imagelinks', 'page_restrictions' ];
3100 $where_clauses = [
3101 'il_to' => $this->mDbkeyform,
3102 'il_from=pr_page',
3103 'pr_cascade' => 1
3104 ];
3105 } else {
3106 $tables = [ 'templatelinks', 'page_restrictions' ];
3107 $where_clauses = [
3108 'tl_namespace' => $this->mNamespace,
3109 'tl_title' => $this->mDbkeyform,
3110 'tl_from=pr_page',
3111 'pr_cascade' => 1
3112 ];
3113 }
3114
3115 if ( $getPages ) {
3116 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3117 'pr_expiry', 'pr_type', 'pr_level' ];
3118 $where_clauses[] = 'page_id=pr_page';
3119 $tables[] = 'page';
3120 } else {
3121 $cols = [ 'pr_expiry' ];
3122 }
3123
3124 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
3125
3126 $sources = $getPages ? [] : false;
3127 $now = wfTimestampNow();
3128
3129 foreach ( $res as $row ) {
3130 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3131 if ( $expiry > $now ) {
3132 if ( $getPages ) {
3133 $page_id = $row->pr_page;
3134 $page_ns = $row->page_namespace;
3135 $page_title = $row->page_title;
3136 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
3137 # Add groups needed for each restriction type if its not already there
3138 # Make sure this restriction type still exists
3139
3140 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
3141 $pagerestrictions[$row->pr_type] = [];
3142 }
3143
3144 if (
3145 isset( $pagerestrictions[$row->pr_type] )
3146 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
3147 ) {
3148 $pagerestrictions[$row->pr_type][] = $row->pr_level;
3149 }
3150 } else {
3151 $sources = true;
3152 }
3153 }
3154 }
3155
3156 if ( $getPages ) {
3157 $this->mCascadeSources = $sources;
3158 $this->mCascadingRestrictions = $pagerestrictions;
3159 } else {
3160 $this->mHasCascadingRestrictions = $sources;
3161 }
3162
3163 return [ $sources, $pagerestrictions ];
3164 }
3165
3166 /**
3167 * Accessor for mRestrictionsLoaded
3168 *
3169 * @return bool Whether or not the page's restrictions have already been
3170 * loaded from the database
3171 * @since 1.23
3172 */
3173 public function areRestrictionsLoaded() {
3174 return $this->mRestrictionsLoaded;
3175 }
3176
3177 /**
3178 * Accessor/initialisation for mRestrictions
3179 *
3180 * @param string $action Action that permission needs to be checked for
3181 * @return array Restriction levels needed to take the action. All levels are
3182 * required. Note that restriction levels are normally user rights, but 'sysop'
3183 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3184 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3185 */
3186 public function getRestrictions( $action ) {
3187 if ( !$this->mRestrictionsLoaded ) {
3188 $this->loadRestrictions();
3189 }
3190 return $this->mRestrictions[$action] ?? [];
3191 }
3192
3193 /**
3194 * Accessor/initialisation for mRestrictions
3195 *
3196 * @return array Keys are actions, values are arrays as returned by
3197 * Title::getRestrictions()
3198 * @since 1.23
3199 */
3200 public function getAllRestrictions() {
3201 if ( !$this->mRestrictionsLoaded ) {
3202 $this->loadRestrictions();
3203 }
3204 return $this->mRestrictions;
3205 }
3206
3207 /**
3208 * Get the expiry time for the restriction against a given action
3209 *
3210 * @param string $action
3211 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3212 * or not protected at all, or false if the action is not recognised.
3213 */
3214 public function getRestrictionExpiry( $action ) {
3215 if ( !$this->mRestrictionsLoaded ) {
3216 $this->loadRestrictions();
3217 }
3218 return $this->mRestrictionsExpiry[$action] ?? false;
3219 }
3220
3221 /**
3222 * Returns cascading restrictions for the current article
3223 *
3224 * @return bool
3225 */
3226 function areRestrictionsCascading() {
3227 if ( !$this->mRestrictionsLoaded ) {
3228 $this->loadRestrictions();
3229 }
3230
3231 return $this->mCascadeRestriction;
3232 }
3233
3234 /**
3235 * Compiles list of active page restrictions from both page table (pre 1.10)
3236 * and page_restrictions table for this existing page.
3237 * Public for usage by LiquidThreads.
3238 *
3239 * @param array $rows Array of db result objects
3240 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3241 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3242 * Edit and move sections are separated by a colon
3243 * Example: "edit=autoconfirmed,sysop:move=sysop"
3244 */
3245 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3246 $dbr = wfGetDB( DB_REPLICA );
3247
3248 $restrictionTypes = $this->getRestrictionTypes();
3249
3250 foreach ( $restrictionTypes as $type ) {
3251 $this->mRestrictions[$type] = [];
3252 $this->mRestrictionsExpiry[$type] = 'infinity';
3253 }
3254
3255 $this->mCascadeRestriction = false;
3256
3257 # Backwards-compatibility: also load the restrictions from the page record (old format).
3258 if ( $oldFashionedRestrictions !== null ) {
3259 $this->mOldRestrictions = $oldFashionedRestrictions;
3260 }
3261
3262 if ( $this->mOldRestrictions === false ) {
3263 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
3264 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
3265 }
3266
3267 if ( $this->mOldRestrictions != '' ) {
3268 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
3269 $temp = explode( '=', trim( $restrict ) );
3270 if ( count( $temp ) == 1 ) {
3271 // old old format should be treated as edit/move restriction
3272 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
3273 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
3274 } else {
3275 $restriction = trim( $temp[1] );
3276 if ( $restriction != '' ) { // some old entries are empty
3277 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
3278 }
3279 }
3280 }
3281 }
3282
3283 if ( count( $rows ) ) {
3284 # Current system - load second to make them override.
3285 $now = wfTimestampNow();
3286
3287 # Cycle through all the restrictions.
3288 foreach ( $rows as $row ) {
3289 // Don't take care of restrictions types that aren't allowed
3290 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
3291 continue;
3292 }
3293
3294 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3295
3296 // Only apply the restrictions if they haven't expired!
3297 if ( !$expiry || $expiry > $now ) {
3298 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
3299 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
3300
3301 $this->mCascadeRestriction |= $row->pr_cascade;
3302 }
3303 }
3304 }
3305
3306 $this->mRestrictionsLoaded = true;
3307 }
3308
3309 /**
3310 * Load restrictions from the page_restrictions table
3311 *
3312 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3313 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3314 * Edit and move sections are separated by a colon
3315 * Example: "edit=autoconfirmed,sysop:move=sysop"
3316 */
3317 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3318 if ( $this->mRestrictionsLoaded ) {
3319 return;
3320 }
3321
3322 $id = $this->getArticleID();
3323 if ( $id ) {
3324 $cache = ObjectCache::getMainWANInstance();
3325 $rows = $cache->getWithSetCallback(
3326 // Page protections always leave a new null revision
3327 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3328 $cache::TTL_DAY,
3329 function ( $curValue, &$ttl, array &$setOpts ) {
3330 $dbr = wfGetDB( DB_REPLICA );
3331
3332 $setOpts += Database::getCacheSetOptions( $dbr );
3333
3334 return iterator_to_array(
3335 $dbr->select(
3336 'page_restrictions',
3337 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3338 [ 'pr_page' => $this->getArticleID() ],
3339 __METHOD__
3340 )
3341 );
3342 }
3343 );
3344
3345 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3346 } else {
3347 $title_protection = $this->getTitleProtectionInternal();
3348
3349 if ( $title_protection ) {
3350 $now = wfTimestampNow();
3351 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3352
3353 if ( !$expiry || $expiry > $now ) {
3354 // Apply the restrictions
3355 $this->mRestrictionsExpiry['create'] = $expiry;
3356 $this->mRestrictions['create'] =
3357 explode( ',', trim( $title_protection['permission'] ) );
3358 } else { // Get rid of the old restrictions
3359 $this->mTitleProtection = false;
3360 }
3361 } else {
3362 $this->mRestrictionsExpiry['create'] = 'infinity';
3363 }
3364 $this->mRestrictionsLoaded = true;
3365 }
3366 }
3367
3368 /**
3369 * Flush the protection cache in this object and force reload from the database.
3370 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3371 */
3372 public function flushRestrictions() {
3373 $this->mRestrictionsLoaded = false;
3374 $this->mTitleProtection = null;
3375 }
3376
3377 /**
3378 * Purge expired restrictions from the page_restrictions table
3379 *
3380 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3381 */
3382 static function purgeExpiredRestrictions() {
3383 if ( wfReadOnly() ) {
3384 return;
3385 }
3386
3387 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3388 wfGetDB( DB_MASTER ),
3389 __METHOD__,
3390 function ( IDatabase $dbw, $fname ) {
3391 $config = MediaWikiServices::getInstance()->getMainConfig();
3392 $ids = $dbw->selectFieldValues(
3393 'page_restrictions',
3394 'pr_id',
3395 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3396 $fname,
3397 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3398 );
3399 if ( $ids ) {
3400 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3401 }
3402 }
3403 ) );
3404
3405 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3406 wfGetDB( DB_MASTER ),
3407 __METHOD__,
3408 function ( IDatabase $dbw, $fname ) {
3409 $dbw->delete(
3410 'protected_titles',
3411 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3412 $fname
3413 );
3414 }
3415 ) );
3416 }
3417
3418 /**
3419 * Does this have subpages? (Warning, usually requires an extra DB query.)
3420 *
3421 * @return bool
3422 */
3423 public function hasSubpages() {
3424 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3425 # Duh
3426 return false;
3427 }
3428
3429 # We dynamically add a member variable for the purpose of this method
3430 # alone to cache the result. There's no point in having it hanging
3431 # around uninitialized in every Title object; therefore we only add it
3432 # if needed and don't declare it statically.
3433 if ( $this->mHasSubpages === null ) {
3434 $this->mHasSubpages = false;
3435 $subpages = $this->getSubpages( 1 );
3436 if ( $subpages instanceof TitleArray ) {
3437 $this->mHasSubpages = (bool)$subpages->count();
3438 }
3439 }
3440
3441 return $this->mHasSubpages;
3442 }
3443
3444 /**
3445 * Get all subpages of this page.
3446 *
3447 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3448 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3449 * doesn't allow subpages
3450 */
3451 public function getSubpages( $limit = -1 ) {
3452 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3453 return [];
3454 }
3455
3456 $dbr = wfGetDB( DB_REPLICA );
3457 $conds['page_namespace'] = $this->mNamespace;
3458 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3459 $options = [];
3460 if ( $limit > -1 ) {
3461 $options['LIMIT'] = $limit;
3462 }
3463 return TitleArray::newFromResult(
3464 $dbr->select( 'page',
3465 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3466 $conds,
3467 __METHOD__,
3468 $options
3469 )
3470 );
3471 }
3472
3473 /**
3474 * Is there a version of this page in the deletion archive?
3475 *
3476 * @return int The number of archived revisions
3477 */
3478 public function isDeleted() {
3479 if ( $this->mNamespace < 0 ) {
3480 $n = 0;
3481 } else {
3482 $dbr = wfGetDB( DB_REPLICA );
3483
3484 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3485 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3486 __METHOD__
3487 );
3488 if ( $this->mNamespace == NS_FILE ) {
3489 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3490 [ 'fa_name' => $this->mDbkeyform ],
3491 __METHOD__
3492 );
3493 }
3494 }
3495 return (int)$n;
3496 }
3497
3498 /**
3499 * Is there a version of this page in the deletion archive?
3500 *
3501 * @return bool
3502 */
3503 public function isDeletedQuick() {
3504 if ( $this->mNamespace < 0 ) {
3505 return false;
3506 }
3507 $dbr = wfGetDB( DB_REPLICA );
3508 $deleted = (bool)$dbr->selectField( 'archive', '1',
3509 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3510 __METHOD__
3511 );
3512 if ( !$deleted && $this->mNamespace == NS_FILE ) {
3513 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3514 [ 'fa_name' => $this->mDbkeyform ],
3515 __METHOD__
3516 );
3517 }
3518 return $deleted;
3519 }
3520
3521 /**
3522 * Get the article ID for this Title from the link cache,
3523 * adding it if necessary
3524 *
3525 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3526 * for update
3527 * @return int The ID
3528 */
3529 public function getArticleID( $flags = 0 ) {
3530 if ( $this->mNamespace < 0 ) {
3531 $this->mArticleID = 0;
3532 return $this->mArticleID;
3533 }
3534 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3535 if ( $flags & self::GAID_FOR_UPDATE ) {
3536 $oldUpdate = $linkCache->forUpdate( true );
3537 $linkCache->clearLink( $this );
3538 $this->mArticleID = $linkCache->addLinkObj( $this );
3539 $linkCache->forUpdate( $oldUpdate );
3540 } else {
3541 if ( -1 == $this->mArticleID ) {
3542 $this->mArticleID = $linkCache->addLinkObj( $this );
3543 }
3544 }
3545 return $this->mArticleID;
3546 }
3547
3548 /**
3549 * Is this an article that is a redirect page?
3550 * Uses link cache, adding it if necessary
3551 *
3552 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3553 * @return bool
3554 */
3555 public function isRedirect( $flags = 0 ) {
3556 if ( !is_null( $this->mRedirect ) ) {
3557 return $this->mRedirect;
3558 }
3559 if ( !$this->getArticleID( $flags ) ) {
3560 $this->mRedirect = false;
3561 return $this->mRedirect;
3562 }
3563
3564 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3565 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3566 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3567 if ( $cached === null ) {
3568 # Trust LinkCache's state over our own
3569 # LinkCache is telling us that the page doesn't exist, despite there being cached
3570 # data relating to an existing page in $this->mArticleID. Updaters should clear
3571 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3572 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3573 # LinkCache to refresh its data from the master.
3574 $this->mRedirect = false;
3575 return $this->mRedirect;
3576 }
3577
3578 $this->mRedirect = (bool)$cached;
3579
3580 return $this->mRedirect;
3581 }
3582
3583 /**
3584 * What is the length of this page?
3585 * Uses link cache, adding it if necessary
3586 *
3587 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3588 * @return int
3589 */
3590 public function getLength( $flags = 0 ) {
3591 if ( $this->mLength != -1 ) {
3592 return $this->mLength;
3593 }
3594 if ( !$this->getArticleID( $flags ) ) {
3595 $this->mLength = 0;
3596 return $this->mLength;
3597 }
3598 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3599 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3600 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3601 if ( $cached === null ) {
3602 # Trust LinkCache's state over our own, as for isRedirect()
3603 $this->mLength = 0;
3604 return $this->mLength;
3605 }
3606
3607 $this->mLength = intval( $cached );
3608
3609 return $this->mLength;
3610 }
3611
3612 /**
3613 * What is the page_latest field for this page?
3614 *
3615 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3616 * @return int Int or 0 if the page doesn't exist
3617 */
3618 public function getLatestRevID( $flags = 0 ) {
3619 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3620 return intval( $this->mLatestID );
3621 }
3622 if ( !$this->getArticleID( $flags ) ) {
3623 $this->mLatestID = 0;
3624 return $this->mLatestID;
3625 }
3626 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3627 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3628 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3629 if ( $cached === null ) {
3630 # Trust LinkCache's state over our own, as for isRedirect()
3631 $this->mLatestID = 0;
3632 return $this->mLatestID;
3633 }
3634
3635 $this->mLatestID = intval( $cached );
3636
3637 return $this->mLatestID;
3638 }
3639
3640 /**
3641 * This clears some fields in this object, and clears any associated
3642 * keys in the "bad links" section of the link cache.
3643 *
3644 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3645 * loading of the new page_id. It's also called from
3646 * WikiPage::doDeleteArticleReal()
3647 *
3648 * @param int $newid The new Article ID
3649 */
3650 public function resetArticleID( $newid ) {
3651 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3652 $linkCache->clearLink( $this );
3653
3654 if ( $newid === false ) {
3655 $this->mArticleID = -1;
3656 } else {
3657 $this->mArticleID = intval( $newid );
3658 }
3659 $this->mRestrictionsLoaded = false;
3660 $this->mRestrictions = [];
3661 $this->mOldRestrictions = false;
3662 $this->mRedirect = null;
3663 $this->mLength = -1;
3664 $this->mLatestID = false;
3665 $this->mContentModel = false;
3666 $this->mEstimateRevisions = null;
3667 $this->mPageLanguage = false;
3668 $this->mDbPageLanguage = false;
3669 $this->mIsBigDeletion = null;
3670 }
3671
3672 public static function clearCaches() {
3673 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3674 $linkCache->clear();
3675
3676 $titleCache = self::getTitleCache();
3677 $titleCache->clear();
3678 }
3679
3680 /**
3681 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3682 *
3683 * @param string $text Containing title to capitalize
3684 * @param int $ns Namespace index, defaults to NS_MAIN
3685 * @return string Containing capitalized title
3686 */
3687 public static function capitalize( $text, $ns = NS_MAIN ) {
3688 if ( MWNamespace::isCapitalized( $ns ) ) {
3689 return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text );
3690 } else {
3691 return $text;
3692 }
3693 }
3694
3695 /**
3696 * Secure and split - main initialisation function for this object
3697 *
3698 * Assumes that mDbkeyform has been set, and is urldecoded
3699 * and uses underscores, but not otherwise munged. This function
3700 * removes illegal characters, splits off the interwiki and
3701 * namespace prefixes, sets the other forms, and canonicalizes
3702 * everything.
3703 *
3704 * @throws MalformedTitleException On invalid titles
3705 * @return bool True on success
3706 */
3707 private function secureAndSplit() {
3708 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3709 // the parsing code with Title, while avoiding massive refactoring.
3710 // @todo: get rid of secureAndSplit, refactor parsing code.
3711 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3712 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3713 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3714 // MalformedTitleException can be thrown here
3715 $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
3716
3717 # Fill fields
3718 $this->setFragment( '#' . $parts['fragment'] );
3719 $this->mInterwiki = $parts['interwiki'];
3720 $this->mLocalInterwiki = $parts['local_interwiki'];
3721 $this->mNamespace = $parts['namespace'];
3722 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3723
3724 $this->mDbkeyform = $parts['dbkey'];
3725 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3726 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3727
3728 # We already know that some pages won't be in the database!
3729 if ( $this->isExternal() || $this->isSpecialPage() ) {
3730 $this->mArticleID = 0;
3731 }
3732
3733 return true;
3734 }
3735
3736 /**
3737 * Get an array of Title objects linking to this Title
3738 * Also stores the IDs in the link cache.
3739 *
3740 * WARNING: do not use this function on arbitrary user-supplied titles!
3741 * On heavily-used templates it will max out the memory.
3742 *
3743 * @param array $options May be FOR UPDATE
3744 * @param string $table Table name
3745 * @param string $prefix Fields prefix
3746 * @return Title[] Array of Title objects linking here
3747 */
3748 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3749 if ( count( $options ) > 0 ) {
3750 $db = wfGetDB( DB_MASTER );
3751 } else {
3752 $db = wfGetDB( DB_REPLICA );
3753 }
3754
3755 $res = $db->select(
3756 [ 'page', $table ],
3757 self::getSelectFields(),
3758 [
3759 "{$prefix}_from=page_id",
3760 "{$prefix}_namespace" => $this->mNamespace,
3761 "{$prefix}_title" => $this->mDbkeyform ],
3762 __METHOD__,
3763 $options
3764 );
3765
3766 $retVal = [];
3767 if ( $res->numRows() ) {
3768 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3769 foreach ( $res as $row ) {
3770 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3771 if ( $titleObj ) {
3772 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3773 $retVal[] = $titleObj;
3774 }
3775 }
3776 }
3777 return $retVal;
3778 }
3779
3780 /**
3781 * Get an array of Title objects using this Title as a template
3782 * Also stores the IDs in the link cache.
3783 *
3784 * WARNING: do not use this function on arbitrary user-supplied titles!
3785 * On heavily-used templates it will max out the memory.
3786 *
3787 * @param array $options Query option to Database::select()
3788 * @return Title[] Array of Title the Title objects linking here
3789 */
3790 public function getTemplateLinksTo( $options = [] ) {
3791 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3792 }
3793
3794 /**
3795 * Get an array of Title objects linked from this Title
3796 * Also stores the IDs in the link cache.
3797 *
3798 * WARNING: do not use this function on arbitrary user-supplied titles!
3799 * On heavily-used templates it will max out the memory.
3800 *
3801 * @param array $options Query option to Database::select()
3802 * @param string $table Table name
3803 * @param string $prefix Fields prefix
3804 * @return array Array of Title objects linking here
3805 */
3806 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3807 $id = $this->getArticleID();
3808
3809 # If the page doesn't exist; there can't be any link from this page
3810 if ( !$id ) {
3811 return [];
3812 }
3813
3814 $db = wfGetDB( DB_REPLICA );
3815
3816 $blNamespace = "{$prefix}_namespace";
3817 $blTitle = "{$prefix}_title";
3818
3819 $pageQuery = WikiPage::getQueryInfo();
3820 $res = $db->select(
3821 [ $table, 'nestpage' => $pageQuery['tables'] ],
3822 array_merge(
3823 [ $blNamespace, $blTitle ],
3824 $pageQuery['fields']
3825 ),
3826 [ "{$prefix}_from" => $id ],
3827 __METHOD__,
3828 $options,
3829 [ 'nestpage' => [
3830 'LEFT JOIN',
3831 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3832 ] ] + $pageQuery['joins']
3833 );
3834
3835 $retVal = [];
3836 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3837 foreach ( $res as $row ) {
3838 if ( $row->page_id ) {
3839 $titleObj = self::newFromRow( $row );
3840 } else {
3841 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3842 $linkCache->addBadLinkObj( $titleObj );
3843 }
3844 $retVal[] = $titleObj;
3845 }
3846
3847 return $retVal;
3848 }
3849
3850 /**
3851 * Get an array of Title objects used on this Title as a template
3852 * Also stores the IDs in the link cache.
3853 *
3854 * WARNING: do not use this function on arbitrary user-supplied titles!
3855 * On heavily-used templates it will max out the memory.
3856 *
3857 * @param array $options May be FOR UPDATE
3858 * @return Title[] Array of Title the Title objects used here
3859 */
3860 public function getTemplateLinksFrom( $options = [] ) {
3861 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3862 }
3863
3864 /**
3865 * Get an array of Title objects referring to non-existent articles linked
3866 * from this page.
3867 *
3868 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3869 * should use redirect table in this case).
3870 * @return Title[] Array of Title the Title objects
3871 */
3872 public function getBrokenLinksFrom() {
3873 if ( $this->getArticleID() == 0 ) {
3874 # All links from article ID 0 are false positives
3875 return [];
3876 }
3877
3878 $dbr = wfGetDB( DB_REPLICA );
3879 $res = $dbr->select(
3880 [ 'page', 'pagelinks' ],
3881 [ 'pl_namespace', 'pl_title' ],
3882 [
3883 'pl_from' => $this->getArticleID(),
3884 'page_namespace IS NULL'
3885 ],
3886 __METHOD__, [],
3887 [
3888 'page' => [
3889 'LEFT JOIN',
3890 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3891 ]
3892 ]
3893 );
3894
3895 $retVal = [];
3896 foreach ( $res as $row ) {
3897 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3898 }
3899 return $retVal;
3900 }
3901
3902 /**
3903 * Get a list of URLs to purge from the CDN cache when this
3904 * page changes
3905 *
3906 * @return string[] Array of String the URLs
3907 */
3908 public function getCdnUrls() {
3909 $urls = [
3910 $this->getInternalURL(),
3911 $this->getInternalURL( 'action=history' )
3912 ];
3913
3914 $pageLang = $this->getPageLanguage();
3915 if ( $pageLang->hasVariants() ) {
3916 $variants = $pageLang->getVariants();
3917 foreach ( $variants as $vCode ) {
3918 $urls[] = $this->getInternalURL( $vCode );
3919 }
3920 }
3921
3922 // If we are looking at a css/js user subpage, purge the action=raw.
3923 if ( $this->isUserJsConfigPage() ) {
3924 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3925 } elseif ( $this->isUserJsonConfigPage() ) {
3926 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3927 } elseif ( $this->isUserCssConfigPage() ) {
3928 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3929 }
3930
3931 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3932 return $urls;
3933 }
3934
3935 /**
3936 * @deprecated since 1.27 use getCdnUrls()
3937 */
3938 public function getSquidURLs() {
3939 return $this->getCdnUrls();
3940 }
3941
3942 /**
3943 * Purge all applicable CDN URLs
3944 */
3945 public function purgeSquid() {
3946 DeferredUpdates::addUpdate(
3947 new CdnCacheUpdate( $this->getCdnUrls() ),
3948 DeferredUpdates::PRESEND
3949 );
3950 }
3951
3952 /**
3953 * Check whether a given move operation would be valid.
3954 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3955 *
3956 * @deprecated since 1.25, use MovePage's methods instead
3957 * @param Title &$nt The new title
3958 * @param bool $auth Whether to check user permissions (uses $wgUser)
3959 * @param string $reason Is the log summary of the move, used for spam checking
3960 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3961 */
3962 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3963 global $wgUser;
3964
3965 if ( !( $nt instanceof Title ) ) {
3966 // Normally we'd add this to $errors, but we'll get
3967 // lots of syntax errors if $nt is not an object
3968 return [ [ 'badtitletext' ] ];
3969 }
3970
3971 $mp = new MovePage( $this, $nt );
3972 $errors = $mp->isValidMove()->getErrorsArray();
3973 if ( $auth ) {
3974 $errors = wfMergeErrorArrays(
3975 $errors,
3976 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3977 );
3978 }
3979
3980 return $errors ?: true;
3981 }
3982
3983 /**
3984 * Check if the requested move target is a valid file move target
3985 * @todo move this to MovePage
3986 * @param Title $nt Target title
3987 * @return array List of errors
3988 */
3989 protected function validateFileMoveOperation( $nt ) {
3990 global $wgUser;
3991
3992 $errors = [];
3993
3994 $destFile = wfLocalFile( $nt );
3995 $destFile->load( File::READ_LATEST );
3996 if ( !$wgUser->isAllowed( 'reupload-shared' )
3997 && !$destFile->exists() && wfFindFile( $nt )
3998 ) {
3999 $errors[] = [ 'file-exists-sharedrepo' ];
4000 }
4001
4002 return $errors;
4003 }
4004
4005 /**
4006 * Move a title to a new location
4007 *
4008 * @deprecated since 1.25, use the MovePage class instead
4009 * @param Title &$nt The new title
4010 * @param bool $auth Indicates whether $wgUser's permissions
4011 * should be checked
4012 * @param string $reason The reason for the move
4013 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4014 * Ignored if the user doesn't have the suppressredirect right.
4015 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4016 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4017 */
4018 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4019 array $changeTags = []
4020 ) {
4021 global $wgUser;
4022 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4023 if ( is_array( $err ) ) {
4024 // Auto-block user's IP if the account was "hard" blocked
4025 $wgUser->spreadAnyEditBlock();
4026 return $err;
4027 }
4028 // Check suppressredirect permission
4029 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4030 $createRedirect = true;
4031 }
4032
4033 $mp = new MovePage( $this, $nt );
4034 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4035 if ( $status->isOK() ) {
4036 return true;
4037 } else {
4038 return $status->getErrorsArray();
4039 }
4040 }
4041
4042 /**
4043 * Move this page's subpages to be subpages of $nt
4044 *
4045 * @param Title $nt Move target
4046 * @param bool $auth Whether $wgUser's permissions should be checked
4047 * @param string $reason The reason for the move
4048 * @param bool $createRedirect Whether to create redirects from the old subpages to
4049 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4050 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4051 * @return array Array with old page titles as keys, and strings (new page titles) or
4052 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4053 * getUserPermissionsErrors()-like error array with numeric indices if
4054 * no pages were moved
4055 */
4056 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4057 array $changeTags = []
4058 ) {
4059 global $wgMaximumMovedPages;
4060 // Check permissions
4061 if ( !$this->userCan( 'move-subpages' ) ) {
4062 return [
4063 [ 'cant-move-subpages' ],
4064 ];
4065 }
4066 // Do the source and target namespaces support subpages?
4067 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
4068 return [
4069 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->mNamespace ) ],
4070 ];
4071 }
4072 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
4073 return [
4074 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
4075 ];
4076 }
4077
4078 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
4079 $retval = [];
4080 $count = 0;
4081 foreach ( $subpages as $oldSubpage ) {
4082 $count++;
4083 if ( $count > $wgMaximumMovedPages ) {
4084 $retval[$oldSubpage->getPrefixedText()] = [
4085 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4086 ];
4087 break;
4088 }
4089
4090 // We don't know whether this function was called before
4091 // or after moving the root page, so check both
4092 // $this and $nt
4093 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4094 || $oldSubpage->getArticleID() == $nt->getArticleID()
4095 ) {
4096 // When moving a page to a subpage of itself,
4097 // don't move it twice
4098 continue;
4099 }
4100 $newPageName = preg_replace(
4101 '#^' . preg_quote( $this->mDbkeyform, '#' ) . '#',
4102 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4103 $oldSubpage->getDBkey() );
4104 if ( $oldSubpage->isTalkPage() ) {
4105 $newNs = $nt->getTalkPage()->getNamespace();
4106 } else {
4107 $newNs = $nt->getSubjectPage()->getNamespace();
4108 }
4109 # T16385: we need makeTitleSafe because the new page names may
4110 # be longer than 255 characters.
4111 $newSubpage = self::makeTitleSafe( $newNs, $newPageName );
4112
4113 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4114 if ( $success === true ) {
4115 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4116 } else {
4117 $retval[$oldSubpage->getPrefixedText()] = $success;
4118 }
4119 }
4120 return $retval;
4121 }
4122
4123 /**
4124 * Checks if this page is just a one-rev redirect.
4125 * Adds lock, so don't use just for light purposes.
4126 *
4127 * @return bool
4128 */
4129 public function isSingleRevRedirect() {
4130 global $wgContentHandlerUseDB;
4131
4132 $dbw = wfGetDB( DB_MASTER );
4133
4134 # Is it a redirect?
4135 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4136 if ( $wgContentHandlerUseDB ) {
4137 $fields[] = 'page_content_model';
4138 }
4139
4140 $row = $dbw->selectRow( 'page',
4141 $fields,
4142 $this->pageCond(),
4143 __METHOD__,
4144 [ 'FOR UPDATE' ]
4145 );
4146 # Cache some fields we may want
4147 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4148 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4149 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4150 $this->mContentModel = $row && isset( $row->page_content_model )
4151 ? strval( $row->page_content_model )
4152 : false;
4153
4154 if ( !$this->mRedirect ) {
4155 return false;
4156 }
4157 # Does the article have a history?
4158 $row = $dbw->selectField( [ 'page', 'revision' ],
4159 'rev_id',
4160 [ 'page_namespace' => $this->mNamespace,
4161 'page_title' => $this->mDbkeyform,
4162 'page_id=rev_page',
4163 'page_latest != rev_id'
4164 ],
4165 __METHOD__,
4166 [ 'FOR UPDATE' ]
4167 );
4168 # Return true if there was no history
4169 return ( $row === false );
4170 }
4171
4172 /**
4173 * Checks if $this can be moved to a given Title
4174 * - Selects for update, so don't call it unless you mean business
4175 *
4176 * @deprecated since 1.25, use MovePage's methods instead
4177 * @param Title $nt The new title to check
4178 * @return bool
4179 */
4180 public function isValidMoveTarget( $nt ) {
4181 # Is it an existing file?
4182 if ( $nt->getNamespace() == NS_FILE ) {
4183 $file = wfLocalFile( $nt );
4184 $file->load( File::READ_LATEST );
4185 if ( $file->exists() ) {
4186 wfDebug( __METHOD__ . ": file exists\n" );
4187 return false;
4188 }
4189 }
4190 # Is it a redirect with no history?
4191 if ( !$nt->isSingleRevRedirect() ) {
4192 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4193 return false;
4194 }
4195 # Get the article text
4196 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4197 if ( !is_object( $rev ) ) {
4198 return false;
4199 }
4200 $content = $rev->getContent();
4201 # Does the redirect point to the source?
4202 # Or is it a broken self-redirect, usually caused by namespace collisions?
4203 $redirTitle = $content ? $content->getRedirectTarget() : null;
4204
4205 if ( $redirTitle ) {
4206 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4207 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4208 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4209 return false;
4210 } else {
4211 return true;
4212 }
4213 } else {
4214 # Fail safe (not a redirect after all. strange.)
4215 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4216 " is a redirect, but it doesn't contain a valid redirect.\n" );
4217 return false;
4218 }
4219 }
4220
4221 /**
4222 * Get categories to which this Title belongs and return an array of
4223 * categories' names.
4224 *
4225 * @return array Array of parents in the form:
4226 * $parent => $currentarticle
4227 */
4228 public function getParentCategories() {
4229 $data = [];
4230
4231 $titleKey = $this->getArticleID();
4232
4233 if ( $titleKey === 0 ) {
4234 return $data;
4235 }
4236
4237 $dbr = wfGetDB( DB_REPLICA );
4238
4239 $res = $dbr->select(
4240 'categorylinks',
4241 'cl_to',
4242 [ 'cl_from' => $titleKey ],
4243 __METHOD__
4244 );
4245
4246 if ( $res->numRows() > 0 ) {
4247 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4248 foreach ( $res as $row ) {
4249 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4250 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
4251 $this->getFullText();
4252 }
4253 }
4254 return $data;
4255 }
4256
4257 /**
4258 * Get a tree of parent categories
4259 *
4260 * @param array $children Array with the children in the keys, to check for circular refs
4261 * @return array Tree of parent categories
4262 */
4263 public function getParentCategoryTree( $children = [] ) {
4264 $stack = [];
4265 $parents = $this->getParentCategories();
4266
4267 if ( $parents ) {
4268 foreach ( $parents as $parent => $current ) {
4269 if ( array_key_exists( $parent, $children ) ) {
4270 # Circular reference
4271 $stack[$parent] = [];
4272 } else {
4273 $nt = self::newFromText( $parent );
4274 if ( $nt ) {
4275 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
4276 }
4277 }
4278 }
4279 }
4280
4281 return $stack;
4282 }
4283
4284 /**
4285 * Get an associative array for selecting this title from
4286 * the "page" table
4287 *
4288 * @return array Array suitable for the $where parameter of DB::select()
4289 */
4290 public function pageCond() {
4291 if ( $this->mArticleID > 0 ) {
4292 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4293 return [ 'page_id' => $this->mArticleID ];
4294 } else {
4295 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
4296 }
4297 }
4298
4299 /**
4300 * Get next/previous revision ID relative to another revision ID
4301 * @param int $revId Revision ID. Get the revision that was before this one.
4302 * @param int $flags Title::GAID_FOR_UPDATE
4303 * @param string $dir 'next' or 'prev'
4304 * @return int|bool New revision ID, or false if none exists
4305 */
4306 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4307 $revId = (int)$revId;
4308 if ( $dir === 'next' ) {
4309 $op = '>';
4310 $sort = 'ASC';
4311 } elseif ( $dir === 'prev' ) {
4312 $op = '<';
4313 $sort = 'DESC';
4314 } else {
4315 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4316 }
4317
4318 if ( $flags & self::GAID_FOR_UPDATE ) {
4319 $db = wfGetDB( DB_MASTER );
4320 } else {
4321 $db = wfGetDB( DB_REPLICA, 'contributions' );
4322 }
4323
4324 // Intentionally not caring if the specified revision belongs to this
4325 // page. We only care about the timestamp.
4326 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ );
4327 if ( $ts === false ) {
4328 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ );
4329 if ( $ts === false ) {
4330 // Or should this throw an InvalidArgumentException or something?
4331 return false;
4332 }
4333 }
4334 $ts = $db->addQuotes( $ts );
4335
4336 $revId = $db->selectField( 'revision', 'rev_id',
4337 [
4338 'rev_page' => $this->getArticleID( $flags ),
4339 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4340 ],
4341 __METHOD__,
4342 [
4343 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4344 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4345 ]
4346 );
4347
4348 if ( $revId === false ) {
4349 return false;
4350 } else {
4351 return intval( $revId );
4352 }
4353 }
4354
4355 /**
4356 * Get the revision ID of the previous revision
4357 *
4358 * @param int $revId Revision ID. Get the revision that was before this one.
4359 * @param int $flags Title::GAID_FOR_UPDATE
4360 * @return int|bool Old revision ID, or false if none exists
4361 */
4362 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4363 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4364 }
4365
4366 /**
4367 * Get the revision ID of the next revision
4368 *
4369 * @param int $revId Revision ID. Get the revision that was after this one.
4370 * @param int $flags Title::GAID_FOR_UPDATE
4371 * @return int|bool Next revision ID, or false if none exists
4372 */
4373 public function getNextRevisionID( $revId, $flags = 0 ) {
4374 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4375 }
4376
4377 /**
4378 * Get the first revision of the page
4379 *
4380 * @param int $flags Title::GAID_FOR_UPDATE
4381 * @return Revision|null If page doesn't exist
4382 */
4383 public function getFirstRevision( $flags = 0 ) {
4384 $pageId = $this->getArticleID( $flags );
4385 if ( $pageId ) {
4386 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4387 $revQuery = Revision::getQueryInfo();
4388 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4389 [ 'rev_page' => $pageId ],
4390 __METHOD__,
4391 [
4392 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4393 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4394 ],
4395 $revQuery['joins']
4396 );
4397 if ( $row ) {
4398 return new Revision( $row );
4399 }
4400 }
4401 return null;
4402 }
4403
4404 /**
4405 * Get the oldest revision timestamp of this page
4406 *
4407 * @param int $flags Title::GAID_FOR_UPDATE
4408 * @return string MW timestamp
4409 */
4410 public function getEarliestRevTime( $flags = 0 ) {
4411 $rev = $this->getFirstRevision( $flags );
4412 return $rev ? $rev->getTimestamp() : null;
4413 }
4414
4415 /**
4416 * Check if this is a new page
4417 *
4418 * @return bool
4419 */
4420 public function isNewPage() {
4421 $dbr = wfGetDB( DB_REPLICA );
4422 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4423 }
4424
4425 /**
4426 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4427 *
4428 * @return bool
4429 */
4430 public function isBigDeletion() {
4431 global $wgDeleteRevisionsLimit;
4432
4433 if ( !$wgDeleteRevisionsLimit ) {
4434 return false;
4435 }
4436
4437 if ( $this->mIsBigDeletion === null ) {
4438 $dbr = wfGetDB( DB_REPLICA );
4439
4440 $revCount = $dbr->selectRowCount(
4441 'revision',
4442 '1',
4443 [ 'rev_page' => $this->getArticleID() ],
4444 __METHOD__,
4445 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4446 );
4447
4448 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4449 }
4450
4451 return $this->mIsBigDeletion;
4452 }
4453
4454 /**
4455 * Get the approximate revision count of this page.
4456 *
4457 * @return int
4458 */
4459 public function estimateRevisionCount() {
4460 if ( !$this->exists() ) {
4461 return 0;
4462 }
4463
4464 if ( $this->mEstimateRevisions === null ) {
4465 $dbr = wfGetDB( DB_REPLICA );
4466 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4467 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4468 }
4469
4470 return $this->mEstimateRevisions;
4471 }
4472
4473 /**
4474 * Get the number of revisions between the given revision.
4475 * Used for diffs and other things that really need it.
4476 *
4477 * @param int|Revision $old Old revision or rev ID (first before range)
4478 * @param int|Revision $new New revision or rev ID (first after range)
4479 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4480 * @return int Number of revisions between these revisions.
4481 */
4482 public function countRevisionsBetween( $old, $new, $max = null ) {
4483 if ( !( $old instanceof Revision ) ) {
4484 $old = Revision::newFromTitle( $this, (int)$old );
4485 }
4486 if ( !( $new instanceof Revision ) ) {
4487 $new = Revision::newFromTitle( $this, (int)$new );
4488 }
4489 if ( !$old || !$new ) {
4490 return 0; // nothing to compare
4491 }
4492 $dbr = wfGetDB( DB_REPLICA );
4493 $conds = [
4494 'rev_page' => $this->getArticleID(),
4495 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4496 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4497 ];
4498 if ( $max !== null ) {
4499 return $dbr->selectRowCount( 'revision', '1',
4500 $conds,
4501 __METHOD__,
4502 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4503 );
4504 } else {
4505 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4506 }
4507 }
4508
4509 /**
4510 * Get the authors between the given revisions or revision IDs.
4511 * Used for diffs and other things that really need it.
4512 *
4513 * @since 1.23
4514 *
4515 * @param int|Revision $old Old revision or rev ID (first before range by default)
4516 * @param int|Revision $new New revision or rev ID (first after range by default)
4517 * @param int $limit Maximum number of authors
4518 * @param string|array $options (Optional): Single option, or an array of options:
4519 * 'include_old' Include $old in the range; $new is excluded.
4520 * 'include_new' Include $new in the range; $old is excluded.
4521 * 'include_both' Include both $old and $new in the range.
4522 * Unknown option values are ignored.
4523 * @return array|null Names of revision authors in the range; null if not both revisions exist
4524 */
4525 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4526 if ( !( $old instanceof Revision ) ) {
4527 $old = Revision::newFromTitle( $this, (int)$old );
4528 }
4529 if ( !( $new instanceof Revision ) ) {
4530 $new = Revision::newFromTitle( $this, (int)$new );
4531 }
4532 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4533 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4534 // in the sanity check below?
4535 if ( !$old || !$new ) {
4536 return null; // nothing to compare
4537 }
4538 $authors = [];
4539 $old_cmp = '>';
4540 $new_cmp = '<';
4541 $options = (array)$options;
4542 if ( in_array( 'include_old', $options ) ) {
4543 $old_cmp = '>=';
4544 }
4545 if ( in_array( 'include_new', $options ) ) {
4546 $new_cmp = '<=';
4547 }
4548 if ( in_array( 'include_both', $options ) ) {
4549 $old_cmp = '>=';
4550 $new_cmp = '<=';
4551 }
4552 // No DB query needed if $old and $new are the same or successive revisions:
4553 if ( $old->getId() === $new->getId() ) {
4554 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4555 [] :
4556 [ $old->getUserText( Revision::RAW ) ];
4557 } elseif ( $old->getId() === $new->getParentId() ) {
4558 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4559 $authors[] = $old->getUserText( Revision::RAW );
4560 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4561 $authors[] = $new->getUserText( Revision::RAW );
4562 }
4563 } elseif ( $old_cmp === '>=' ) {
4564 $authors[] = $old->getUserText( Revision::RAW );
4565 } elseif ( $new_cmp === '<=' ) {
4566 $authors[] = $new->getUserText( Revision::RAW );
4567 }
4568 return $authors;
4569 }
4570 $dbr = wfGetDB( DB_REPLICA );
4571 $revQuery = Revision::getQueryInfo();
4572 $authors = $dbr->selectFieldValues(
4573 $revQuery['tables'],
4574 $revQuery['fields']['rev_user_text'],
4575 [
4576 'rev_page' => $this->getArticleID(),
4577 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4578 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4579 ], __METHOD__,
4580 [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
4581 $revQuery['joins']
4582 );
4583 return $authors;
4584 }
4585
4586 /**
4587 * Get the number of authors between the given revisions or revision IDs.
4588 * Used for diffs and other things that really need it.
4589 *
4590 * @param int|Revision $old Old revision or rev ID (first before range by default)
4591 * @param int|Revision $new New revision or rev ID (first after range by default)
4592 * @param int $limit Maximum number of authors
4593 * @param string|array $options (Optional): Single option, or an array of options:
4594 * 'include_old' Include $old in the range; $new is excluded.
4595 * 'include_new' Include $new in the range; $old is excluded.
4596 * 'include_both' Include both $old and $new in the range.
4597 * Unknown option values are ignored.
4598 * @return int Number of revision authors in the range; zero if not both revisions exist
4599 */
4600 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4601 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4602 return $authors ? count( $authors ) : 0;
4603 }
4604
4605 /**
4606 * Compare with another title.
4607 *
4608 * @param Title $title
4609 * @return bool
4610 */
4611 public function equals( Title $title ) {
4612 // Note: === is necessary for proper matching of number-like titles.
4613 return $this->mInterwiki === $title->mInterwiki
4614 && $this->mNamespace == $title->mNamespace
4615 && $this->mDbkeyform === $title->mDbkeyform;
4616 }
4617
4618 /**
4619 * Check if this title is a subpage of another title
4620 *
4621 * @param Title $title
4622 * @return bool
4623 */
4624 public function isSubpageOf( Title $title ) {
4625 return $this->mInterwiki === $title->mInterwiki
4626 && $this->mNamespace == $title->mNamespace
4627 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
4628 }
4629
4630 /**
4631 * Check if page exists. For historical reasons, this function simply
4632 * checks for the existence of the title in the page table, and will
4633 * thus return false for interwiki links, special pages and the like.
4634 * If you want to know if a title can be meaningfully viewed, you should
4635 * probably call the isKnown() method instead.
4636 *
4637 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4638 * from master/for update
4639 * @return bool
4640 */
4641 public function exists( $flags = 0 ) {
4642 $exists = $this->getArticleID( $flags ) != 0;
4643 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4644 return $exists;
4645 }
4646
4647 /**
4648 * Should links to this title be shown as potentially viewable (i.e. as
4649 * "bluelinks"), even if there's no record by this title in the page
4650 * table?
4651 *
4652 * This function is semi-deprecated for public use, as well as somewhat
4653 * misleadingly named. You probably just want to call isKnown(), which
4654 * calls this function internally.
4655 *
4656 * (ISSUE: Most of these checks are cheap, but the file existence check
4657 * can potentially be quite expensive. Including it here fixes a lot of
4658 * existing code, but we might want to add an optional parameter to skip
4659 * it and any other expensive checks.)
4660 *
4661 * @return bool
4662 */
4663 public function isAlwaysKnown() {
4664 $isKnown = null;
4665
4666 /**
4667 * Allows overriding default behavior for determining if a page exists.
4668 * If $isKnown is kept as null, regular checks happen. If it's
4669 * a boolean, this value is returned by the isKnown method.
4670 *
4671 * @since 1.20
4672 *
4673 * @param Title $title
4674 * @param bool|null $isKnown
4675 */
4676 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4677
4678 if ( !is_null( $isKnown ) ) {
4679 return $isKnown;
4680 }
4681
4682 if ( $this->isExternal() ) {
4683 return true; // any interwiki link might be viewable, for all we know
4684 }
4685
4686 switch ( $this->mNamespace ) {
4687 case NS_MEDIA:
4688 case NS_FILE:
4689 // file exists, possibly in a foreign repo
4690 return (bool)wfFindFile( $this );
4691 case NS_SPECIAL:
4692 // valid special page
4693 return MediaWikiServices::getInstance()->getSpecialPageFactory()->
4694 exists( $this->mDbkeyform );
4695 case NS_MAIN:
4696 // selflink, possibly with fragment
4697 return $this->mDbkeyform == '';
4698 case NS_MEDIAWIKI:
4699 // known system message
4700 return $this->hasSourceText() !== false;
4701 default:
4702 return false;
4703 }
4704 }
4705
4706 /**
4707 * Does this title refer to a page that can (or might) be meaningfully
4708 * viewed? In particular, this function may be used to determine if
4709 * links to the title should be rendered as "bluelinks" (as opposed to
4710 * "redlinks" to non-existent pages).
4711 * Adding something else to this function will cause inconsistency
4712 * since LinkHolderArray calls isAlwaysKnown() and does its own
4713 * page existence check.
4714 *
4715 * @return bool
4716 */
4717 public function isKnown() {
4718 return $this->isAlwaysKnown() || $this->exists();
4719 }
4720
4721 /**
4722 * Does this page have source text?
4723 *
4724 * @return bool
4725 */
4726 public function hasSourceText() {
4727 if ( $this->exists() ) {
4728 return true;
4729 }
4730
4731 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4732 // If the page doesn't exist but is a known system message, default
4733 // message content will be displayed, same for language subpages-
4734 // Use always content language to avoid loading hundreds of languages
4735 // to get the link color.
4736 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4737 list( $name, ) = MessageCache::singleton()->figureMessage(
4738 $contLang->lcfirst( $this->getText() )
4739 );
4740 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4741 return $message->exists();
4742 }
4743
4744 return false;
4745 }
4746
4747 /**
4748 * Get the default message text or false if the message doesn't exist
4749 *
4750 * @return string|bool
4751 */
4752 public function getDefaultMessageText() {
4753 if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
4754 return false;
4755 }
4756
4757 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4758 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4759 );
4760 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4761
4762 if ( $message->exists() ) {
4763 return $message->plain();
4764 } else {
4765 return false;
4766 }
4767 }
4768
4769 /**
4770 * Updates page_touched for this page; called from LinksUpdate.php
4771 *
4772 * @param string|null $purgeTime [optional] TS_MW timestamp
4773 * @return bool True if the update succeeded
4774 */
4775 public function invalidateCache( $purgeTime = null ) {
4776 if ( wfReadOnly() ) {
4777 return false;
4778 } elseif ( $this->mArticleID === 0 ) {
4779 return true; // avoid gap locking if we know it's not there
4780 }
4781
4782 $dbw = wfGetDB( DB_MASTER );
4783 $dbw->onTransactionPreCommitOrIdle(
4784 function () {
4785 ResourceLoaderWikiModule::invalidateModuleCache( $this, null, null, wfWikiID() );
4786 },
4787 __METHOD__
4788 );
4789
4790 $conds = $this->pageCond();
4791 DeferredUpdates::addUpdate(
4792 new AutoCommitUpdate(
4793 $dbw,
4794 __METHOD__,
4795 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4796 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4797 $dbw->update(
4798 'page',
4799 [ 'page_touched' => $dbTimestamp ],
4800 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4801 $fname
4802 );
4803 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4804 }
4805 ),
4806 DeferredUpdates::PRESEND
4807 );
4808
4809 return true;
4810 }
4811
4812 /**
4813 * Update page_touched timestamps and send CDN purge messages for
4814 * pages linking to this title. May be sent to the job queue depending
4815 * on the number of links. Typically called on create and delete.
4816 */
4817 public function touchLinks() {
4818 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4819 if ( $this->mNamespace == NS_CATEGORY ) {
4820 DeferredUpdates::addUpdate(
4821 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4822 );
4823 }
4824 }
4825
4826 /**
4827 * Get the last touched timestamp
4828 *
4829 * @param IDatabase|null $db
4830 * @return string|false Last-touched timestamp
4831 */
4832 public function getTouched( $db = null ) {
4833 if ( $db === null ) {
4834 $db = wfGetDB( DB_REPLICA );
4835 }
4836 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4837 return $touched;
4838 }
4839
4840 /**
4841 * Get the timestamp when this page was updated since the user last saw it.
4842 *
4843 * @param User|null $user
4844 * @return string|null
4845 */
4846 public function getNotificationTimestamp( $user = null ) {
4847 global $wgUser;
4848
4849 // Assume current user if none given
4850 if ( !$user ) {
4851 $user = $wgUser;
4852 }
4853 // Check cache first
4854 $uid = $user->getId();
4855 if ( !$uid ) {
4856 return false;
4857 }
4858 // avoid isset here, as it'll return false for null entries
4859 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4860 return $this->mNotificationTimestamp[$uid];
4861 }
4862 // Don't cache too much!
4863 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4864 $this->mNotificationTimestamp = [];
4865 }
4866
4867 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4868 $watchedItem = $store->getWatchedItem( $user, $this );
4869 if ( $watchedItem ) {
4870 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4871 } else {
4872 $this->mNotificationTimestamp[$uid] = false;
4873 }
4874
4875 return $this->mNotificationTimestamp[$uid];
4876 }
4877
4878 /**
4879 * Generate strings used for xml 'id' names in monobook tabs
4880 *
4881 * @param string $prepend Defaults to 'nstab-'
4882 * @return string XML 'id' name
4883 */
4884 public function getNamespaceKey( $prepend = 'nstab-' ) {
4885 // Gets the subject namespace of this title
4886 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
4887 // Prefer canonical namespace name for HTML IDs
4888 $namespaceKey = MWNamespace::getCanonicalName( $subjectNS );
4889 if ( $namespaceKey === false ) {
4890 // Fallback to localised text
4891 $namespaceKey = $this->getSubjectNsText();
4892 }
4893 // Makes namespace key lowercase
4894 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4895 // Uses main
4896 if ( $namespaceKey == '' ) {
4897 $namespaceKey = 'main';
4898 }
4899 // Changes file to image for backwards compatibility
4900 if ( $namespaceKey == 'file' ) {
4901 $namespaceKey = 'image';
4902 }
4903 return $prepend . $namespaceKey;
4904 }
4905
4906 /**
4907 * Get all extant redirects to this Title
4908 *
4909 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4910 * @return Title[] Array of Title redirects to this title
4911 */
4912 public function getRedirectsHere( $ns = null ) {
4913 $redirs = [];
4914
4915 $dbr = wfGetDB( DB_REPLICA );
4916 $where = [
4917 'rd_namespace' => $this->mNamespace,
4918 'rd_title' => $this->mDbkeyform,
4919 'rd_from = page_id'
4920 ];
4921 if ( $this->isExternal() ) {
4922 $where['rd_interwiki'] = $this->mInterwiki;
4923 } else {
4924 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4925 }
4926 if ( !is_null( $ns ) ) {
4927 $where['page_namespace'] = $ns;
4928 }
4929
4930 $res = $dbr->select(
4931 [ 'redirect', 'page' ],
4932 [ 'page_namespace', 'page_title' ],
4933 $where,
4934 __METHOD__
4935 );
4936
4937 foreach ( $res as $row ) {
4938 $redirs[] = self::newFromRow( $row );
4939 }
4940 return $redirs;
4941 }
4942
4943 /**
4944 * Check if this Title is a valid redirect target
4945 *
4946 * @return bool
4947 */
4948 public function isValidRedirectTarget() {
4949 global $wgInvalidRedirectTargets;
4950
4951 if ( $this->isSpecialPage() ) {
4952 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4953 if ( $this->isSpecial( 'Userlogout' ) ) {
4954 return false;
4955 }
4956
4957 foreach ( $wgInvalidRedirectTargets as $target ) {
4958 if ( $this->isSpecial( $target ) ) {
4959 return false;
4960 }
4961 }
4962 }
4963
4964 return true;
4965 }
4966
4967 /**
4968 * Get a backlink cache object
4969 *
4970 * @return BacklinkCache
4971 */
4972 public function getBacklinkCache() {
4973 return BacklinkCache::get( $this );
4974 }
4975
4976 /**
4977 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4978 *
4979 * @return bool
4980 */
4981 public function canUseNoindex() {
4982 global $wgExemptFromUserRobotsControl;
4983
4984 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4985 ? MWNamespace::getContentNamespaces()
4986 : $wgExemptFromUserRobotsControl;
4987
4988 return !in_array( $this->mNamespace, $bannedNamespaces );
4989 }
4990
4991 /**
4992 * Returns the raw sort key to be used for categories, with the specified
4993 * prefix. This will be fed to Collation::getSortKey() to get a
4994 * binary sortkey that can be used for actual sorting.
4995 *
4996 * @param string $prefix The prefix to be used, specified using
4997 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4998 * prefix.
4999 * @return string
5000 */
5001 public function getCategorySortkey( $prefix = '' ) {
5002 $unprefixed = $this->getText();
5003
5004 // Anything that uses this hook should only depend
5005 // on the Title object passed in, and should probably
5006 // tell the users to run updateCollations.php --force
5007 // in order to re-sort existing category relations.
5008 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5009 if ( $prefix !== '' ) {
5010 # Separate with a line feed, so the unprefixed part is only used as
5011 # a tiebreaker when two pages have the exact same prefix.
5012 # In UCA, tab is the only character that can sort above LF
5013 # so we strip both of them from the original prefix.
5014 $prefix = strtr( $prefix, "\n\t", ' ' );
5015 return "$prefix\n$unprefixed";
5016 }
5017 return $unprefixed;
5018 }
5019
5020 /**
5021 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5022 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5023 * the db, it will return NULL.
5024 *
5025 * @return string|null|bool
5026 */
5027 private function getDbPageLanguageCode() {
5028 global $wgPageLanguageUseDB;
5029
5030 // check, if the page language could be saved in the database, and if so and
5031 // the value is not requested already, lookup the page language using LinkCache
5032 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
5033 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
5034 $linkCache->addLinkObj( $this );
5035 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5036 }
5037
5038 return $this->mDbPageLanguage;
5039 }
5040
5041 /**
5042 * Get the language in which the content of this page is written in
5043 * wikitext. Defaults to content language, but in certain cases it can be
5044 * e.g. $wgLang (such as special pages, which are in the user language).
5045 *
5046 * @since 1.18
5047 * @return Language
5048 */
5049 public function getPageLanguage() {
5050 global $wgLang, $wgLanguageCode;
5051 if ( $this->isSpecialPage() ) {
5052 // special pages are in the user language
5053 return $wgLang;
5054 }
5055
5056 // Checking if DB language is set
5057 $dbPageLanguage = $this->getDbPageLanguageCode();
5058 if ( $dbPageLanguage ) {
5059 return wfGetLangObj( $dbPageLanguage );
5060 }
5061
5062 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
5063 // Note that this may depend on user settings, so the cache should
5064 // be only per-request.
5065 // NOTE: ContentHandler::getPageLanguage() may need to load the
5066 // content to determine the page language!
5067 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5068 // tests.
5069 $contentHandler = ContentHandler::getForTitle( $this );
5070 $langObj = $contentHandler->getPageLanguage( $this );
5071 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
5072 } else {
5073 $langObj = Language::factory( $this->mPageLanguage[0] );
5074 }
5075
5076 return $langObj;
5077 }
5078
5079 /**
5080 * Get the language in which the content of this page is written when
5081 * viewed by user. Defaults to content language, but in certain cases it can be
5082 * e.g. $wgLang (such as special pages, which are in the user language).
5083 *
5084 * @since 1.20
5085 * @return Language
5086 */
5087 public function getPageViewLanguage() {
5088 global $wgLang;
5089
5090 if ( $this->isSpecialPage() ) {
5091 // If the user chooses a variant, the content is actually
5092 // in a language whose code is the variant code.
5093 $variant = $wgLang->getPreferredVariant();
5094 if ( $wgLang->getCode() !== $variant ) {
5095 return Language::factory( $variant );
5096 }
5097
5098 return $wgLang;
5099 }
5100
5101 // Checking if DB language is set
5102 $dbPageLanguage = $this->getDbPageLanguageCode();
5103 if ( $dbPageLanguage ) {
5104 $pageLang = wfGetLangObj( $dbPageLanguage );
5105 $variant = $pageLang->getPreferredVariant();
5106 if ( $pageLang->getCode() !== $variant ) {
5107 $pageLang = Language::factory( $variant );
5108 }
5109
5110 return $pageLang;
5111 }
5112
5113 // @note Can't be cached persistently, depends on user settings.
5114 // @note ContentHandler::getPageViewLanguage() may need to load the
5115 // content to determine the page language!
5116 $contentHandler = ContentHandler::getForTitle( $this );
5117 $pageLang = $contentHandler->getPageViewLanguage( $this );
5118 return $pageLang;
5119 }
5120
5121 /**
5122 * Get a list of rendered edit notices for this page.
5123 *
5124 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5125 * they will already be wrapped in paragraphs.
5126 *
5127 * @since 1.21
5128 * @param int $oldid Revision ID that's being edited
5129 * @return array
5130 */
5131 public function getEditNotices( $oldid = 0 ) {
5132 $notices = [];
5133
5134 // Optional notice for the entire namespace
5135 $editnotice_ns = 'editnotice-' . $this->mNamespace;
5136 $msg = wfMessage( $editnotice_ns );
5137 if ( $msg->exists() ) {
5138 $html = $msg->parseAsBlock();
5139 // Edit notices may have complex logic, but output nothing (T91715)
5140 if ( trim( $html ) !== '' ) {
5141 $notices[$editnotice_ns] = Html::rawElement(
5142 'div',
5143 [ 'class' => [
5144 'mw-editnotice',
5145 'mw-editnotice-namespace',
5146 Sanitizer::escapeClass( "mw-$editnotice_ns" )
5147 ] ],
5148 $html
5149 );
5150 }
5151 }
5152
5153 if ( MWNamespace::hasSubpages( $this->mNamespace ) ) {
5154 // Optional notice for page itself and any parent page
5155 $parts = explode( '/', $this->mDbkeyform );
5156 $editnotice_base = $editnotice_ns;
5157 while ( count( $parts ) > 0 ) {
5158 $editnotice_base .= '-' . array_shift( $parts );
5159 $msg = wfMessage( $editnotice_base );
5160 if ( $msg->exists() ) {
5161 $html = $msg->parseAsBlock();
5162 if ( trim( $html ) !== '' ) {
5163 $notices[$editnotice_base] = Html::rawElement(
5164 'div',
5165 [ 'class' => [
5166 'mw-editnotice',
5167 'mw-editnotice-base',
5168 Sanitizer::escapeClass( "mw-$editnotice_base" )
5169 ] ],
5170 $html
5171 );
5172 }
5173 }
5174 }
5175 } else {
5176 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5177 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
5178 $msg = wfMessage( $editnoticeText );
5179 if ( $msg->exists() ) {
5180 $html = $msg->parseAsBlock();
5181 if ( trim( $html ) !== '' ) {
5182 $notices[$editnoticeText] = Html::rawElement(
5183 'div',
5184 [ 'class' => [
5185 'mw-editnotice',
5186 'mw-editnotice-page',
5187 Sanitizer::escapeClass( "mw-$editnoticeText" )
5188 ] ],
5189 $html
5190 );
5191 }
5192 }
5193 }
5194
5195 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5196 return $notices;
5197 }
5198
5199 /**
5200 * @return array
5201 */
5202 public function __sleep() {
5203 return [
5204 'mNamespace',
5205 'mDbkeyform',
5206 'mFragment',
5207 'mInterwiki',
5208 'mLocalInterwiki',
5209 'mUserCaseDBKey',
5210 'mDefaultNamespace',
5211 ];
5212 }
5213
5214 public function __wakeup() {
5215 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
5216 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
5217 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
5218 }
5219
5220 }