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