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