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