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