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