MediaWiki  master
Title.php
Go to the documentation of this file.
1 <?php
29 use Wikimedia\Assert\Assert;
32 
41 class Title implements LinkTarget, IDBAccessObject {
43  private static $titleCache = null;
44 
50  private const CACHE_MAX = 1000;
51 
57  public const GAID_FOR_UPDATE = 512;
58 
66  public const NEW_CLONE = 'clone';
67 
73  // @{
74 
76  public $mTextform = '';
78  public $mUrlform = '';
80  public $mDbkeyform = '';
82  public $mNamespace = NS_MAIN;
84  public $mInterwiki = '';
86  private $mLocalInterwiki = false;
88  public $mFragment = '';
89 
91  public $mArticleID = -1;
92 
94  protected $mLatestID = false;
95 
100  private $mContentModel = false;
101 
106  private $mForcedContentModel = false;
107 
110 
112  public $mRestrictions = [];
113 
120  protected $mOldRestrictions = false;
121 
124 
127 
129  protected $mRestrictionsExpiry = [];
130 
133 
136 
138  public $mRestrictionsLoaded = false;
139 
148  public $prefixedText = null;
149 
152 
160 
162  protected $mLength = -1;
163 
165  public $mRedirect = null;
166 
168  private $mHasSubpages;
169 
171  private $mPageLanguage;
172 
176  private $mDbPageLanguage = false;
177 
179  private $mTitleValue = null;
180 
182  private $mIsBigDeletion = null;
183 
185  private $mIsValid = null;
186  // @}
187 
193  private function getLanguageConverter( $language ) : ILanguageConverter {
194  return MediaWikiServices::getInstance()->getLanguageConverterFactory()
195  ->getLanguageConverter( $language );
196  }
197 
203  return $this->getLanguageConverter( $this->getPageLanguage() );
204  }
205 
214  private static function getTitleFormatter() {
215  return MediaWikiServices::getInstance()->getTitleFormatter();
216  }
217 
226  private static function getInterwikiLookup() {
227  return MediaWikiServices::getInstance()->getInterwikiLookup();
228  }
229 
230  private function __construct() {
231  }
232 
241  public static function newFromDBkey( $key ) {
242  $t = new self();
243 
244  try {
245  $t->secureAndSplit( $key );
246  return $t;
247  } catch ( MalformedTitleException $ex ) {
248  return null;
249  }
250  }
251 
265  public static function newFromTitleValue( TitleValue $titleValue, $forceClone = '' ) {
266  return self::newFromLinkTarget( $titleValue, $forceClone );
267  }
268 
280  public static function newFromLinkTarget( LinkTarget $linkTarget, $forceClone = '' ) {
281  if ( $linkTarget instanceof Title ) {
282  // Special case if it's already a Title object
283  if ( $forceClone === self::NEW_CLONE ) {
284  return clone $linkTarget;
285  } else {
286  return $linkTarget;
287  }
288  }
289  return self::makeTitle(
290  $linkTarget->getNamespace(),
291  $linkTarget->getText(),
292  $linkTarget->getFragment(),
293  $linkTarget->getInterwiki()
294  );
295  }
296 
304  public static function castFromLinkTarget( $linkTarget ) {
305  return $linkTarget ? self::newFromLinkTarget( $linkTarget ) : null;
306  }
307 
328  public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
329  // DWIM: Integers can be passed in here when page titles are used as array keys.
330  if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
331  throw new InvalidArgumentException( '$text must be a string.' );
332  }
333  if ( $text === null ) {
334  return null;
335  }
336 
337  try {
338  return self::newFromTextThrow( (string)$text, (int)$defaultNamespace );
339  } catch ( MalformedTitleException $ex ) {
340  return null;
341  }
342  }
343 
363  public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
364  if ( is_object( $text ) ) {
365  throw new MWException( '$text must be a string, given an object' );
366  } elseif ( $text === null ) {
367  // Legacy code relies on MalformedTitleException being thrown in this case
368  // (happens when URL with no title in it is parsed). TODO fix
369  throw new MalformedTitleException( 'title-invalid-empty' );
370  }
371 
373 
374  // Wiki pages often contain multiple links to the same page.
375  // Title normalization and parsing can become expensive on pages with many
376  // links, so we can save a little time by caching them.
377  // In theory these are value objects and won't get changed...
378  if ( $defaultNamespace === NS_MAIN ) {
379  $t = $titleCache->get( $text );
380  if ( $t ) {
381  return $t;
382  }
383  }
384 
385  // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
386  $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
387 
388  $t = new Title();
389  $dbKeyForm = strtr( $filteredText, ' ', '_' );
390 
391  $t->secureAndSplit( $dbKeyForm, (int)$defaultNamespace );
392  if ( $defaultNamespace === NS_MAIN ) {
393  $titleCache->set( $text, $t );
394  }
395  return $t;
396  }
397 
413  public static function newFromURL( $url ) {
414  $t = new Title();
415 
416  # For compatibility with old buggy URLs. "+" is usually not valid in titles,
417  # but some URLs used it as a space replacement and they still come
418  # from some external search tools.
419  if ( strpos( self::legalChars(), '+' ) === false ) {
420  $url = strtr( $url, '+', ' ' );
421  }
422 
423  $dbKeyForm = strtr( $url, ' ', '_' );
424 
425  try {
426  $t->secureAndSplit( $dbKeyForm );
427  return $t;
428  } catch ( MalformedTitleException $ex ) {
429  return null;
430  }
431  }
432 
436  private static function getTitleCache() {
437  if ( self::$titleCache === null ) {
438  self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
439  }
440  return self::$titleCache;
441  }
442 
449  protected static function getSelectFields() {
450  global $wgPageLanguageUseDB;
451 
452  $fields = [
453  'page_namespace', 'page_title', 'page_id',
454  'page_len', 'page_is_redirect', 'page_latest',
455  'page_content_model',
456  ];
457 
458  if ( $wgPageLanguageUseDB ) {
459  $fields[] = 'page_lang';
460  }
461 
462  return $fields;
463  }
464 
472  public static function newFromID( $id, $flags = 0 ) {
473  $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
474  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
475  $row = wfGetDB( $index )->selectRow(
476  'page',
477  self::getSelectFields(),
478  [ 'page_id' => $id ],
479  __METHOD__,
480  $options
481  );
482  if ( $row !== false ) {
483  $title = self::newFromRow( $row );
484  } else {
485  $title = null;
486  }
487 
488  return $title;
489  }
490 
497  public static function newFromIDs( $ids ) {
498  if ( !count( $ids ) ) {
499  return [];
500  }
501  $dbr = wfGetDB( DB_REPLICA );
502 
503  $res = $dbr->select(
504  'page',
505  self::getSelectFields(),
506  [ 'page_id' => $ids ],
507  __METHOD__
508  );
509 
510  $titles = [];
511  foreach ( $res as $row ) {
512  $titles[] = self::newFromRow( $row );
513  }
514  return $titles;
515  }
516 
523  public static function newFromRow( $row ) {
524  $t = self::makeTitle( $row->page_namespace, $row->page_title );
525  $t->loadFromRow( $row );
526  return $t;
527  }
528 
535  public function loadFromRow( $row ) {
536  if ( $row ) { // page found
537  if ( isset( $row->page_id ) ) {
538  $this->mArticleID = (int)$row->page_id;
539  }
540  if ( isset( $row->page_len ) ) {
541  $this->mLength = (int)$row->page_len;
542  }
543  if ( isset( $row->page_is_redirect ) ) {
544  $this->mRedirect = (bool)$row->page_is_redirect;
545  }
546  if ( isset( $row->page_latest ) ) {
547  $this->mLatestID = (int)$row->page_latest;
548  }
549  if ( isset( $row->page_content_model ) ) {
550  $this->lazyFillContentModel( $row->page_content_model );
551  } else {
552  $this->lazyFillContentModel( false ); // lazily-load getContentModel()
553  }
554  if ( isset( $row->page_lang ) ) {
555  $this->mDbPageLanguage = (string)$row->page_lang;
556  }
557  if ( isset( $row->page_restrictions ) ) {
558  $this->mOldRestrictions = $row->page_restrictions;
559  }
560  } else { // page not found
561  $this->mArticleID = 0;
562  $this->mLength = 0;
563  $this->mRedirect = false;
564  $this->mLatestID = 0;
565  $this->lazyFillContentModel( false ); // lazily-load getContentModel()
566  }
567  }
568 
591  public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
592  $t = new Title();
593  $t->mInterwiki = $interwiki;
594  $t->mFragment = $fragment;
595  $t->mNamespace = $ns = (int)$ns;
596  $t->mDbkeyform = strtr( $title, ' ', '_' );
597  $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
598  $t->mUrlform = wfUrlencode( $t->mDbkeyform );
599  $t->mTextform = strtr( $title, '_', ' ' );
600  return $t;
601  }
602 
617  public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
618  // NOTE: ideally, this would just call makeTitle() and then isValid(),
619  // but presently, that means more overhead on a potential performance hotspot.
620 
621  if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
622  return null;
623  }
624 
625  $t = new Title();
626  $dbKeyForm = self::makeName( $ns, $title, $fragment, $interwiki, true );
627 
628  try {
629  $t->secureAndSplit( $dbKeyForm );
630  return $t;
631  } catch ( MalformedTitleException $ex ) {
632  return null;
633  }
634  }
635 
653  public static function newMainPage( MessageLocalizer $localizer = null ) {
654  if ( $localizer ) {
655  $msg = $localizer->msg( 'mainpage' );
656  } else {
657  $msg = wfMessage( 'mainpage' );
658  }
659 
660  $title = self::newFromText( $msg->inContentLanguage()->text() );
661 
662  // Every page renders at least one link to the Main Page (e.g. sidebar).
663  // If the localised value is invalid, don't produce fatal errors that
664  // would make the wiki inaccessible (and hard to fix the invalid message).
665  // Gracefully fallback...
666  if ( !$title ) {
667  $title = self::newFromText( 'Main Page' );
668  }
669  return $title;
670  }
671 
679  public static function nameOf( $id ) {
680  wfDeprecated( __METHOD__, '1.36' );
681 
682  $dbr = wfGetDB( DB_REPLICA );
683 
684  $s = $dbr->selectRow(
685  'page',
686  [ 'page_namespace', 'page_title' ],
687  [ 'page_id' => $id ],
688  __METHOD__
689  );
690  if ( $s === false ) {
691  return null;
692  }
693 
694  return self::makeName( $s->page_namespace, $s->page_title );
695  }
696 
702  public static function legalChars() {
703  global $wgLegalTitleChars;
704  return $wgLegalTitleChars;
705  }
706 
716  public static function convertByteClassToUnicodeClass( $byteClass ) {
717  $length = strlen( $byteClass );
718  // Input token queue
719  $x0 = $x1 = $x2 = '';
720  // Decoded queue
721  $d0 = $d1 = $d2 = '';
722  // Decoded integer codepoints
723  $ord0 = $ord1 = $ord2 = 0;
724  // Re-encoded queue
725  $r0 = $r1 = $r2 = '';
726  // Output
727  $out = '';
728  // Flags
729  $allowUnicode = false;
730  for ( $pos = 0; $pos < $length; $pos++ ) {
731  // Shift the queues down
732  $x2 = $x1;
733  $x1 = $x0;
734  $d2 = $d1;
735  $d1 = $d0;
736  $ord2 = $ord1;
737  $ord1 = $ord0;
738  $r2 = $r1;
739  $r1 = $r0;
740  // Load the current input token and decoded values
741  $inChar = $byteClass[$pos];
742  if ( $inChar == '\\' ) {
743  if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
744  $x0 = $inChar . $m[0];
745  $d0 = chr( hexdec( $m[1] ) );
746  $pos += strlen( $m[0] );
747  } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
748  $x0 = $inChar . $m[0];
749  $d0 = chr( octdec( $m[0] ) );
750  $pos += strlen( $m[0] );
751  } elseif ( $pos + 1 >= $length ) {
752  $x0 = $d0 = '\\';
753  } else {
754  $d0 = $byteClass[$pos + 1];
755  $x0 = $inChar . $d0;
756  $pos += 1;
757  }
758  } else {
759  $x0 = $d0 = $inChar;
760  }
761  $ord0 = ord( $d0 );
762  // Load the current re-encoded value
763  if ( $ord0 < 32 || $ord0 == 0x7f ) {
764  $r0 = sprintf( '\x%02x', $ord0 );
765  } elseif ( $ord0 >= 0x80 ) {
766  // Allow unicode if a single high-bit character appears
767  $r0 = sprintf( '\x%02x', $ord0 );
768  $allowUnicode = true;
769  // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
770  } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
771  $r0 = '\\' . $d0;
772  } else {
773  $r0 = $d0;
774  }
775  // Do the output
776  if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
777  // Range
778  if ( $ord2 > $ord0 ) {
779  // Empty range
780  } elseif ( $ord0 >= 0x80 ) {
781  // Unicode range
782  $allowUnicode = true;
783  if ( $ord2 < 0x80 ) {
784  // Keep the non-unicode section of the range
785  $out .= "$r2-\\x7F";
786  }
787  } else {
788  // Normal range
789  $out .= "$r2-$r0";
790  }
791  // Reset state to the initial value
792  $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
793  } elseif ( $ord2 < 0x80 ) {
794  // ASCII character
795  $out .= $r2;
796  }
797  }
798  // @phan-suppress-next-line PhanSuspiciousValueComparison
799  if ( $ord1 < 0x80 ) {
800  $out .= $r1;
801  }
802  if ( $ord0 < 0x80 ) {
803  $out .= $r0;
804  }
805  if ( $allowUnicode ) {
806  $out .= '\u0080-\uFFFF';
807  }
808  return $out;
809  }
810 
822  public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
823  $canonicalNamespace = false
824  ) {
825  if ( $canonicalNamespace ) {
826  $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
827  getCanonicalName( $ns );
828  } else {
829  $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
830  }
831  $name = $namespace == '' ? $title : "$namespace:$title";
832  if ( strval( $interwiki ) != '' ) {
833  $name = "$interwiki:$name";
834  }
835  if ( strval( $fragment ) != '' ) {
836  $name .= '#' . $fragment;
837  }
838  return $name;
839  }
840 
849  public static function compare( LinkTarget $a, LinkTarget $b ) {
850  return $a->getNamespace() <=> $b->getNamespace()
851  ?: strcmp( $a->getText(), $b->getText() );
852  }
853 
870  public function isValid() {
871  if ( $this->mIsValid !== null ) {
872  return $this->mIsValid;
873  }
874 
875  try {
876  $text = $this->getFullText();
877  $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
878 
879  '@phan-var MediaWikiTitleCodec $titleCodec';
880  $parts = $titleCodec->splitTitleString( $text, $this->mNamespace );
881 
882  // Check that nothing changed!
883  // This ensures that $text was already perperly normalized.
884  if ( $parts['fragment'] !== $this->mFragment
885  || $parts['interwiki'] !== $this->mInterwiki
886  || $parts['local_interwiki'] !== $this->mLocalInterwiki
887  || $parts['namespace'] !== $this->mNamespace
888  || $parts['dbkey'] !== $this->mDbkeyform
889  ) {
890  $this->mIsValid = false;
891  return $this->mIsValid;
892  }
893  } catch ( MalformedTitleException $ex ) {
894  $this->mIsValid = false;
895  return $this->mIsValid;
896  }
897 
898  $this->mIsValid = true;
899  return $this->mIsValid;
900  }
901 
909  public function isLocal() {
910  if ( $this->isExternal() ) {
911  $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
912  if ( $iw ) {
913  return $iw->isLocal();
914  }
915  }
916  return true;
917  }
918 
924  public function isExternal() {
925  return $this->mInterwiki !== '';
926  }
927 
935  public function getInterwiki() {
936  return $this->mInterwiki;
937  }
938 
944  public function wasLocalInterwiki() {
945  return $this->mLocalInterwiki;
946  }
947 
954  public function isTrans() {
955  if ( !$this->isExternal() ) {
956  return false;
957  }
958 
959  return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
960  }
961 
967  public function getTransWikiID() {
968  if ( !$this->isExternal() ) {
969  return false;
970  }
971 
972  return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
973  }
974 
984  public function getTitleValue() {
985  if ( $this->mTitleValue === null ) {
986  try {
987  $this->mTitleValue = new TitleValue(
988  $this->mNamespace,
989  $this->mDbkeyform,
990  $this->mFragment,
991  $this->mInterwiki
992  );
993  } catch ( InvalidArgumentException $ex ) {
994  wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
995  $this->getPrefixedText() . ']]: ' . $ex->getMessage() );
996  }
997  }
998 
999  return $this->mTitleValue;
1000  }
1001 
1007  public function getText() {
1008  return $this->mTextform;
1009  }
1010 
1016  public function getPartialURL() {
1017  return $this->mUrlform;
1018  }
1019 
1025  public function getDBkey() {
1026  return $this->mDbkeyform;
1027  }
1028 
1034  public function getNamespace() {
1035  return $this->mNamespace;
1036  }
1037 
1046  public function getContentModel( $flags = 0 ) {
1047  if ( $this->mForcedContentModel ) {
1048  if ( !$this->mContentModel ) {
1049  throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
1050  }
1051  // Content model is locked to the currently loaded one
1052  return $this->mContentModel;
1053  }
1054 
1055  if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
1056  $this->lazyFillContentModel( $this->loadFieldFromDB( 'page_content_model', $flags ) );
1057  } elseif (
1058  ( !$this->mContentModel || $flags & self::GAID_FOR_UPDATE ) &&
1059  $this->getArticleID( $flags )
1060  ) {
1061  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1062  $linkCache->addLinkObj( $this ); # in case we already had an article ID
1063  $this->lazyFillContentModel( $linkCache->getGoodLinkFieldObj( $this, 'model' ) );
1064  }
1065 
1066  if ( !$this->mContentModel ) {
1068  }
1069 
1070  return $this->mContentModel;
1071  }
1072 
1079  public function hasContentModel( $id ) {
1080  return $this->getContentModel() == $id;
1081  }
1082 
1096  public function setContentModel( $model ) {
1097  if ( (string)$model === '' ) {
1098  throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
1099  }
1100 
1101  $this->mContentModel = $model;
1102  $this->mForcedContentModel = true;
1103  }
1104 
1110  private function lazyFillContentModel( $model ) {
1111  if ( !$this->mForcedContentModel ) {
1112  $this->mContentModel = ( $model === false ) ? false : (string)$model;
1113  }
1114  }
1115 
1121  public function getNsText() {
1122  if ( $this->isExternal() ) {
1123  // This probably shouldn't even happen, except for interwiki transclusion.
1124  // If possible, use the canonical name for the foreign namespace.
1125  $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
1126  getCanonicalName( $this->mNamespace );
1127  if ( $nsText !== false ) {
1128  return $nsText;
1129  }
1130  }
1131 
1132  try {
1133  $formatter = self::getTitleFormatter();
1134  return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1135  } catch ( InvalidArgumentException $ex ) {
1136  wfDebug( __METHOD__ . ': ' . $ex->getMessage() );
1137  return false;
1138  }
1139  }
1140 
1146  public function getSubjectNsText() {
1147  $services = MediaWikiServices::getInstance();
1148  return $services->getContentLanguage()->
1149  getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
1150  }
1151 
1157  public function getTalkNsText() {
1158  $services = MediaWikiServices::getInstance();
1159  return $services->getContentLanguage()->
1160  getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
1161  }
1162 
1174  public function canHaveTalkPage() {
1175  return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1176  }
1177 
1188  public function canExist() {
1189  // NOTE: Don't use getArticleID(), we don't want to
1190  // trigger a database query here. This check is supposed to
1191  // act as an optimization, not add extra cost.
1192  if ( $this->mArticleID > 0 ) {
1193  // It exists, so it can exist.
1194  return true;
1195  }
1196 
1197  // NOTE: we call the relatively expensive isValid() method further down,
1198  // but we can bail out early if we already know the title is invalid.
1199  if ( $this->mIsValid === false ) {
1200  // It's invalid, so it can't exist.
1201  return false;
1202  }
1203 
1204  if ( $this->getNamespace() < NS_MAIN ) {
1205  // It's a special page, so it can't exist in the database.
1206  return false;
1207  }
1208 
1209  if ( $this->isExternal() ) {
1210  // If it's external, it's not local, so it can't exist.
1211  return false;
1212  }
1213 
1214  if ( $this->getText() === '' ) {
1215  // The title has no text, so it can't exist in the database.
1216  // It's probably an on-page section link, like "#something".
1217  return false;
1218  }
1219 
1220  // Double check that the title is valid.
1221  return $this->isValid();
1222  }
1223 
1232  public function isWatchable() {
1233  $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
1234  return $this->getText() !== '' && !$this->isExternal() &&
1235  $nsInfo->isWatchable( $this->mNamespace );
1236  }
1237 
1243  public function isSpecialPage() {
1244  return $this->mNamespace === NS_SPECIAL;
1245  }
1246 
1253  public function isSpecial( $name ) {
1254  if ( $this->isSpecialPage() ) {
1255  list( $thisName, /* $subpage */ ) =
1256  MediaWikiServices::getInstance()->getSpecialPageFactory()->
1257  resolveAlias( $this->mDbkeyform );
1258  if ( $name == $thisName ) {
1259  return true;
1260  }
1261  }
1262  return false;
1263  }
1264 
1271  public function fixSpecialName() {
1272  if ( $this->isSpecialPage() ) {
1273  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1274  list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform );
1275  if ( $canonicalName ) {
1276  $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1277  if ( $localName != $this->mDbkeyform ) {
1278  return self::makeTitle( NS_SPECIAL, $localName );
1279  }
1280  }
1281  }
1282  return $this;
1283  }
1284 
1295  public function inNamespace( $ns ) {
1296  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1297  equals( $this->mNamespace, $ns );
1298  }
1299 
1307  public function inNamespaces( ...$namespaces ) {
1308  if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1309  $namespaces = $namespaces[0];
1310  }
1311 
1312  foreach ( $namespaces as $ns ) {
1313  if ( $this->inNamespace( $ns ) ) {
1314  return true;
1315  }
1316  }
1317 
1318  return false;
1319  }
1320 
1334  public function hasSubjectNamespace( $ns ) {
1335  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1336  subjectEquals( $this->mNamespace, $ns );
1337  }
1338 
1346  public function isContentPage() {
1347  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1348  isContent( $this->mNamespace );
1349  }
1350 
1357  public function isMovable() {
1358  if (
1359  !MediaWikiServices::getInstance()->getNamespaceInfo()->
1360  isMovable( $this->mNamespace ) || $this->isExternal()
1361  ) {
1362  // Interwiki title or immovable namespace. Hooks don't get to override here
1363  return false;
1364  }
1365 
1366  $result = true;
1367  Hooks::runner()->onTitleIsMovable( $this, $result );
1368  return $result;
1369  }
1370 
1381  public function isMainPage() {
1382  return $this->equals( self::newMainPage() );
1383  }
1384 
1390  public function isSubpage() {
1391  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1392  hasSubpages( $this->mNamespace )
1393  ? strpos( $this->getText(), '/' ) !== false
1394  : false;
1395  }
1396 
1402  public function isConversionTable() {
1403  // @todo ConversionTable should become a separate content model.
1404 
1405  return $this->mNamespace === NS_MEDIAWIKI &&
1406  strpos( $this->getText(), 'Conversiontable/' ) === 0;
1407  }
1408 
1414  public function isWikitextPage() {
1415  return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1416  }
1417 
1432  public function isSiteConfigPage() {
1433  return (
1434  $this->isSiteCssConfigPage()
1435  || $this->isSiteJsonConfigPage()
1436  || $this->isSiteJsConfigPage()
1437  );
1438  }
1439 
1446  public function isUserConfigPage() {
1447  return (
1448  $this->isUserCssConfigPage()
1449  || $this->isUserJsonConfigPage()
1450  || $this->isUserJsConfigPage()
1451  );
1452  }
1453 
1460  public function getSkinFromConfigSubpage() {
1461  $subpage = explode( '/', $this->mTextform );
1462  $subpage = $subpage[count( $subpage ) - 1];
1463  $lastdot = strrpos( $subpage, '.' );
1464  if ( $lastdot === false ) {
1465  return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1466  }
1467  return substr( $subpage, 0, $lastdot );
1468  }
1469 
1476  public function isUserCssConfigPage() {
1477  return (
1478  $this->mNamespace === NS_USER
1479  && $this->isSubpage()
1480  && $this->hasContentModel( CONTENT_MODEL_CSS )
1481  );
1482  }
1483 
1490  public function isUserJsonConfigPage() {
1491  return (
1492  $this->mNamespace === NS_USER
1493  && $this->isSubpage()
1494  && $this->hasContentModel( CONTENT_MODEL_JSON )
1495  );
1496  }
1497 
1504  public function isUserJsConfigPage() {
1505  return (
1506  $this->mNamespace === NS_USER
1507  && $this->isSubpage()
1509  );
1510  }
1511 
1518  public function isSiteCssConfigPage() {
1519  return (
1520  $this->mNamespace === NS_MEDIAWIKI
1521  && (
1523  // paranoia - a MediaWiki: namespace page with mismatching extension and content
1524  // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1525  || substr( $this->mDbkeyform, -4 ) === '.css'
1526  )
1527  );
1528  }
1529 
1536  public function isSiteJsonConfigPage() {
1537  return (
1538  $this->mNamespace === NS_MEDIAWIKI
1539  && (
1541  // paranoia - a MediaWiki: namespace page with mismatching extension and content
1542  // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1543  || substr( $this->mDbkeyform, -5 ) === '.json'
1544  )
1545  );
1546  }
1547 
1554  public function isSiteJsConfigPage() {
1555  return (
1556  $this->mNamespace === NS_MEDIAWIKI
1557  && (
1559  // paranoia - a MediaWiki: namespace page with mismatching extension and content
1560  // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1561  || substr( $this->mDbkeyform, -3 ) === '.js'
1562  )
1563  );
1564  }
1565 
1572  public function isRawHtmlMessage() {
1573  global $wgRawHtmlMessages;
1574 
1575  if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1576  return false;
1577  }
1578  $message = lcfirst( $this->getRootTitle()->getDBkey() );
1579  return in_array( $message, $wgRawHtmlMessages, true );
1580  }
1581 
1587  public function isTalkPage() {
1588  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1589  isTalk( $this->mNamespace );
1590  }
1591 
1603  public function getTalkPage() {
1604  // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1605  // Instead of failing on invalid titles, let's just log the issue for now.
1606  // See the discussion on T227817.
1607 
1608  // Is this the same title?
1609  $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
1610  if ( $this->mNamespace == $talkNS ) {
1611  return $this;
1612  }
1613 
1614  $title = self::makeTitle( $talkNS, $this->mDbkeyform );
1615 
1616  $this->warnIfPageCannotExist( $title, __METHOD__ );
1617 
1618  return $title;
1619  // TODO: replace the above with the code below:
1620  // return self::castFromLinkTarget(
1621  // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1622  }
1623 
1633  public function getTalkPageIfDefined() {
1634  if ( !$this->canHaveTalkPage() ) {
1635  return null;
1636  }
1637 
1638  return $this->getTalkPage();
1639  }
1640 
1648  public function getSubjectPage() {
1649  // Is this the same title?
1650  $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
1651  ->getSubject( $this->mNamespace );
1652  if ( $this->mNamespace == $subjectNS ) {
1653  return $this;
1654  }
1655  // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1656  // Instead of failing on invalid titles, let's just log the issue for now.
1657  // See the discussion on T227817.
1658  $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
1659 
1660  $this->warnIfPageCannotExist( $title, __METHOD__ );
1661 
1662  return $title;
1663  // TODO: replace the above with the code below:
1664  // return self::castFromLinkTarget(
1665  // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1666  }
1667 
1674  private function warnIfPageCannotExist( Title $title, $method ) {
1675  if ( $this->getText() == '' ) {
1676  wfLogWarning(
1677  $method . ': called on empty title ' . $this->getFullText() . ', returning '
1678  . $title->getFullText()
1679  );
1680 
1681  return true;
1682  }
1683 
1684  if ( $this->getInterwiki() !== '' ) {
1685  wfLogWarning(
1686  $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1687  . $title->getFullText()
1688  );
1689 
1690  return true;
1691  }
1692 
1693  return false;
1694  }
1695 
1705  public function getOtherPage() {
1706  // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1707  // until their semantics has become exactly the same.
1708  // See the discussion on T227817.
1709  if ( $this->isSpecialPage() ) {
1710  throw new MWException( 'Special pages cannot have other pages' );
1711  }
1712  if ( $this->isTalkPage() ) {
1713  return $this->getSubjectPage();
1714  } else {
1715  if ( !$this->canHaveTalkPage() ) {
1716  throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1717  }
1718  return $this->getTalkPage();
1719  }
1720  // TODO: replace the above with the code below:
1721  // return self::castFromLinkTarget(
1722  // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1723  }
1724 
1730  public function getDefaultNamespace() {
1731  return $this->mDefaultNamespace;
1732  }
1733 
1741  public function getFragment() {
1742  return $this->mFragment;
1743  }
1744 
1751  public function hasFragment() {
1752  return $this->mFragment !== '';
1753  }
1754 
1760  public function getFragmentForURL() {
1761  if ( !$this->hasFragment() ) {
1762  return '';
1763  } elseif ( $this->isExternal() ) {
1764  // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1765  // so we treat it like a local interwiki.
1766  $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1767  if ( $interwiki && !$interwiki->isLocal() ) {
1768  return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1769  }
1770  }
1771 
1772  return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1773  }
1774 
1787  public function setFragment( $fragment ) {
1788  $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1789  }
1790 
1798  public function createFragmentTarget( $fragment ) {
1799  return self::makeTitle(
1800  $this->mNamespace,
1801  $this->getText(),
1802  $fragment,
1803  $this->mInterwiki
1804  );
1805  }
1806 
1814  private function prefix( $name ) {
1815  $p = '';
1816  if ( $this->isExternal() ) {
1817  $p = $this->mInterwiki . ':';
1818  }
1819 
1820  if ( $this->mNamespace != 0 ) {
1821  $nsText = $this->getNsText();
1822 
1823  if ( $nsText === false ) {
1824  // See T165149. Awkward, but better than erroneously linking to the main namespace.
1825  $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1826  getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1827  }
1828 
1829  $p .= $nsText . ':';
1830  }
1831  return $p . $name;
1832  }
1833 
1840  public function getPrefixedDBkey() {
1841  $s = $this->prefix( $this->mDbkeyform );
1842  $s = strtr( $s, ' ', '_' );
1843  return $s;
1844  }
1845 
1852  public function getPrefixedText() {
1853  if ( $this->prefixedText === null ) {
1854  $s = $this->prefix( $this->mTextform );
1855  $s = strtr( $s, '_', ' ' );
1856  $this->prefixedText = $s;
1857  }
1858  return $this->prefixedText;
1859  }
1860 
1866  public function __toString() {
1867  return $this->getPrefixedText();
1868  }
1869 
1876  public function getFullText() {
1877  $text = $this->getPrefixedText();
1878  if ( $this->hasFragment() ) {
1879  $text .= '#' . $this->mFragment;
1880  }
1881  return $text;
1882  }
1883 
1898  private function findSubpageDivider( $text, $dir ) {
1899  $top = strlen( $text ) - 1;
1900  $bottom = 0;
1901 
1902  while ( $bottom < $top && $text[$bottom] === '/' ) {
1903  $bottom++;
1904  }
1905 
1906  if ( $top < $bottom ) {
1907  return false;
1908  }
1909 
1910  if ( $dir > 0 ) {
1911  $idx = $bottom;
1912  while ( $idx <= $top && $text[$idx] !== '/' ) {
1913  $idx++;
1914  }
1915  } else {
1916  $idx = $top;
1917  while ( $idx > $bottom && $text[$idx] !== '/' ) {
1918  $idx--;
1919  }
1920  }
1921 
1922  if ( $idx < $bottom || $idx > $top ) {
1923  return false;
1924  }
1925 
1926  if ( $idx < 1 ) {
1927  return false;
1928  }
1929 
1930  return $idx;
1931  }
1932 
1937  private function hasSubpagesEnabled() {
1938  return MediaWikiServices::getInstance()->getNamespaceInfo()->
1939  hasSubpages( $this->mNamespace );
1940  }
1941 
1957  public function getRootText() {
1958  $text = $this->getText();
1959  if ( !$this->hasSubpagesEnabled() ) {
1960  return $text;
1961  }
1962 
1963  $firstSlashPos = $this->findSubpageDivider( $text, +1 );
1964  // Don't discard the real title if there's no subpage involved
1965  if ( $firstSlashPos === false ) {
1966  return $text;
1967  }
1968 
1969  return substr( $text, 0, $firstSlashPos );
1970  }
1971 
1984  public function getRootTitle() {
1985  $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1986  Assert::postcondition(
1987  $title !== null,
1988  'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1989  );
1990  return $title;
1991  }
1992 
2007  public function getBaseText() {
2008  $text = $this->getText();
2009  if ( !$this->hasSubpagesEnabled() ) {
2010  return $text;
2011  }
2012 
2013  $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2014  // Don't discard the real title if there's no subpage involved
2015  if ( $lastSlashPos === false ) {
2016  return $text;
2017  }
2018 
2019  return substr( $text, 0, $lastSlashPos );
2020  }
2021 
2034  public function getBaseTitle() {
2035  $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
2036  Assert::postcondition(
2037  $title !== null,
2038  'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
2039  );
2040  return $title;
2041  }
2042 
2054  public function getSubpageText() {
2055  $text = $this->getText();
2056  if ( !$this->hasSubpagesEnabled() ) {
2057  return $text;
2058  }
2059 
2060  $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2061  if ( $lastSlashPos === false ) {
2062  // T256922 - Return the title text if no subpages
2063  return $text;
2064  }
2065  return substr( $text, $lastSlashPos + 1 );
2066  }
2067 
2081  public function getSubpage( $text ) {
2082  return self::makeTitleSafe(
2083  $this->mNamespace,
2084  $this->getText() . '/' . $text,
2085  '',
2086  $this->mInterwiki
2087  );
2088  }
2089 
2095  public function getSubpageUrlForm() {
2096  $text = $this->getSubpageText();
2097  $text = wfUrlencode( strtr( $text, ' ', '_' ) );
2098  return $text;
2099  }
2100 
2106  public function getPrefixedURL() {
2107  $s = $this->prefix( $this->mDbkeyform );
2108  $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2109  return $s;
2110  }
2111 
2125  private static function fixUrlQueryArgs( $query, $query2 = false ) {
2126  if ( $query2 !== false ) {
2127  wfDeprecatedMsg( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
2128  "method called with a second parameter is deprecated since MediaWiki 1.19. " .
2129  "Add your parameter to an array passed as the first parameter.", "1.19" );
2130  }
2131  if ( is_array( $query ) ) {
2132  $query = wfArrayToCgi( $query );
2133  }
2134  if ( $query2 ) {
2135  if ( is_string( $query2 ) ) {
2136  // $query2 is a string, we will consider this to be
2137  // a deprecated $variant argument and add it to the query
2138  $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
2139  } else {
2140  $query2 = wfArrayToCgi( $query2 );
2141  }
2142  // If we have $query content add a & to it first
2143  if ( $query ) {
2144  $query .= '&';
2145  }
2146  // Now append the queries together
2147  $query .= $query2;
2148  }
2149  return $query;
2150  }
2151 
2163  public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
2164  $query = self::fixUrlQueryArgs( $query, $query2 );
2165 
2166  # Hand off all the decisions on urls to getLocalURL
2167  $url = $this->getLocalURL( $query );
2168 
2169  # Expand the url to make it a full url. Note that getLocalURL has the
2170  # potential to output full urls for a variety of reasons, so we use
2171  # wfExpandUrl instead of simply prepending $wgServer
2172  $url = wfExpandUrl( $url, $proto );
2173 
2174  # Finally, add the fragment.
2175  $url .= $this->getFragmentForURL();
2176  Hooks::runner()->onGetFullURL( $this, $url, $query );
2177  return $url;
2178  }
2179 
2196  public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2197  $target = $this;
2198  if ( $this->isExternal() ) {
2199  $target = SpecialPage::getTitleFor(
2200  'GoToInterwiki',
2201  $this->getPrefixedDBkey()
2202  );
2203  }
2204  return $target->getFullURL( $query, false, $proto );
2205  }
2206 
2230  public function getLocalURL( $query = '', $query2 = false ) {
2232 
2233  $query = self::fixUrlQueryArgs( $query, $query2 );
2234 
2235  $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2236  if ( $interwiki ) {
2237  $namespace = $this->getNsText();
2238  if ( $namespace != '' ) {
2239  # Can this actually happen? Interwikis shouldn't be parsed.
2240  # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2241  $namespace .= ':';
2242  }
2243  $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2244  $url = wfAppendQuery( $url, $query );
2245  } else {
2246  $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2247  if ( $query == '' ) {
2248  $url = str_replace( '$1', $dbkey, $wgArticlePath );
2249  Hooks::runner()->onGetLocalURL__Article( $this, $url );
2250  } else {
2252  $url = false;
2253  $matches = [];
2254 
2256 
2257  if ( $articlePaths
2258  && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2259  ) {
2260  $action = urldecode( $matches[2] );
2261  if ( isset( $articlePaths[$action] ) ) {
2262  $query = $matches[1];
2263  if ( isset( $matches[4] ) ) {
2264  $query .= $matches[4];
2265  }
2266  $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2267  if ( $query != '' ) {
2268  $url = wfAppendQuery( $url, $query );
2269  }
2270  }
2271  }
2272 
2273  if ( $url === false
2275  && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2276  && $this->getPageLanguage()->equals(
2277  MediaWikiServices::getInstance()->getContentLanguage() )
2278  && $this->getPageLanguageConverter()->hasVariants()
2279  ) {
2280  $variant = urldecode( $matches[1] );
2281  if ( $this->getPageLanguageConverter()->hasVariant( $variant ) ) {
2282  // Only do the variant replacement if the given variant is a valid
2283  // variant for the page's language.
2284  $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2285  $url = str_replace( '$1', $dbkey, $url );
2286  }
2287  }
2288 
2289  if ( $url === false ) {
2290  if ( $query == '-' ) {
2291  $query = '';
2292  }
2293  $url = "{$wgScript}?title={$dbkey}&{$query}";
2294  }
2295  }
2296  Hooks::runner()->onGetLocalURL__Internal( $this, $url, $query );
2297 
2298  // @todo FIXME: This causes breakage in various places when we
2299  // actually expected a local URL and end up with dupe prefixes.
2300  if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2301  $url = $wgServer . $url;
2302  }
2303  }
2304 
2305  if ( $wgMainPageIsDomainRoot && $this->isMainPage() && $query === '' ) {
2306  return '/';
2307  }
2308 
2309  Hooks::runner()->onGetLocalURL( $this, $url, $query );
2310  return $url;
2311  }
2312 
2330  public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2331  if ( $this->isExternal() || $proto !== false ) {
2332  $ret = $this->getFullURL( $query, $query2, $proto );
2333  } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2334  $ret = $this->getFragmentForURL();
2335  } else {
2336  $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2337  }
2338  return $ret;
2339  }
2340 
2355  public function getInternalURL( $query = '', $query2 = false ) {
2356  global $wgInternalServer, $wgServer;
2357  $query = self::fixUrlQueryArgs( $query, $query2 );
2358  $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2359  $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2360  Hooks::runner()->onGetInternalURL( $this, $url, $query );
2361  return $url;
2362  }
2363 
2377  public function getCanonicalURL( $query = '', $query2 = false ) {
2378  $query = self::fixUrlQueryArgs( $query, $query2 );
2379  $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2380  Hooks::runner()->onGetCanonicalURL( $this, $url, $query );
2381  return $url;
2382  }
2383 
2389  public function getEditURL() {
2390  if ( $this->isExternal() ) {
2391  return '';
2392  }
2393  $s = $this->getLocalURL( 'action=edit' );
2394 
2395  return $s;
2396  }
2397 
2405  public static function getFilteredRestrictionTypes( $exists = true ) {
2406  global $wgRestrictionTypes;
2407  $types = $wgRestrictionTypes;
2408  if ( $exists ) {
2409  # Remove the create restriction for existing titles
2410  $types = array_diff( $types, [ 'create' ] );
2411  } else {
2412  # Only the create and upload restrictions apply to non-existing titles
2413  $types = array_intersect( $types, [ 'create', 'upload' ] );
2414  }
2415  return $types;
2416  }
2417 
2423  public function getRestrictionTypes() {
2424  if ( $this->isSpecialPage() ) {
2425  return [];
2426  }
2427 
2428  $types = self::getFilteredRestrictionTypes( $this->exists() );
2429 
2430  if ( $this->mNamespace !== NS_FILE ) {
2431  # Remove the upload restriction for non-file titles
2432  $types = array_diff( $types, [ 'upload' ] );
2433  }
2434 
2435  Hooks::runner()->onTitleGetRestrictionTypes( $this, $types );
2436 
2437  wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2438  $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}" );
2439 
2440  return $types;
2441  }
2442 
2450  public function getTitleProtection() {
2451  $protection = $this->getTitleProtectionInternal();
2452  if ( $protection ) {
2453  if ( $protection['permission'] == 'sysop' ) {
2454  $protection['permission'] = 'editprotected'; // B/C
2455  }
2456  if ( $protection['permission'] == 'autoconfirmed' ) {
2457  $protection['permission'] = 'editsemiprotected'; // B/C
2458  }
2459  }
2460  return $protection;
2461  }
2462 
2473  protected function getTitleProtectionInternal() {
2474  // Can't protect pages in special namespaces
2475  if ( $this->mNamespace < 0 ) {
2476  return false;
2477  }
2478 
2479  // Can't protect pages that exist.
2480  if ( $this->exists() ) {
2481  return false;
2482  }
2483 
2484  if ( $this->mTitleProtection === null ) {
2485  $dbr = wfGetDB( DB_REPLICA );
2486  $commentStore = CommentStore::getStore();
2487  $commentQuery = $commentStore->getJoin( 'pt_reason' );
2488  $res = $dbr->select(
2489  [ 'protected_titles' ] + $commentQuery['tables'],
2490  [
2491  'user' => 'pt_user',
2492  'expiry' => 'pt_expiry',
2493  'permission' => 'pt_create_perm'
2494  ] + $commentQuery['fields'],
2495  [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2496  __METHOD__,
2497  [],
2498  $commentQuery['joins']
2499  );
2500 
2501  // fetchRow returns false if there are no rows.
2502  $row = $dbr->fetchRow( $res );
2503  if ( $row ) {
2504  $this->mTitleProtection = [
2505  'user' => $row['user'],
2506  'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2507  'permission' => $row['permission'],
2508  'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
2509  ];
2510  } else {
2511  $this->mTitleProtection = false;
2512  }
2513  }
2514  return $this->mTitleProtection;
2515  }
2516 
2520  public function deleteTitleProtection() {
2521  $dbw = wfGetDB( DB_MASTER );
2522 
2523  $dbw->delete(
2524  'protected_titles',
2525  [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2526  __METHOD__
2527  );
2528  $this->mTitleProtection = false;
2529  }
2530 
2538  public function isSemiProtected( $action = 'edit' ) {
2540 
2541  $restrictions = $this->getRestrictions( $action );
2543  if ( !$restrictions || !$semi ) {
2544  // Not protected, or all protection is full protection
2545  return false;
2546  }
2547 
2548  // Remap autoconfirmed to editsemiprotected for BC
2549  foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2550  $semi[$key] = 'editsemiprotected';
2551  }
2552  foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2553  $restrictions[$key] = 'editsemiprotected';
2554  }
2555 
2556  return !array_diff( $restrictions, $semi );
2557  }
2558 
2566  public function isProtected( $action = '' ) {
2567  global $wgRestrictionLevels;
2568 
2569  $restrictionTypes = $this->getRestrictionTypes();
2570 
2571  # Special pages have inherent protection
2572  if ( $this->isSpecialPage() ) {
2573  return true;
2574  }
2575 
2576  # Check regular protection levels
2577  foreach ( $restrictionTypes as $type ) {
2578  if ( $action == $type || $action == '' ) {
2579  $r = $this->getRestrictions( $type );
2580  foreach ( $wgRestrictionLevels as $level ) {
2581  if ( in_array( $level, $r ) && $level != '' ) {
2582  return true;
2583  }
2584  }
2585  }
2586  }
2587 
2588  return false;
2589  }
2590 
2599  public function isNamespaceProtected( User $user ) {
2600  global $wgNamespaceProtection;
2601 
2602  if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2603  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2604  foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2605  if ( !$permissionManager->userHasRight( $user, $right ) ) {
2606  return true;
2607  }
2608  }
2609  }
2610  return false;
2611  }
2612 
2618  public function isCascadeProtected() {
2619  list( $isCascadeProtected, ) = $this->getCascadeProtectionSources( false );
2620  return $isCascadeProtected;
2621  }
2622 
2632  public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2633  return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2634  }
2635 
2649  public function getCascadeProtectionSources( $getPages = true ) {
2650  $pagerestrictions = [];
2651 
2652  if ( $this->mCascadeSources !== null && $getPages ) {
2654  } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2655  return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2656  }
2657 
2658  $dbr = wfGetDB( DB_REPLICA );
2659 
2660  if ( $this->mNamespace === NS_FILE ) {
2661  $tables = [ 'imagelinks', 'page_restrictions' ];
2662  $where_clauses = [
2663  'il_to' => $this->mDbkeyform,
2664  'il_from=pr_page',
2665  'pr_cascade' => 1
2666  ];
2667  } else {
2668  $tables = [ 'templatelinks', 'page_restrictions' ];
2669  $where_clauses = [
2670  'tl_namespace' => $this->mNamespace,
2671  'tl_title' => $this->mDbkeyform,
2672  'tl_from=pr_page',
2673  'pr_cascade' => 1
2674  ];
2675  }
2676 
2677  if ( $getPages ) {
2678  $cols = [ 'pr_page', 'page_namespace', 'page_title',
2679  'pr_expiry', 'pr_type', 'pr_level' ];
2680  $where_clauses[] = 'page_id=pr_page';
2681  $tables[] = 'page';
2682  } else {
2683  $cols = [ 'pr_expiry' ];
2684  }
2685 
2686  $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2687 
2688  $sources = $getPages ? [] : false;
2689  $now = wfTimestampNow();
2690 
2691  foreach ( $res as $row ) {
2692  $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2693  if ( $expiry > $now ) {
2694  if ( $getPages ) {
2695  $page_id = $row->pr_page;
2696  $page_ns = $row->page_namespace;
2697  $page_title = $row->page_title;
2698  $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
2699  # Add groups needed for each restriction type if its not already there
2700  # Make sure this restriction type still exists
2701 
2702  if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2703  $pagerestrictions[$row->pr_type] = [];
2704  }
2705 
2706  if (
2707  isset( $pagerestrictions[$row->pr_type] )
2708  && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2709  ) {
2710  $pagerestrictions[$row->pr_type][] = $row->pr_level;
2711  }
2712  } else {
2713  $sources = true;
2714  }
2715  }
2716  }
2717 
2718  if ( $getPages ) {
2719  $this->mCascadeSources = $sources;
2720  $this->mCascadingRestrictions = $pagerestrictions;
2721  } else {
2722  $this->mHasCascadingRestrictions = $sources;
2723  }
2724 
2725  return [ $sources, $pagerestrictions ];
2726  }
2727 
2735  public function areRestrictionsLoaded() {
2737  }
2738 
2748  public function getRestrictions( $action ) {
2749  if ( !$this->mRestrictionsLoaded ) {
2750  $this->loadRestrictions();
2751  }
2752  return $this->mRestrictions[$action] ?? [];
2753  }
2754 
2762  public function getAllRestrictions() {
2763  if ( !$this->mRestrictionsLoaded ) {
2764  $this->loadRestrictions();
2765  }
2766  return $this->mRestrictions;
2767  }
2768 
2776  public function getRestrictionExpiry( $action ) {
2777  if ( !$this->mRestrictionsLoaded ) {
2778  $this->loadRestrictions();
2779  }
2780  return $this->mRestrictionsExpiry[$action] ?? false;
2781  }
2782 
2788  public function areRestrictionsCascading() {
2789  if ( !$this->mRestrictionsLoaded ) {
2790  $this->loadRestrictions();
2791  }
2792 
2794  }
2795 
2807  public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2808  // This function will only read rows from a table that we migrated away
2809  // from before adding READ_LATEST support to loadRestrictions, so we
2810  // don't need to support reading from DB_MASTER here.
2811  $dbr = wfGetDB( DB_REPLICA );
2812 
2813  $restrictionTypes = $this->getRestrictionTypes();
2814 
2815  foreach ( $restrictionTypes as $type ) {
2816  $this->mRestrictions[$type] = [];
2817  $this->mRestrictionsExpiry[$type] = 'infinity';
2818  }
2819 
2820  $this->mCascadeRestriction = false;
2821 
2822  # Backwards-compatibility: also load the restrictions from the page record (old format).
2823  if ( $oldFashionedRestrictions !== null ) {
2824  $this->mOldRestrictions = $oldFashionedRestrictions;
2825  }
2826 
2827  if ( $this->mOldRestrictions === false ) {
2828  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2829  $linkCache->addLinkObj( $this ); # in case we already had an article ID
2830  $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2831  }
2832 
2833  if ( $this->mOldRestrictions != '' ) {
2834  foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2835  $temp = explode( '=', trim( $restrict ) );
2836  if ( count( $temp ) == 1 ) {
2837  // old old format should be treated as edit/move restriction
2838  $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2839  $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2840  } else {
2841  $restriction = trim( $temp[1] );
2842  if ( $restriction != '' ) { // some old entries are empty
2843  $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2844  }
2845  }
2846  }
2847  }
2848 
2849  if ( count( $rows ) ) {
2850  # Current system - load second to make them override.
2851  $now = wfTimestampNow();
2852 
2853  # Cycle through all the restrictions.
2854  foreach ( $rows as $row ) {
2855  // Don't take care of restrictions types that aren't allowed
2856  if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2857  continue;
2858  }
2859 
2860  $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2861 
2862  // Only apply the restrictions if they haven't expired!
2863  if ( !$expiry || $expiry > $now ) {
2864  $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2865  $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2866 
2867  $this->mCascadeRestriction = $this->mCascadeRestriction || $row->pr_cascade;
2868  }
2869  }
2870  }
2871 
2872  $this->mRestrictionsLoaded = true;
2873  }
2874 
2885  public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2886  $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
2887  if ( $this->mRestrictionsLoaded && !$readLatest ) {
2888  return;
2889  }
2890 
2891  $id = $this->getArticleID( $flags );
2892  if ( $id ) {
2893  $fname = __METHOD__;
2894  $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
2895  return iterator_to_array(
2896  $dbr->select(
2897  'page_restrictions',
2898  [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2899  [ 'pr_page' => $id ],
2900  $fname
2901  )
2902  );
2903  };
2904 
2905  if ( $readLatest ) {
2906  $dbr = wfGetDB( DB_MASTER );
2907  $rows = $loadRestrictionsFromDb( $dbr );
2908  } else {
2909  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2910  $rows = $cache->getWithSetCallback(
2911  // Page protections always leave a new null revision
2912  $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2913  $cache::TTL_DAY,
2914  function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2915  $dbr = wfGetDB( DB_REPLICA );
2916 
2917  $setOpts += Database::getCacheSetOptions( $dbr );
2918  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2919  if ( $lb->hasOrMadeRecentMasterChanges() ) {
2920  // @TODO: cleanup Title cache and caller assumption mess in general
2921  $ttl = WANObjectCache::TTL_UNCACHEABLE;
2922  }
2923 
2924  return $loadRestrictionsFromDb( $dbr );
2925  }
2926  );
2927  }
2928 
2929  $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2930  } else {
2931  $title_protection = $this->getTitleProtectionInternal();
2932 
2933  if ( $title_protection ) {
2934  $now = wfTimestampNow();
2935  $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
2936 
2937  if ( !$expiry || $expiry > $now ) {
2938  // Apply the restrictions
2939  $this->mRestrictionsExpiry['create'] = $expiry;
2940  $this->mRestrictions['create'] =
2941  explode( ',', trim( $title_protection['permission'] ) );
2942  } else { // Get rid of the old restrictions
2943  $this->mTitleProtection = false;
2944  }
2945  } else {
2946  $this->mRestrictionsExpiry['create'] = 'infinity';
2947  }
2948  $this->mRestrictionsLoaded = true;
2949  }
2950  }
2951 
2956  public function flushRestrictions() {
2957  $this->mRestrictionsLoaded = false;
2958  $this->mTitleProtection = null;
2959  }
2960 
2966  public static function purgeExpiredRestrictions() {
2967  if ( wfReadOnly() ) {
2968  return;
2969  }
2970 
2972  wfGetDB( DB_MASTER ),
2973  __METHOD__,
2974  function ( IDatabase $dbw, $fname ) {
2975  $config = MediaWikiServices::getInstance()->getMainConfig();
2976  $ids = $dbw->selectFieldValues(
2977  'page_restrictions',
2978  'pr_id',
2979  [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2980  $fname,
2981  [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2982  );
2983  if ( $ids ) {
2984  $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2985  }
2986  }
2987  ) );
2988 
2990  wfGetDB( DB_MASTER ),
2991  __METHOD__,
2992  function ( IDatabase $dbw, $fname ) {
2993  $dbw->delete(
2994  'protected_titles',
2995  [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2996  $fname
2997  );
2998  }
2999  ) );
3000  }
3001 
3007  public function hasSubpages() {
3008  if (
3009  !MediaWikiServices::getInstance()->getNamespaceInfo()->
3010  hasSubpages( $this->mNamespace )
3011  ) {
3012  # Duh
3013  return false;
3014  }
3015 
3016  # We dynamically add a member variable for the purpose of this method
3017  # alone to cache the result. There's no point in having it hanging
3018  # around uninitialized in every Title object; therefore we only add it
3019  # if needed and don't declare it statically.
3020  if ( $this->mHasSubpages === null ) {
3021  $this->mHasSubpages = false;
3022  $subpages = $this->getSubpages( 1 );
3023  if ( $subpages instanceof TitleArray ) {
3024  $this->mHasSubpages = (bool)$subpages->current();
3025  }
3026  }
3027 
3028  return $this->mHasSubpages;
3029  }
3030 
3038  public function getSubpages( $limit = -1 ) {
3039  if (
3040  !MediaWikiServices::getInstance()->getNamespaceInfo()->
3041  hasSubpages( $this->mNamespace )
3042  ) {
3043  return [];
3044  }
3045 
3046  $dbr = wfGetDB( DB_REPLICA );
3047  $conds = [ 'page_namespace' => $this->mNamespace ];
3048  $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3049  $options = [];
3050  if ( $limit > -1 ) {
3051  $options['LIMIT'] = $limit;
3052  }
3054  $dbr->select( 'page',
3055  [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3056  $conds,
3057  __METHOD__,
3058  $options
3059  )
3060  );
3061  }
3062 
3069  public function isDeleted() {
3070  return $this->getDeletedEditsCount();
3071  }
3072 
3079  public function getDeletedEditsCount() {
3080  if ( $this->mNamespace < 0 ) {
3081  $n = 0;
3082  } else {
3083  $dbr = wfGetDB( DB_REPLICA );
3084 
3085  $n = $dbr->selectField( 'archive', 'COUNT(*)',
3086  [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3087  __METHOD__
3088  );
3089  if ( $this->mNamespace === NS_FILE ) {
3090  $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3091  [ 'fa_name' => $this->mDbkeyform ],
3092  __METHOD__
3093  );
3094  }
3095  }
3096  return (int)$n;
3097  }
3098 
3105  public function isDeletedQuick() {
3106  return $this->hasDeletedEdits();
3107  }
3108 
3115  public function hasDeletedEdits() {
3116  if ( $this->mNamespace < 0 ) {
3117  return false;
3118  }
3119  $dbr = wfGetDB( DB_REPLICA );
3120  $deleted = (bool)$dbr->selectField( 'archive', '1',
3121  [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3122  __METHOD__
3123  );
3124  if ( !$deleted && $this->mNamespace === NS_FILE ) {
3125  $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3126  [ 'fa_name' => $this->mDbkeyform ],
3127  __METHOD__
3128  );
3129  }
3130  return $deleted;
3131  }
3132 
3140  public function getArticleID( $flags = 0 ) {
3141  if ( $this->mNamespace < 0 ) {
3142  $this->mArticleID = 0;
3143 
3144  return $this->mArticleID;
3145  }
3146 
3147  if ( $flags & self::GAID_FOR_UPDATE ) {
3148  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3149  $oldUpdate = $linkCache->forUpdate( true );
3150  $linkCache->clearLink( $this );
3151  $this->mArticleID = $linkCache->addLinkObj( $this );
3152  $linkCache->forUpdate( $oldUpdate );
3153  } elseif ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3154  // If mArticleID is >0, pageCond() will use it, making it impossible
3155  // for the call below to return a different result, e.g. after a
3156  // page move.
3157  $this->mArticleID = -1;
3158  $this->mArticleID = (int)$this->loadFieldFromDB( 'page_id', $flags );
3159  } elseif ( $this->mArticleID == -1 ) {
3160  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3161  $this->mArticleID = $linkCache->addLinkObj( $this );
3162  }
3163 
3164  return $this->mArticleID;
3165  }
3166 
3174  public function isRedirect( $flags = 0 ) {
3175  if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3176  $this->mRedirect = (bool)$this->loadFieldFromDB( 'page_is_redirect', $flags );
3177  } elseif ( $this->mRedirect === null ) {
3178  if ( $this->getArticleID( $flags ) ) {
3179  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3180  $linkCache->addLinkObj( $this ); // in case we already had an article ID
3181  // Note that LinkCache returns null if it thinks the page does not exist;
3182  // always trust the state of LinkCache over that of this Title instance.
3183  $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3184  } else {
3185  $this->mRedirect = false;
3186  }
3187  }
3188 
3189  return $this->mRedirect;
3190  }
3191 
3199  public function getLength( $flags = 0 ) {
3200  if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3201  $this->mLength = (int)$this->loadFieldFromDB( 'page_len', $flags );
3202  } else {
3203  if ( $this->mLength != -1 ) {
3204  return $this->mLength;
3205  } elseif ( !$this->getArticleID( $flags ) ) {
3206  $this->mLength = 0;
3207  return $this->mLength;
3208  }
3209 
3210  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3211  $linkCache->addLinkObj( $this ); // in case we already had an article ID
3212  // Note that LinkCache returns null if it thinks the page does not exist;
3213  // always trust the state of LinkCache over that of this Title instance.
3214  $this->mLength = (int)$linkCache->getGoodLinkFieldObj( $this, 'length' );
3215  }
3216 
3217  return $this->mLength;
3218  }
3219 
3226  public function getLatestRevID( $flags = 0 ) {
3227  if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3228  $this->mLatestID = (int)$this->loadFieldFromDB( 'page_latest', $flags );
3229  } else {
3230  if ( $this->mLatestID !== false ) {
3231  return (int)$this->mLatestID;
3232  } elseif ( !$this->getArticleID( $flags ) ) {
3233  $this->mLatestID = 0;
3234 
3235  return $this->mLatestID;
3236  }
3237 
3238  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3239  $linkCache->addLinkObj( $this ); // in case we already had an article ID
3240  // Note that LinkCache returns null if it thinks the page does not exist;
3241  // always trust the state of LinkCache over that of this Title instance.
3242  $this->mLatestID = (int)$linkCache->getGoodLinkFieldObj( $this, 'revision' );
3243  }
3244 
3245  return $this->mLatestID;
3246  }
3247 
3261  public function resetArticleID( $id ) {
3262  if ( $id === false ) {
3263  $this->mArticleID = -1;
3264  } else {
3265  $this->mArticleID = (int)$id;
3266  }
3267  $this->mRestrictionsLoaded = false;
3268  $this->mRestrictions = [];
3269  $this->mOldRestrictions = false;
3270  $this->mRedirect = null;
3271  $this->mLength = -1;
3272  $this->mLatestID = false;
3273  $this->mContentModel = false;
3274  $this->mForcedContentModel = false;
3275  $this->mEstimateRevisions = null;
3276  $this->mPageLanguage = null;
3277  $this->mDbPageLanguage = false;
3278  $this->mIsBigDeletion = null;
3279 
3280  MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
3281  }
3282 
3283  public static function clearCaches() {
3284  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3285  $linkCache->clear();
3286 
3288  $titleCache->clear();
3289  }
3290 
3298  public static function capitalize( $text, $ns = NS_MAIN ) {
3299  $services = MediaWikiServices::getInstance();
3300  if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3301  return $services->getContentLanguage()->ucfirst( $text );
3302  } else {
3303  return $text;
3304  }
3305  }
3306 
3323  private function secureAndSplit( $text, $defaultNamespace = null ) {
3324  if ( $defaultNamespace === null ) {
3325  $defaultNamespace = $this->mDefaultNamespace;
3326  }
3327 
3328  // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3329  // the parsing code with Title, while avoiding massive refactoring.
3330  // @todo: get rid of secureAndSplit, refactor parsing code.
3331  // @note: getTitleParser() returns a TitleParser implementation which does not have a
3332  // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3334  $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3335  '@phan-var MediaWikiTitleCodec $titleCodec';
3336  // MalformedTitleException can be thrown here
3337  $parts = $titleCodec->splitTitleString( $text, $defaultNamespace );
3338 
3339  # Fill fields
3340  $this->setFragment( '#' . $parts['fragment'] );
3341  $this->mInterwiki = $parts['interwiki'];
3342  $this->mLocalInterwiki = $parts['local_interwiki'];
3343  $this->mNamespace = $parts['namespace'];
3344  $this->mDefaultNamespace = $defaultNamespace;
3345 
3346  $this->mDbkeyform = $parts['dbkey'];
3347  $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3348  $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3349 
3350  // splitTitleString() guarantees that this title is valid.
3351  $this->mIsValid = true;
3352 
3353  # We already know that some pages won't be in the database!
3354  if ( $this->isExternal() || $this->isSpecialPage() || $this->mTextform === '' ) {
3355  $this->mArticleID = 0;
3356  }
3357  }
3358 
3371  public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3372  if ( count( $options ) > 0 ) {
3373  $db = wfGetDB( DB_MASTER );
3374  } else {
3375  $db = wfGetDB( DB_REPLICA );
3376  }
3377 
3378  $res = $db->select(
3379  [ 'page', $table ],
3380  self::getSelectFields(),
3381  [
3382  "{$prefix}_from=page_id",
3383  "{$prefix}_namespace" => $this->mNamespace,
3384  "{$prefix}_title" => $this->mDbkeyform ],
3385  __METHOD__,
3386  $options
3387  );
3388 
3389  $retVal = [];
3390  if ( $res->numRows() ) {
3391  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3392  foreach ( $res as $row ) {
3393  $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3394  if ( $titleObj ) {
3395  $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3396  $retVal[] = $titleObj;
3397  }
3398  }
3399  }
3400  return $retVal;
3401  }
3402 
3413  public function getTemplateLinksTo( $options = [] ) {
3414  return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3415  }
3416 
3429  public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3430  $id = $this->getArticleID();
3431 
3432  # If the page doesn't exist; there can't be any link from this page
3433  if ( !$id ) {
3434  return [];
3435  }
3436 
3437  $db = wfGetDB( DB_REPLICA );
3438 
3439  $blNamespace = "{$prefix}_namespace";
3440  $blTitle = "{$prefix}_title";
3441 
3442  $pageQuery = WikiPage::getQueryInfo();
3443  $res = $db->select(
3444  [ $table, 'nestpage' => $pageQuery['tables'] ],
3445  array_merge(
3446  [ $blNamespace, $blTitle ],
3447  $pageQuery['fields']
3448  ),
3449  [ "{$prefix}_from" => $id ],
3450  __METHOD__,
3451  $options,
3452  [ 'nestpage' => [
3453  'LEFT JOIN',
3454  [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3455  ] ] + $pageQuery['joins']
3456  );
3457 
3458  $retVal = [];
3459  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3460  foreach ( $res as $row ) {
3461  if ( $row->page_id ) {
3462  $titleObj = self::newFromRow( $row );
3463  } else {
3464  $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3465  $linkCache->addBadLinkObj( $titleObj );
3466  }
3467  $retVal[] = $titleObj;
3468  }
3469 
3470  return $retVal;
3471  }
3472 
3483  public function getTemplateLinksFrom( $options = [] ) {
3484  return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3485  }
3486 
3495  public function getBrokenLinksFrom() {
3496  if ( $this->getArticleID() == 0 ) {
3497  # All links from article ID 0 are false positives
3498  return [];
3499  }
3500 
3501  $dbr = wfGetDB( DB_REPLICA );
3502  $res = $dbr->select(
3503  [ 'page', 'pagelinks' ],
3504  [ 'pl_namespace', 'pl_title' ],
3505  [
3506  'pl_from' => $this->getArticleID(),
3507  'page_namespace IS NULL'
3508  ],
3509  __METHOD__, [],
3510  [
3511  'page' => [
3512  'LEFT JOIN',
3513  [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3514  ]
3515  ]
3516  );
3517 
3518  $retVal = [];
3519  foreach ( $res as $row ) {
3520  $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3521  }
3522  return $retVal;
3523  }
3524 
3531  public function getCdnUrls() {
3532  $htmlCache = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
3533  return $htmlCache->getUrls( $this );
3534  }
3535 
3540  public function purgeSquid() {
3541  $htmlCache = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
3542  $htmlCache->purgeTitleUrls( $this, $htmlCache::PURGE_INTENT_TXROUND_REFLECTED );
3543  }
3544 
3552  public function isSingleRevRedirect() {
3553  $dbw = wfGetDB( DB_MASTER );
3554  $dbw->startAtomic( __METHOD__ );
3555 
3556  $row = $dbw->selectRow(
3557  'page',
3558  self::getSelectFields(),
3559  $this->pageCond(),
3560  __METHOD__,
3561  [ 'FOR UPDATE' ]
3562  );
3563  // Update the cached fields
3564  $this->loadFromRow( $row );
3565 
3566  if ( $this->mRedirect && $this->mLatestID ) {
3567  $isSingleRevRedirect = !$dbw->selectField(
3568  'revision',
3569  '1',
3570  [ 'rev_page' => $this->mArticleID, 'rev_id != ' . (int)$this->mLatestID ],
3571  __METHOD__,
3572  [ 'FOR UPDATE' ]
3573  );
3574  } else {
3575  $isSingleRevRedirect = false;
3576  }
3577 
3578  $dbw->endAtomic( __METHOD__ );
3579 
3580  return $isSingleRevRedirect;
3581  }
3582 
3590  public function getParentCategories() {
3591  $data = [];
3592 
3593  $titleKey = $this->getArticleID();
3594 
3595  if ( $titleKey === 0 ) {
3596  return $data;
3597  }
3598 
3599  $dbr = wfGetDB( DB_REPLICA );
3600 
3601  $res = $dbr->select(
3602  'categorylinks',
3603  'cl_to',
3604  [ 'cl_from' => $titleKey ],
3605  __METHOD__
3606  );
3607 
3608  if ( $res->numRows() > 0 ) {
3609  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
3610  foreach ( $res as $row ) {
3611  // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3612  $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
3613  $this->getFullText();
3614  }
3615  }
3616  return $data;
3617  }
3618 
3625  public function getParentCategoryTree( $children = [] ) {
3626  $stack = [];
3627  $parents = $this->getParentCategories();
3628 
3629  if ( $parents ) {
3630  foreach ( $parents as $parent => $current ) {
3631  if ( array_key_exists( $parent, $children ) ) {
3632  # Circular reference
3633  $stack[$parent] = [];
3634  } else {
3635  $nt = self::newFromText( $parent );
3636  if ( $nt ) {
3637  $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3638  }
3639  }
3640  }
3641  }
3642 
3643  return $stack;
3644  }
3645 
3652  public function pageCond() {
3653  if ( $this->mArticleID > 0 ) {
3654  // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3655  return [ 'page_id' => $this->mArticleID ];
3656  } else {
3657  return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3658  }
3659  }
3660 
3668  private function getRelativeRevisionID( $revId, $flags, $dir ) {
3669  $rl = MediaWikiServices::getInstance()->getRevisionLookup();
3670  $rev = $rl->getRevisionById( $revId, $flags );
3671  if ( !$rev ) {
3672  return false;
3673  }
3674 
3675  $oldRev = ( $dir === 'next' )
3676  ? $rl->getNextRevision( $rev, $flags )
3677  : $rl->getPreviousRevision( $rev, $flags );
3678 
3679  return $oldRev ? $oldRev->getId() : false;
3680  }
3681 
3690  public function getPreviousRevisionID( $revId, $flags = 0 ) {
3691  return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3692  }
3693 
3702  public function getNextRevisionID( $revId, $flags = 0 ) {
3703  return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3704  }
3705 
3713  public function getFirstRevision( $flags = 0 ) {
3714  wfDeprecated( __METHOD__, '1.35' );
3715  $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
3716  $rev = MediaWikiServices::getInstance()
3717  ->getRevisionLookup()
3718  ->getFirstRevision( $this, $flags );
3719  return $rev ? new Revision( $rev ) : null;
3720  }
3721 
3729  public function getEarliestRevTime( $flags = 0 ) {
3730  $rev = MediaWikiServices::getInstance()
3731  ->getRevisionLookup()
3732  ->getFirstRevision( $this, $flags );
3733  return $rev ? $rev->getTimestamp() : null;
3734  }
3735 
3741  public function isNewPage() {
3742  $dbr = wfGetDB( DB_REPLICA );
3743  return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3744  }
3745 
3751  public function isBigDeletion() {
3752  global $wgDeleteRevisionsLimit;
3753 
3754  if ( !$wgDeleteRevisionsLimit ) {
3755  return false;
3756  }
3757 
3758  if ( $this->mIsBigDeletion === null ) {
3759  $dbr = wfGetDB( DB_REPLICA );
3760 
3761  $revCount = $dbr->selectRowCount(
3762  'revision',
3763  '1',
3764  [ 'rev_page' => $this->getArticleID() ],
3765  __METHOD__,
3766  [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
3767  );
3768 
3769  $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
3770  }
3771 
3772  return $this->mIsBigDeletion;
3773  }
3774 
3780  public function estimateRevisionCount() {
3781  if ( !$this->exists() ) {
3782  return 0;
3783  }
3784 
3785  if ( $this->mEstimateRevisions === null ) {
3786  $dbr = wfGetDB( DB_REPLICA );
3787  $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
3788  [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
3789  }
3790 
3792  }
3793 
3805  public function countRevisionsBetween( $old, $new, $max = null ) {
3806  wfDeprecated( __METHOD__, '1.35' );
3807  if ( !( $old instanceof Revision ) ) {
3808  $old = Revision::newFromTitle( $this, (int)$old );
3809  }
3810  if ( !( $new instanceof Revision ) ) {
3811  $new = Revision::newFromTitle( $this, (int)$new );
3812  }
3813  if ( !$old || !$new ) {
3814  return 0; // nothing to compare
3815  }
3816  return MediaWikiServices::getInstance()
3817  ->getRevisionStore()
3818  ->countRevisionsBetween(
3819  $this->getArticleID(),
3820  $old->getRevisionRecord(),
3821  $new->getRevisionRecord(),
3822  $max
3823  );
3824  }
3825 
3843  public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3844  wfDeprecated( __METHOD__, '1.35' );
3845  if ( !( $old instanceof Revision ) ) {
3846  $old = Revision::newFromTitle( $this, (int)$old );
3847  }
3848  if ( !( $new instanceof Revision ) ) {
3849  $new = Revision::newFromTitle( $this, (int)$new );
3850  }
3851  try {
3852  $users = MediaWikiServices::getInstance()
3853  ->getRevisionStore()
3854  ->getAuthorsBetween(
3855  $this->getArticleID(),
3856  $old->getRevisionRecord(),
3857  $new->getRevisionRecord(),
3858  null,
3859  $limit,
3860  $options
3861  );
3862  return array_map( function ( UserIdentity $user ) {
3863  return $user->getName();
3864  }, $users );
3865  } catch ( InvalidArgumentException $e ) {
3866  return null; // b/c
3867  }
3868  }
3869 
3886  public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3887  wfDeprecated( __METHOD__, '1.35' );
3888  $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3889  return $authors ? count( $authors ) : 0;
3890  }
3891 
3898  public function equals( LinkTarget $title ) {
3899  // Note: === is necessary for proper matching of number-like titles.
3900  return $this->mInterwiki === $title->getInterwiki()
3901  && $this->mNamespace == $title->getNamespace()
3902  && $this->mDbkeyform === $title->getDBkey();
3903  }
3904 
3911  public function isSubpageOf( Title $title ) {
3912  return $this->mInterwiki === $title->mInterwiki
3913  && $this->mNamespace == $title->mNamespace
3914  && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
3915  }
3916 
3927  public function exists( $flags = 0 ) {
3928  $exists = $this->getArticleID( $flags ) != 0;
3929  Hooks::runner()->onTitleExists( $this, $exists );
3930  return $exists;
3931  }
3932 
3949  public function isAlwaysKnown() {
3950  $isKnown = null;
3951 
3962  Hooks::runner()->onTitleIsAlwaysKnown( $this, $isKnown );
3963 
3964  if ( $isKnown !== null ) {
3965  return $isKnown;
3966  }
3967 
3968  if ( $this->isExternal() ) {
3969  return true; // any interwiki link might be viewable, for all we know
3970  }
3971 
3972  $services = MediaWikiServices::getInstance();
3973  switch ( $this->mNamespace ) {
3974  case NS_MEDIA:
3975  case NS_FILE:
3976  // file exists, possibly in a foreign repo
3977  return (bool)$services->getRepoGroup()->findFile( $this );
3978  case NS_SPECIAL:
3979  // valid special page
3980  return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
3981  case NS_MAIN:
3982  // selflink, possibly with fragment
3983  return $this->mDbkeyform == '';
3984  case NS_MEDIAWIKI:
3985  // known system message
3986  return $this->hasSourceText() !== false;
3987  default:
3988  return false;
3989  }
3990  }
3991 
4003  public function isKnown() {
4004  return $this->isAlwaysKnown() || $this->exists();
4005  }
4006 
4012  public function hasSourceText() {
4013  if ( $this->exists() ) {
4014  return true;
4015  }
4016 
4017  if ( $this->mNamespace === NS_MEDIAWIKI ) {
4018  $services = MediaWikiServices::getInstance();
4019  // If the page doesn't exist but is a known system message, default
4020  // message content will be displayed, same for language subpages-
4021  // Use always content language to avoid loading hundreds of languages
4022  // to get the link color.
4023  $contLang = $services->getContentLanguage();
4024  list( $name, ) = $services->getMessageCache()->figureMessage(
4025  $contLang->lcfirst( $this->getText() )
4026  );
4027  $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4028  return $message->exists();
4029  }
4030 
4031  return false;
4032  }
4033 
4071  public function getDefaultMessageText() {
4072  if ( $this->mNamespace !== NS_MEDIAWIKI ) { // Just in case
4073  return false;
4074  }
4075 
4076  list( $name, $lang ) = MediaWikiServices::getInstance()->getMessageCache()->figureMessage(
4077  MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4078  );
4079  $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4080 
4081  if ( $message->exists() ) {
4082  return $message->plain();
4083  } else {
4084  return false;
4085  }
4086  }
4087 
4094  public function invalidateCache( $purgeTime = null ) {
4095  if ( wfReadOnly() ) {
4096  return false;
4097  }
4098  if ( $this->mArticleID === 0 ) {
4099  // avoid gap locking if we know it's not there
4100  return true;
4101  }
4102 
4103  $conds = $this->pageCond();
4105  new AutoCommitUpdate(
4106  wfGetDB( DB_MASTER ),
4107  __METHOD__,
4108  function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4109  $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4110  $dbw->update(
4111  'page',
4112  [ 'page_touched' => $dbTimestamp ],
4113  $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4114  $fname
4115  );
4116 
4117  MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4118 
4120  $this, null, null, $dbw->getDomainID() );
4121  }
4122  ),
4124  );
4125 
4126  return true;
4127  }
4128 
4134  public function touchLinks() {
4135  $jobs = [];
4137  $this,
4138  'pagelinks',
4139  [ 'causeAction' => 'page-touch' ]
4140  );
4141  if ( $this->mNamespace === NS_CATEGORY ) {
4143  $this,
4144  'categorylinks',
4145  [ 'causeAction' => 'category-touch' ]
4146  );
4147  }
4148 
4149  JobQueueGroup::singleton()->lazyPush( $jobs );
4150  }
4151 
4158  public function getTouched( $db = null ) {
4159  if ( $db === null ) {
4160  $db = wfGetDB( DB_REPLICA );
4161  }
4162  $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4163  return $touched;
4164  }
4165 
4174  public function getNotificationTimestamp( User $user ) {
4175  return MediaWikiServices::getInstance()
4176  ->getWatchlistNotificationManager()
4177  ->getTitleNotificationTimestamp( $user, $this );
4178  }
4179 
4186  public function getNamespaceKey( $prepend = 'nstab-' ) {
4187  // Gets the subject namespace of this title
4188  $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
4189  $subjectNS = $nsInfo->getSubject( $this->mNamespace );
4190  // Prefer canonical namespace name for HTML IDs
4191  $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4192  if ( $namespaceKey === false ) {
4193  // Fallback to localised text
4194  $namespaceKey = $this->getSubjectNsText();
4195  }
4196  // Makes namespace key lowercase
4197  $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4198  // Uses main
4199  if ( $namespaceKey == '' ) {
4200  $namespaceKey = 'main';
4201  }
4202  // Changes file to image for backwards compatibility
4203  if ( $namespaceKey == 'file' ) {
4204  $namespaceKey = 'image';
4205  }
4206  return $prepend . $namespaceKey;
4207  }
4208 
4215  public function getRedirectsHere( $ns = null ) {
4216  $redirs = [];
4217 
4218  $dbr = wfGetDB( DB_REPLICA );
4219  $where = [
4220  'rd_namespace' => $this->mNamespace,
4221  'rd_title' => $this->mDbkeyform,
4222  'rd_from = page_id'
4223  ];
4224  if ( $this->isExternal() ) {
4225  $where['rd_interwiki'] = $this->mInterwiki;
4226  } else {
4227  $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4228  }
4229  if ( $ns !== null ) {
4230  $where['page_namespace'] = $ns;
4231  }
4232 
4233  $res = $dbr->select(
4234  [ 'redirect', 'page' ],
4235  [ 'page_namespace', 'page_title' ],
4236  $where,
4237  __METHOD__
4238  );
4239 
4240  foreach ( $res as $row ) {
4241  $redirs[] = self::newFromRow( $row );
4242  }
4243  return $redirs;
4244  }
4245 
4251  public function isValidRedirectTarget() {
4253 
4254  if ( $this->isSpecialPage() ) {
4255  // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4256  if ( $this->isSpecial( 'Userlogout' ) ) {
4257  return false;
4258  }
4259 
4260  foreach ( $wgInvalidRedirectTargets as $target ) {
4261  if ( $this->isSpecial( $target ) ) {
4262  return false;
4263  }
4264  }
4265  }
4266 
4267  return true;
4268  }
4269 
4275  public function getBacklinkCache() {
4276  return BacklinkCache::get( $this );
4277  }
4278 
4284  public function canUseNoindex() {
4286 
4287  $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4288  MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
4289 
4290  return !in_array( $this->mNamespace, $bannedNamespaces );
4291  }
4292 
4303  public function getCategorySortkey( $prefix = '' ) {
4304  $unprefixed = $this->getText();
4305 
4306  // Anything that uses this hook should only depend
4307  // on the Title object passed in, and should probably
4308  // tell the users to run updateCollations.php --force
4309  // in order to re-sort existing category relations.
4310  Hooks::runner()->onGetDefaultSortkey( $this, $unprefixed );
4311  if ( $prefix !== '' ) {
4312  # Separate with a line feed, so the unprefixed part is only used as
4313  # a tiebreaker when two pages have the exact same prefix.
4314  # In UCA, tab is the only character that can sort above LF
4315  # so we strip both of them from the original prefix.
4316  $prefix = strtr( $prefix, "\n\t", ' ' );
4317  return "$prefix\n$unprefixed";
4318  }
4319  return $unprefixed;
4320  }
4321 
4329  private function getDbPageLanguageCode() {
4330  global $wgPageLanguageUseDB;
4331 
4332  // check, if the page language could be saved in the database, and if so and
4333  // the value is not requested already, lookup the page language using LinkCache
4334  if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4335  $linkCache = MediaWikiServices::getInstance()->getLinkCache();
4336  $linkCache->addLinkObj( $this );
4337  $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4338  }
4339 
4340  return $this->mDbPageLanguage;
4341  }
4342 
4351  public function getPageLanguage() {
4352  global $wgLang, $wgLanguageCode;
4353  if ( $this->isSpecialPage() ) {
4354  // special pages are in the user language
4355  return $wgLang;
4356  }
4357 
4358  // Checking if DB language is set
4359  $dbPageLanguage = $this->getDbPageLanguageCode();
4360  if ( $dbPageLanguage ) {
4361  return wfGetLangObj( $dbPageLanguage );
4362  }
4363 
4364  if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4365  // Note that this may depend on user settings, so the cache should
4366  // be only per-request.
4367  // NOTE: ContentHandler::getPageLanguage() may need to load the
4368  // content to determine the page language!
4369  // Checking $wgLanguageCode hasn't changed for the benefit of unit
4370  // tests.
4371  $contentHandler = MediaWikiServices::getInstance()
4372  ->getContentHandlerFactory()
4373  ->getContentHandler( $this->getContentModel() );
4374  $langObj = $contentHandler->getPageLanguage( $this );
4375  $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4376  } else {
4377  $langObj = MediaWikiServices::getInstance()->getLanguageFactory()
4378  ->getLanguage( $this->mPageLanguage[0] );
4379  }
4380 
4381  return $langObj;
4382  }
4383 
4392  public function getPageViewLanguage() {
4393  global $wgLang;
4394 
4395  if ( $this->isSpecialPage() ) {
4396  // If the user chooses a variant, the content is actually
4397  // in a language whose code is the variant code.
4398  $variant = $this->getLanguageConverter( $wgLang )->getPreferredVariant();
4399  if ( $wgLang->getCode() !== $variant ) {
4400  return MediaWikiServices::getInstance()->getLanguageFactory()
4401  ->getLanguage( $variant );
4402  }
4403 
4404  return $wgLang;
4405  }
4406 
4407  // Checking if DB language is set
4408  $dbPageLanguage = $this->getDbPageLanguageCode();
4409  if ( $dbPageLanguage ) {
4410  $pageLang = wfGetLangObj( $dbPageLanguage );
4411  $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
4412  if ( $pageLang->getCode() !== $variant ) {
4413  $pageLang = MediaWikiServices::getInstance()->getLanguageFactory()
4414  ->getLanguage( $variant );
4415  }
4416 
4417  return $pageLang;
4418  }
4419 
4420  // @note Can't be cached persistently, depends on user settings.
4421  // @note ContentHandler::getPageViewLanguage() may need to load the
4422  // content to determine the page language!
4423  $contentHandler = MediaWikiServices::getInstance()
4424  ->getContentHandlerFactory()
4425  ->getContentHandler( $this->getContentModel() );
4426  $pageLang = $contentHandler->getPageViewLanguage( $this );
4427  return $pageLang;
4428  }
4429 
4440  public function getEditNotices( $oldid = 0 ) {
4441  $notices = [];
4442 
4443  // Optional notice for the entire namespace
4444  $editnotice_ns = 'editnotice-' . $this->mNamespace;
4445  $msg = wfMessage( $editnotice_ns );
4446  if ( $msg->exists() ) {
4447  $html = $msg->parseAsBlock();
4448  // Edit notices may have complex logic, but output nothing (T91715)
4449  if ( trim( $html ) !== '' ) {
4450  $notices[$editnotice_ns] = Html::rawElement(
4451  'div',
4452  [ 'class' => [
4453  'mw-editnotice',
4454  'mw-editnotice-namespace',
4455  Sanitizer::escapeClass( "mw-$editnotice_ns" )
4456  ] ],
4457  $html
4458  );
4459  }
4460  }
4461 
4462  if (
4463  MediaWikiServices::getInstance()->getNamespaceInfo()->
4464  hasSubpages( $this->mNamespace )
4465  ) {
4466  // Optional notice for page itself and any parent page
4467  $editnotice_base = $editnotice_ns;
4468  foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
4469  $editnotice_base .= '-' . $part;
4470  $msg = wfMessage( $editnotice_base );
4471  if ( $msg->exists() ) {
4472  $html = $msg->parseAsBlock();
4473  if ( trim( $html ) !== '' ) {
4474  $notices[$editnotice_base] = Html::rawElement(
4475  'div',
4476  [ 'class' => [
4477  'mw-editnotice',
4478  'mw-editnotice-base',
4479  Sanitizer::escapeClass( "mw-$editnotice_base" )
4480  ] ],
4481  $html
4482  );
4483  }
4484  }
4485  }
4486  } else {
4487  // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4488  $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
4489  $msg = wfMessage( $editnoticeText );
4490  if ( $msg->exists() ) {
4491  $html = $msg->parseAsBlock();
4492  if ( trim( $html ) !== '' ) {
4493  $notices[$editnoticeText] = Html::rawElement(
4494  'div',
4495  [ 'class' => [
4496  'mw-editnotice',
4497  'mw-editnotice-page',
4498  Sanitizer::escapeClass( "mw-$editnoticeText" )
4499  ] ],
4500  $html
4501  );
4502  }
4503  }
4504  }
4505 
4506  Hooks::runner()->onTitleGetEditNotices( $this, $oldid, $notices );
4507  return $notices;
4508  }
4509 
4515  private function loadFieldFromDB( $field, $flags ) {
4516  if ( !in_array( $field, self::getSelectFields(), true ) ) {
4517  return false; // field does not exist
4518  }
4519 
4520  $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
4521  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
4522 
4523  return wfGetDB( $index )->selectField(
4524  'page',
4525  $field,
4526  $this->pageCond(),
4527  __METHOD__,
4528  $options
4529  );
4530  }
4531 
4535  public function __sleep() {
4536  return [
4537  'mNamespace',
4538  'mDbkeyform',
4539  'mFragment',
4540  'mInterwiki',
4541  'mLocalInterwiki',
4542  'mDefaultNamespace',
4543  ];
4544  }
4545 
4546  public function __wakeup() {
4547  $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4548  $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4549  $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4550  }
4551 
4552 }
Title\$mLocalInterwiki
bool $mLocalInterwiki
Was this Title created from a string with a local interwiki prefix?
Definition: Title.php:86
Title\$mRestrictions
array $mRestrictions
Array of groups allowed to edit this article.
Definition: Title.php:112
Title\canHaveTalkPage
canHaveTalkPage()
Can this title have a corresponding talk page?
Definition: Title.php:1174
Title\getTitleProtection
getTitleProtection()
Is this title subject to title protection? Title protection is the one applied against creation of su...
Definition: Title.php:2450
Title\canUseNoindex
canUseNoindex()
Whether the magic words INDEX and NOINDEX function for this page.
Definition: Title.php:4284
Title\getLocalURL
getLocalURL( $query='', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
Definition: Title.php:2230
CONTENT_MODEL_JSON
const CONTENT_MODEL_JSON
Definition: Defines.php:228
Title\isSemiProtected
isSemiProtected( $action='edit')
Is this page "semi-protected" - the only protection levels are listed in $wgSemiprotectedRestrictionL...
Definition: Title.php:2538
Title\$mHasCascadingRestrictions
bool $mHasCascadingRestrictions
Are cascading restrictions in effect on this page?
Definition: Title.php:132
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:50
Title\isNamespaceProtected
isNamespaceProtected(User $user)
Determines if $user is unable to edit this page because it has been protected by $wgNamespaceProtecti...
Definition: Title.php:2599
Title\getTalkNsText
getTalkNsText()
Get the namespace text of the talk page.
Definition: Title.php:1157
Title\getSubpageText
getSubpageText()
Get the lowest-level subpage name, i.e.
Definition: Title.php:2054
MediaWiki\Linker\LinkTarget\getInterwiki
getInterwiki()
The interwiki component of this LinkTarget.
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:328
Title\isBigDeletion
isBigDeletion()
Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit.
Definition: Title.php:3751
Title\getNextRevisionID
getNextRevisionID( $revId, $flags=0)
Get the revision ID of the next revision.
Definition: Title.php:3702
PROTO_CANONICAL
const PROTO_CANONICAL
Definition: Defines.php:212
Title\areCascadeProtectionSourcesLoaded
areCascadeProtectionSourcesLoaded( $getPages=true)
Determines whether cascading protection sources have already been loaded from the database.
Definition: Title.php:2632
MediaWiki\Linker\LinkTarget\getText
getText()
Returns the link in text form, without namespace prefix or fragment.
Title\getFilteredRestrictionTypes
static getFilteredRestrictionTypes( $exists=true)
Get a filtered list of all restriction types supported by this wiki.
Definition: Title.php:2405
Title\makeName
static makeName( $ns, $title, $fragment='', $interwiki='', $canonicalNamespace=false)
Make a prefixed DB key from a DB key and a namespace index.
Definition: Title.php:822
Title\getInternalURL
getInternalURL( $query='', $query2=false)
Get the URL form for an internal link.
Definition: Title.php:2355
Title\getFragment
getFragment()
Get the Title fragment (i.e.
Definition: Title.php:1741
$wgExemptFromUserRobotsControl
$wgExemptFromUserRobotsControl
An array of namespace keys in which the INDEX/__NOINDEX__ magic words will not function,...
Definition: DefaultSettings.php:8520
Title\getTalkPageIfDefined
getTalkPageIfDefined()
Get a Title object associated with the talk page of this article, if such a talk page can exist.
Definition: Title.php:1633
Title\inNamespace
inNamespace( $ns)
Returns true if the title is inside the specified namespace.
Definition: Title.php:1295
Title\$mForcedContentModel
bool $mForcedContentModel
If a content model was forced via setContentModel() this will be true to avoid having other code path...
Definition: Title.php:106
TitleArray\newFromResult
static newFromResult( $res)
Definition: TitleArray.php:42
Title\isMovable
isMovable()
Would anybody with sufficient privileges be able to move this page? Some pages just aren't movable.
Definition: Title.php:1357
Title\wasLocalInterwiki
wasLocalInterwiki()
Was this a local interwiki link?
Definition: Title.php:944
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
Title\inNamespaces
inNamespaces(... $namespaces)
Returns true if the title is inside one of the specified namespaces.
Definition: Title.php:1307
Title\isWikitextPage
isWikitextPage()
Does that page contain wikitext, or it is JS, CSS or whatever?
Definition: Title.php:1414
Title\isUserCssConfigPage
isUserCssConfigPage()
Is this a CSS "config" sub-page of a user page?
Definition: Title.php:1476
Title\getBacklinkCache
getBacklinkCache()
Get a backlink cache object.
Definition: Title.php:4275
Title\getPartialURL
getPartialURL()
Get the URL-encoded form of the main part.
Definition: Title.php:1016
$wgLegalTitleChars
$wgLegalTitleChars
Allowed title characters – regex character class Don't change this unless you know what you're doing.
Definition: DefaultSettings.php:4351
Title\clearCaches
static clearCaches()
Was this Title created from a string with a local interwiki prefix?
Definition: Title.php:3283
AutoCommitUpdate
Deferrable Update for closure/callback updates that should use auto-commit mode.
Definition: AutoCommitUpdate.php:9
Title\getTitleValue
getTitleValue()
Get a TitleValue object representing this Title.
Definition: Title.php:984
Title\estimateRevisionCount
estimateRevisionCount()
Get the approximate revision count of this page.
Definition: Title.php:3780
ResourceLoaderWikiModule\invalidateModuleCache
static invalidateModuleCache(Title $title, ?RevisionRecord $old, ?RevisionRecord $new, $domain)
Clear the preloadTitleInfo() cache for all wiki modules on this wiki on page change if it was a JS or...
Definition: ResourceLoaderWikiModule.php:545
Title\countRevisionsBetween
countRevisionsBetween( $old, $new, $max=null)
Get the number of revisions between the given revision.
Definition: Title.php:3805
Title\getPrefixedDBkey
getPrefixedDBkey()
Get the prefixed database key form.
Definition: Title.php:1840
Title\getDbPageLanguageCode
getDbPageLanguageCode()
Returns the page language code saved in the database, if $wgPageLanguageUseDB is set to true in Local...
Definition: Title.php:4329
Title\getSkinFromConfigSubpage
getSkinFromConfigSubpage()
Trim down a .css, .json, or .js subpage title to get the corresponding skin name.
Definition: Title.php:1460
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:207
Title\$mHasSubpages
bool $mHasSubpages
Whether a page has any subpages.
Definition: Title.php:168
Title\getTalkPage
getTalkPage()
Get a Title object associated with the talk page of this article.
Definition: Title.php:1603
Title\NEW_CLONE
const NEW_CLONE
Flag for use with factory methods like newFromLinkTarget() that have a $forceClone parameter.
Definition: Title.php:66
Title\getParentCategoryTree
getParentCategoryTree( $children=[])
Get a tree of parent categories.
Definition: Title.php:3625
CONTENT_MODEL_CSS
const CONTENT_MODEL_CSS
Definition: Defines.php:226
Title\fixUrlQueryArgs
static fixUrlQueryArgs( $query, $query2=false)
Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args get{Canonical,...
Definition: Title.php:2125
Title\fixSpecialName
fixSpecialName()
If the Title refers to a special page alias which is not the local default, resolve the alias,...
Definition: Title.php:1271
Title\getInterwikiLookup
static getInterwikiLookup()
B/C kludge: provide an InterwikiLookup for use by Title.
Definition: Title.php:226
Title\isUserJsConfigPage
isUserJsConfigPage()
Is this a JS "config" sub-page of a user page?
Definition: Title.php:1504
Title\touchLinks
touchLinks()
Update page_touched timestamps and send CDN purge messages for pages linking to this title.
Definition: Title.php:4134
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:308
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1852
Title\getTransWikiID
getTransWikiID()
Returns the DB name of the distant wiki which owns the object.
Definition: Title.php:967
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:106
Title\getArticleID
getArticleID( $flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
Definition: Title.php:3140
Title\getLinkURL
getLinkURL( $query='', $query2=false, $proto=false)
Get a URL that's the simplest URL that will be valid to link, locally, to the current Title.
Definition: Title.php:2330
Title\$mTitleValue
TitleValue null $mTitleValue
A corresponding TitleValue object.
Definition: Title.php:179
NS_FILE
const NS_FILE
Definition: Defines.php:75
Title\isTalkPage
isTalkPage()
Is this a talk page of some sort?
Definition: Title.php:1587
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1126
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
Sanitizer\decodeCharReferencesAndNormalize
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
Definition: Sanitizer.php:1249
$s
$s
Definition: mergeMessageFileList.php:184
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:96
Sanitizer\escapeClass
static escapeClass( $class)
Given a value, escape it so that it can be used as a CSS class and return it.
Definition: Sanitizer.php:976
Title\getNotificationTimestamp
getNotificationTimestamp(User $user)
Get the timestamp when this page was updated since the user last saw it.
Definition: Title.php:4174
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1087
Title\isExternal
isExternal()
Is this Title interwiki?
Definition: Title.php:924
DBAccessObjectUtils\getDBOptions
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
Definition: DBAccessObjectUtils.php:52
Title\loadRestrictionsFromRows
loadRestrictionsFromRows( $rows, $oldFashionedRestrictions=null)
Compiles list of active page restrictions from both page table (pre 1.10) and page_restrictions table...
Definition: Title.php:2807
Title\newMainPage
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:653
Title\getDefaultMessageText
getDefaultMessageText()
Get the default (plain) message contents for an page that overrides an interface message key.
Definition: Title.php:4071
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:224
Title\hasSourceText
hasSourceText()
Does this page have source text?
Definition: Title.php:4012
Title\loadFromRow
loadFromRow( $row)
Load Title object fields from a DB row.
Definition: Title.php:535
Title\setFragment
setFragment( $fragment)
Set the fragment for this title.
Definition: Title.php:1787
$res
$res
Definition: testCompression.php:57
IDBAccessObject
Interface for database access objects.
Definition: IDBAccessObject.php:57
Title\equals
equals(LinkTarget $title)
Compare with another title.
Definition: Title.php:3898
Title\$mIsBigDeletion
bool null $mIsBigDeletion
Would deleting this page be a big deletion?
Definition: Title.php:182
Title\convertByteClassToUnicodeClass
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
Definition: Title.php:716
Title\hasSubpagesEnabled
hasSubpagesEnabled()
Whether this Title's namespace has subpages enabled.
Definition: Title.php:1937
Title\__wakeup
__wakeup()
Was this Title created from a string with a local interwiki prefix?
Definition: Title.php:4546
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(Title $title, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:59
Title\getParentCategories
getParentCategories()
Get categories to which this Title belongs and return an array of categories' names.
Definition: Title.php:3590
Title\getLinksTo
getLinksTo( $options=[], $table='pagelinks', $prefix='pl')
Get an array of Title objects linking to this Title Also stores the IDs in the link cache.
Definition: Title.php:3371
Title\$mContentModel
bool string $mContentModel
ID of the page's content model, i.e.
Definition: Title.php:100
Title\getPageLanguageConverter
getPageLanguageConverter()
Shorthand for getting a Language Converter for page's language.
Definition: Title.php:202
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Title\isSiteCssConfigPage
isSiteCssConfigPage()
Is this a sitewide CSS "config" page?
Definition: Title.php:1518
MessageLocalizer
Interface for localizing messages in MediaWiki.
Definition: MessageLocalizer.php:29
Title\getNsText
getNsText()
Get the namespace text.
Definition: Title.php:1121
Title\$mRedirect
null bool $mRedirect
Is the article at this title a redirect?
Definition: Title.php:165
Title\$mDbkeyform
string $mDbkeyform
Main part with underscores.
Definition: Title.php:80
Title\$mUrlform
string $mUrlform
URL-encoded form of the main part.
Definition: Title.php:78
$dbr
$dbr
Definition: testCompression.php:54
Title\getLinksFrom
getLinksFrom( $options=[], $table='pagelinks', $prefix='pl')
Get an array of Title objects linked from this Title Also stores the IDs in the link cache.
Definition: Title.php:3429
Title\$mOldRestrictions
string bool $mOldRestrictions
Comma-separated set of permission keys indicating who can move or edit the page from the page table,...
Definition: Title.php:120
PathRouter\getActionPaths
static getActionPaths(array $actionPaths, $articlePath)
Definition: PathRouter.php:430
Wikimedia\Rdbms\IDatabase\update
update( $table, $set, $conds, $fname=__METHOD__, $options=[])
Update all rows in a table that match a given condition.
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:438
Revision
Definition: Revision.php:40
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
Title\loadFieldFromDB
loadFieldFromDB( $field, $flags)
Definition: Title.php:4515
Title\isCascadeProtected
isCascadeProtected()
Cascading protection: Return true if cascading restrictions apply to this page, false if not.
Definition: Title.php:2618
Revision\newFromTitle
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition: Revision.php:143
Title\getCdnUrls
getCdnUrls()
Get a list of URLs to purge from the CDN cache when this page changes.
Definition: Title.php:3531
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:58
Title\getOtherPage
getOtherPage()
Get the other title for this page, if this is a subject page get the talk page, if it is a subject pa...
Definition: Title.php:1705
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
Title\isSiteConfigPage
isSiteConfigPage()
Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the global UI.
Definition: Title.php:1432
Title\isUserJsonConfigPage
isUserJsonConfigPage()
Is this a JSON "config" sub-page of a user page?
Definition: Title.php:1490
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
ContentHandler\getDefaultModelFor
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title.
Definition: ContentHandler.php:194
$wgRawHtmlMessages
string[] $wgRawHtmlMessages
List of messages which might contain raw HTML.
Definition: DefaultSettings.php:9310
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:1025
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1059
Title\nameOf
static nameOf( $id)
Get the prefixed DB key associated with an ID.
Definition: Title.php:679
Title\$mDbPageLanguage
string bool null $mDbPageLanguage
The page language code from the database, null if not saved in the database or false if not loaded,...
Definition: Title.php:176
Title\isSpecial
isSpecial( $name)
Returns true if this title resolves to the named special page.
Definition: Title.php:1253
MWException
MediaWiki exception.
Definition: MWException.php:29
Title\getTitleFormatter
static getTitleFormatter()
B/C kludge: provide a TitleParser for use by Title.
Definition: Title.php:214
Title\isMainPage
isMainPage()
Is this the mainpage?
Definition: Title.php:1381
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
Title\getSubpage
getSubpage( $text)
Get the title for a subpage of the current page.
Definition: Title.php:2081
Title\getBaseTitle
getBaseTitle()
Get the base page name title, i.e.
Definition: Title.php:2034
Title\getNamespace
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1034
BacklinkCache\get
static get(Title $title)
Create a new BacklinkCache or reuse any existing one.
Definition: BacklinkCache.php:116
Title\newFromRow
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:523
Title\isConversionTable
isConversionTable()
Is this a conversion table for the LanguageConverter?
Definition: Title.php:1402
Title\isProtected
isProtected( $action='')
Does the title correspond to a protected article?
Definition: Title.php:2566
Title\flushRestrictions
flushRestrictions()
Flush the protection cache in this object and force reload from the database.
Definition: Title.php:2956
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2459
Title\getCategorySortkey
getCategorySortkey( $prefix='')
Returns the raw sort key to be used for categories, with the specified prefix.
Definition: Title.php:4303
Title\getInterwiki
getInterwiki()
Get the interwiki prefix.
Definition: Title.php:935
Title\isSiteJsonConfigPage
isSiteJsonConfigPage()
Is this a sitewide JSON "config" page?
Definition: Title.php:1536
$matches
$matches
Definition: NoLocalSettings.php:24
Title\isValidRedirectTarget
isValidRedirectTarget()
Check if this Title is a valid redirect target.
Definition: Title.php:4251
Title\deleteTitleProtection
deleteTitleProtection()
Remove any title protection due to page existing.
Definition: Title.php:2520
Title\__construct
__construct()
Was this Title created from a string with a local interwiki prefix?
Definition: Title.php:230
$wgLang
$wgLang
Definition: Setup.php:778
MediaWiki\Interwiki\InterwikiLookup
Service interface for looking up Interwiki records.
Definition: InterwikiLookup.php:32
Title\getBrokenLinksFrom
getBrokenLinksFrom()
Get an array of Title objects referring to non-existent articles linked from this page.
Definition: Title.php:3495
Title\isUserConfigPage
isUserConfigPage()
Is this a "config" (.css, .json, or .js) sub-page of a user page?
Definition: Title.php:1446
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:211
Title\getLanguageConverter
getLanguageConverter( $language)
Shorthand for getting a Language Converter for specific language.
Definition: Title.php:193
Title\$mCascadeSources
array $mCascadeSources
Where are the cascading restrictions coming from on this page?
Definition: Title.php:135
Title\getSubjectPage
getSubjectPage()
Get a title object associated with the subject page of this talk page.
Definition: Title.php:1648
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:37
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1170
Title\loadRestrictions
loadRestrictions( $oldFashionedRestrictions=null, $flags=0)
Load restrictions from the page_restrictions table.
Definition: Title.php:2885
$wgInvalidRedirectTargets
$wgInvalidRedirectTargets
Array of invalid page redirect targets.
Definition: DefaultSettings.php:4526
Title\getFullText
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with '#')
Definition: Title.php:1876
Title\getTitleCache
static getTitleCache()
Definition: Title.php:436
Title\hasFragment
hasFragment()
Check if a Title fragment is set.
Definition: Title.php:1751
Title\getRedirectsHere
getRedirectsHere( $ns=null)
Get all extant redirects to this Title.
Definition: Title.php:4215
MediaWiki\User\UserIdentity\getName
getName()
$title
$title
Definition: testCompression.php:38
Title\warnIfPageCannotExist
warnIfPageCannotExist(Title $title, $method)
Definition: Title.php:1674
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:591
Title\$mInterwiki
string $mInterwiki
Interwiki prefix.
Definition: Title.php:84
Title\$mCascadeRestriction
bool $mCascadeRestriction
Cascade restrictions on this page to included templates and images?
Definition: Title.php:123
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1844
Title\getRootText
getRootText()
Get the root page name text without a namespace, i.e.
Definition: Title.php:1957
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:83
$wgNamespaceProtection
$wgNamespaceProtection
Set the minimum permissions required to edit pages in each namespace.
Definition: DefaultSettings.php:5787
Title\canExist
canExist()
Can this title represent a page in the wiki's database?
Definition: Title.php:1188
$wgDeleteRevisionsLimit
$wgDeleteRevisionsLimit
Optional to restrict deletion of pages with higher revision counts to users with the 'bigdelete' perm...
Definition: DefaultSettings.php:5964
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Title\$prefixedText
string null $prefixedText
Text form including namespace/interwiki, initialised on demand.
Definition: Title.php:148
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:910
Title\__sleep
__sleep()
Definition: Title.php:4535
Title\getCanonicalURL
getCanonicalURL( $query='', $query2=false)
Get the URL for a canonical link, for use in things like IRC and e-mail notifications.
Definition: Title.php:2377
Title\createFragmentTarget
createFragmentTarget( $fragment)
Creates a new Title for a different fragment of the same page.
Definition: Title.php:1798
Title\$mNamespace
int $mNamespace
Namespace index, i.e.
Definition: Title.php:82
Title\getDefaultNamespace
getDefaultNamespace()
Get the default namespace index, for when there is no namespace.
Definition: Title.php:1730
Title\newFromTextThrow
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
Definition: Title.php:363
$wgPageLanguageUseDB
bool $wgPageLanguageUseDB
Enable page language feature Allows setting page language in database.
Definition: DefaultSettings.php:9189
Title\$mPageLanguage
array null $mPageLanguage
The (string) language code of the page's language and content code.
Definition: Title.php:171
Title\isValid
isValid()
Returns true if the title is a valid link target, and that it has been properly normalized.
Definition: Title.php:870
AtomicSectionUpdate
Deferrable Update for closure/callback updates via IDatabase::doAtomicSection()
Definition: AtomicSectionUpdate.php:9
Title\getPrefixedURL
getPrefixedURL()
Get a URL-encoded title (not an actual URL) including interwiki.
Definition: Title.php:2106
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
Title\__toString
__toString()
Return a string representation of this title.
Definition: Title.php:1866
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:28
DBAccessObjectUtils\hasFlags
static hasFlags( $bitfield, $flags)
Definition: DBAccessObjectUtils.php:35
Title\getTemplateLinksTo
getTemplateLinksTo( $options=[])
Get an array of Title objects using this Title as a template Also stores the IDs in the link cache.
Definition: Title.php:3413
$wgMainPageIsDomainRoot
bool $wgMainPageIsDomainRoot
Option to whether serve the main page as the domain root.
Definition: DefaultSettings.php:9570
Title\areRestrictionsCascading
areRestrictionsCascading()
Returns cascading restrictions for the current article.
Definition: Title.php:2788
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:57
Title\getLatestRevID
getLatestRevID( $flags=0)
What is the page_latest field for this page?
Definition: Title.php:3226
Title\areRestrictionsLoaded
areRestrictionsLoaded()
Accessor for mRestrictionsLoaded.
Definition: Title.php:2735
Title\hasDeletedEdits
hasDeletedEdits()
Is there a version of this page in the deletion archive?
Definition: Title.php:3115
Title\getSubpages
getSubpages( $limit=-1)
Get all subpages of this page.
Definition: Title.php:3038
Wikimedia\Rdbms\IDatabase\getDomainID
getDomainID()
Return the currently selected domain ID.
Title\isSingleRevRedirect
isSingleRevRedirect()
Locks the page row and check if this page is single revision redirect.
Definition: Title.php:3552
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:111
Title\GAID_FOR_UPDATE
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define().
Definition: Title.php:57
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
Title\getPageViewLanguage
getPageViewLanguage()
Get the language in which the content of this page is written when viewed by user.
Definition: Title.php:4392
Title\newFromDBkey
static newFromDBkey( $key)
Create a new Title from a prefixed DB key.
Definition: Title.php:241
Sanitizer\escapeIdForExternalInterwiki
static escapeIdForExternalInterwiki( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
Definition: Sanitizer.php:865
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:3110
Title\isSubpage
isSubpage()
Is this a subpage?
Definition: Title.php:1390
Title\hasContentModel
hasContentModel( $id)
Convenience method for checking a title's content model name.
Definition: Title.php:1079
Title\getRestrictionExpiry
getRestrictionExpiry( $action)
Get the expiry time for the restriction against a given action.
Definition: Title.php:2776
Title\newFromURL
static newFromURL( $url)
THIS IS NOT THE FUNCTION YOU WANT.
Definition: Title.php:413
MediaWiki\Linker\LinkTarget\getFragment
getFragment()
Get the link fragment (i.e.
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:208
Title\$mRestrictionsExpiry
array $mRestrictionsExpiry
When do the restrictions on this page expire?
Definition: Title.php:129
MapCacheLRU\set
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
Definition: MapCacheLRU.php:110
PROTO_RELATIVE
const PROTO_RELATIVE
Definition: Defines.php:210
Title\resetArticleID
resetArticleID( $id)
Inject a page ID, reset DB-loaded fields, and clear the link cache for this title.
Definition: Title.php:3261
Title\isSubpageOf
isSubpageOf(Title $title)
Check if this title is a subpage of another title.
Definition: Title.php:3911
Title\isLocal
isLocal()
Determine whether the object refers to a page within this project (either this wiki or a wiki with a ...
Definition: Title.php:909
Title\$mFragment
string $mFragment
Title fragment (i.e.
Definition: Title.php:88
Title\getContentModel
getContentModel( $flags=0)
Get the page's content model id, see the CONTENT_MODEL_XXX constants.
Definition: Title.php:1046
Title\newFromIDs
static newFromIDs( $ids)
Make an array of titles from an array of IDs.
Definition: Title.php:497
WikiPage\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new page object.
Definition: WikiPage.php:336
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:280
Title\prefix
prefix( $name)
Prefix some arbitrary text with the namespace or interwiki prefix of this object.
Definition: Title.php:1814
Title\getNamespaceKey
getNamespaceKey( $prepend='nstab-')
Generate strings used for xml 'id' names in monobook tabs.
Definition: Title.php:4186
Title\getEditURL
getEditURL()
Get the edit URL for this Title.
Definition: Title.php:2389
Title\getFullURL
getFullURL( $query='', $query2=false, $proto=PROTO_RELATIVE)
Get a real URL referring to this title, with interwiki link and fragment.
Definition: Title.php:2163
Title\isKnown
isKnown()
Does this title refer to a page that can (or might) be meaningfully viewed? In particular,...
Definition: Title.php:4003
$wgArticlePath
$wgArticlePath
The URL path for primary article page views.
Definition: DefaultSettings.php:267
Title\$mIsValid
bool null $mIsValid
Is the title known to be valid?
Definition: Title.php:185
Title\getFirstRevision
getFirstRevision( $flags=0)
Get the first revision of the page.
Definition: Title.php:3713
Title\getAllRestrictions
getAllRestrictions()
Accessor/initialisation for mRestrictions.
Definition: Title.php:2762
Title\getEarliestRevTime
getEarliestRevTime( $flags=0)
Get the oldest revision timestamp of this page.
Definition: Title.php:3729
Title
Represents a title within MediaWiki.
Definition: Title.php:41
$wgActionPaths
$wgActionPaths
To set 'pretty' URL paths for actions other than plain page views, add to this array.
Definition: DefaultSettings.php:454
Title\$mCascadingRestrictions
$mCascadingRestrictions
Caching the results of getCascadeProtectionSources.
Definition: Title.php:126
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
Title\getCascadeProtectionSources
getCascadeProtectionSources( $getPages=true)
Cascading protection: Get the source of any cascading restrictions on this page.
Definition: Title.php:2649
$cache
$cache
Definition: mcc.php:33
$wgSemiprotectedRestrictionLevels
$wgSemiprotectedRestrictionLevels
Restriction levels that should be considered "semiprotected".
Definition: DefaultSettings.php:5778
Title\getRestrictionTypes
getRestrictionTypes()
Returns restriction types for the current Title.
Definition: Title.php:2423
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:26
Title\getTitleProtectionInternal
getTitleProtectionInternal()
Fetch title protection settings.
Definition: Title.php:2473
Wikimedia\Rdbms\IDatabase\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
Title\getTemplateLinksFrom
getTemplateLinksFrom( $options=[])
Get an array of Title objects used on this Title as a template Also stores the IDs in the link cache.
Definition: Title.php:3483
Title\isRedirect
isRedirect( $flags=0)
Is this an article that is a redirect page? Uses link cache, adding it if necessary.
Definition: Title.php:3174
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:84
Title\$mArticleID
int $mArticleID
Article ID, fetched from the link cache on demand.
Definition: Title.php:91
Title\isDeleted
isDeleted()
Is there a version of this page in the deletion archive?
Definition: Title.php:3069
Title\capitalize
static capitalize( $text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
Definition: Title.php:3298
Title\$mDefaultNamespace
int $mDefaultNamespace
Namespace index when there is no namespace.
Definition: Title.php:159
Title\$mLength
int $mLength
The page length, 0 for special pages.
Definition: Title.php:162
Title\$mEstimateRevisions
int $mEstimateRevisions
Estimated number of revisions; null of not loaded.
Definition: Title.php:109
Title\hasSubjectNamespace
hasSubjectNamespace( $ns)
Returns true if the title has the same subject namespace as the namespace specified.
Definition: Title.php:1334
Title\isSpecialPage
isSpecialPage()
Returns true if this is a special page.
Definition: Title.php:1243
MapCacheLRU\get
get( $key, $maxAge=INF, $default=null)
Get the value for a key.
Definition: MapCacheLRU.php:168
Title\purgeSquid
purgeSquid()
Purge all applicable CDN URLs.
Definition: Title.php:3540
Title\getDeletedEditsCount
getDeletedEditsCount()
Is there a version of this page in the deletion archive?
Definition: Title.php:3079
Title\getPreviousRevisionID
getPreviousRevisionID( $revId, $flags=0)
Get the revision ID of the previous revision.
Definition: Title.php:3690
TitleArray
The TitleArray class only exists to provide the newFromResult method at pre- sent.
Definition: TitleArray.php:35
Title\getPageLanguage
getPageLanguage()
Get the language in which the content of this page is written in wikitext.
Definition: Title.php:4351
Title\CACHE_MAX
const CACHE_MAX
Title::newFromText maintains a cache to avoid expensive re-normalization of commonly used titles.
Definition: Title.php:50
Title\getEditNotices
getEditNotices( $oldid=0)
Get a list of rendered edit notices for this page.
Definition: Title.php:4440
Title\getTouched
getTouched( $db=null)
Get the last touched timestamp.
Definition: Title.php:4158
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
Wikimedia\Rdbms\IDatabase\selectFieldValues
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
$wgRestrictionLevels
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
Definition: DefaultSettings.php:5753
Title\getFragmentForURL
getFragmentForURL()
Get the fragment in URL form, including the "#" character if there is one.
Definition: Title.php:1760
Title\exists
exists( $flags=0)
Check if page exists.
Definition: Title.php:3927
NS_USER
const NS_USER
Definition: Defines.php:71
Sanitizer\escapeIdForLink
static escapeIdForLink( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
Definition: Sanitizer.php:842
Title\isAlwaysKnown
isAlwaysKnown()
Should links to this title be shown as potentially viewable (i.e.
Definition: Title.php:3949
Title\secureAndSplit
secureAndSplit( $text, $defaultNamespace=null)
Secure and split - main initialisation function for this object.
Definition: Title.php:3323
Title\isDeletedQuick
isDeletedQuick()
Is there a version of this page in the deletion archive?
Definition: Title.php:3105
Title\getSubpageUrlForm
getSubpageUrlForm()
Get a URL-encoded form of the subpage text.
Definition: Title.php:2095
MapCacheLRU\clear
clear( $keys=null)
Clear one or several cache entries, or all cache entries.
Definition: MapCacheLRU.php:285
Title\isNewPage
isNewPage()
Check if this is a new page.
Definition: Title.php:3741
$wgRestrictionTypes
$wgRestrictionTypes
Set of available actions that can be restricted via action=protect You probably shouldn't change this...
Definition: DefaultSettings.php:5740
Title\setContentModel
setContentModel( $model)
Set a proposed content model for the page for permissions checking.
Definition: Title.php:1096
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:77
CONTENT_MODEL_JAVASCRIPT
const CONTENT_MODEL_JAVASCRIPT
Definition: Defines.php:225
Title\compare
static compare(LinkTarget $a, LinkTarget $b)
Callback for usort() to do title sorts by (namespace, title)
Definition: Title.php:849
Title\countAuthorsBetween
countAuthorsBetween( $old, $new, $limit, $options=[])
Get the number of authors between the given revisions or revision IDs.
Definition: Title.php:3886
$t
$t
Definition: testCompression.php:74
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:702
Title\castFromLinkTarget
static castFromLinkTarget( $linkTarget)
Same as newFromLinkTarget, but if passed null, returns null.
Definition: Title.php:304
Title\isSiteJsConfigPage
isSiteJsConfigPage()
Is this a sitewide JS "config" page?
Definition: Title.php:1554
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:4094
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:646
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
Title\isTrans
isTrans()
Determine whether the object refers to a page within this project and is transcludable.
Definition: Title.php:954
Title\getRestrictions
getRestrictions( $action)
Accessor/initialisation for mRestrictions.
Definition: Title.php:2748
CommentStore\getStore
static getStore()
Definition: CommentStore.php:120
Title\isContentPage
isContentPage()
Is this Title in a namespace which contains content? In other words, is this a content page,...
Definition: Title.php:1346
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
Title\$titleCache
static MapCacheLRU null $titleCache
Definition: Title.php:43
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:472
$wgVariantArticlePath
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
Definition: DefaultSettings.php:3305
Title\isRawHtmlMessage
isRawHtmlMessage()
Is this a message which can contain raw HTML?
Definition: Title.php:1572
Title\getSelectFields
static getSelectFields()
Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
Definition: Title.php:449
Title\hasSubpages
hasSubpages()
Does this have subpages? (Warning, usually requires an extra DB query.)
Definition: Title.php:3007
Title\getBaseText
getBaseText()
Get the base page name without a namespace, i.e.
Definition: Title.php:2007
Title\pageCond
pageCond()
Get an associative array for selecting this title from the "page" table.
Definition: Title.php:3652
Title\getText
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:1007
Title\$mTextform
string $mTextform
Text form (spaces not underscores) of the main part.
Definition: Title.php:76
Wikimedia\Rdbms\IDatabase\delete
delete( $table, $conds, $fname=__METHOD__)
Delete all rows in a table that match a condition.
Title\purgeExpiredRestrictions
static purgeExpiredRestrictions()
Purge expired restrictions from the page_restrictions table.
Definition: Title.php:2966
$wgInternalServer
$wgInternalServer
Internal server name as known to CDN, if different.
Definition: DefaultSettings.php:2916
Title\$mLatestID
bool int $mLatestID
ID of most recent revision.
Definition: Title.php:94
Title\$mRestrictionsLoaded
bool $mRestrictionsLoaded
Boolean for initialisation on demand.
Definition: Title.php:138
Title\lazyFillContentModel
lazyFillContentModel( $model)
If the content model field is not frozen then update it with a retreived value.
Definition: Title.php:1110
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:490
Title\getSubjectNsText
getSubjectNsText()
Get the namespace text of the subject (rather than talk) page.
Definition: Title.php:1146
Title\$mTitleProtection
mixed $mTitleProtection
Cached value for getTitleProtection (create protection)
Definition: Title.php:151
TitleValue
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:39
Title\newFromTitleValue
static newFromTitleValue(TitleValue $titleValue, $forceClone='')
Returns a Title given a TitleValue.
Definition: Title.php:265
Title\getRelativeRevisionID
getRelativeRevisionID( $revId, $flags, $dir)
Get next/previous revision ID relative to another revision ID.
Definition: Title.php:3668
wfArrayToCgi
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
Definition: GlobalFunctions.php:346
Title\getFullUrlForRedirect
getFullUrlForRedirect( $query='', $proto=PROTO_CURRENT)
Get a url appropriate for making redirects based on an untrusted url arg.
Definition: Title.php:2196
Title\getRootTitle
getRootTitle()
Get the root page name title, i.e.
Definition: Title.php:1984
$type
$type
Definition: testCompression.php:52
Title\getLength
getLength( $flags=0)
What is the length of this page? Uses link cache, adding it if necessary.
Definition: Title.php:3199
Title\findSubpageDivider
findSubpageDivider( $text, $dir)
Finds the first or last subpage divider (slash) in the string.
Definition: Title.php:1898
Title\getAuthorsBetween
getAuthorsBetween( $old, $new, $limit, $options=[])
Get the authors between the given revisions or revision IDs.
Definition: Title.php:3843
Title\isWatchable
isWatchable()
Can this title be added to a user's watchlist?
Definition: Title.php:1232