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