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