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