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