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