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