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