-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Title.php
3890 lines (3506 loc) · 116 KB
/
Title.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Representation of a title within MediaWiki.
*
* See Title.md
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
namespace MediaWiki\Title;
use HTMLCacheUpdateJob;
use InvalidArgumentException;
use MapCacheLRU;
use MediaWiki\Cache\LinkCache;
use MediaWiki\Context\RequestContext;
use MediaWiki\DAO\WikiAwareEntityTrait;
use MediaWiki\Deferred\AutoCommitUpdate;
use MediaWiki\Deferred\DeferredUpdates;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Html\Html;
use MediaWiki\Interwiki\InterwikiLookup;
use MediaWiki\Language\ILanguageConverter;
use MediaWiki\Language\Language;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\Page\ExistingPageRecord;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\PageIdentityValue;
use MediaWiki\Page\PageReference;
use MediaWiki\Page\PageStoreRecord;
use MediaWiki\Page\ProperPageIdentity;
use MediaWiki\Parser\Sanitizer;
use MediaWiki\Request\PathRouter;
use MediaWiki\ResourceLoader\WikiModule;
use MediaWiki\SpecialPage\SpecialPage;
use MediaWiki\Utils\MWTimestamp;
use MessageLocalizer;
use MWException;
use RuntimeException;
use stdClass;
use Stringable;
use Wikimedia\Assert\Assert;
use Wikimedia\Assert\PreconditionException;
use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
use Wikimedia\Parsoid\Core\LinkTargetTrait;
use Wikimedia\Rdbms\DBAccessObjectUtils;
use Wikimedia\Rdbms\IConnectionProvider;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\IDBAccessObject;
use WikiPage;
/**
* Represents a title within MediaWiki.
* Optionally may contain an interwiki designation or namespace.
* @note This class can fetch various kinds of data from the database;
* however, it does so inefficiently.
* @note Consider using a TitleValue object instead. TitleValue is more lightweight
* and does not rely on global state or the database.
*/
class Title implements Stringable, LinkTarget, PageIdentity {
use WikiAwareEntityTrait;
use LinkTargetTrait;
/** @var MapCacheLRU|null */
private static $titleCache = null;
/**
* Title::newFromText maintains a cache to avoid expensive re-normalization of
* commonly used titles. On a batch operation this can become a memory leak
* if not bounded.
*/
private const CACHE_MAX = 1000;
/**
* Flag for use with factory methods like newFromLinkTarget() that have
* a $forceClone parameter. If set, the method must return a new instance.
* Without this flag, some factory methods may return existing instances.as
*
* @since 1.33
*/
public const NEW_CLONE = 'clone';
/** @var string Text form (spaces not underscores) of the main part */
private $mTextform = '';
/** @var string URL-encoded form of the main part */
private $mUrlform = '';
/** @var string Main part with underscores */
private $mDbkeyform = '';
/** @var int Namespace index, i.e. one of the NS_xxxx constants */
private $mNamespace = NS_MAIN;
/** @var string Interwiki prefix */
private $mInterwiki = '';
/** @var bool Was this Title created from a string with a local interwiki prefix? */
private $mLocalInterwiki = false;
/** @var string Title fragment (i.e. the bit after the #) */
private $mFragment = '';
/***************************************************************************/
// region Private member variables
/** @name Private member variables
* Please use the accessor functions instead.
* @internal
* @{
*/
/** @var int Article ID, fetched from the link cache on demand */
public $mArticleID = -1;
/** @var int|false ID of most recent revision */
protected $mLatestID = false;
/**
* @var string|false ID of the page's content model, i.e. one of the
* CONTENT_MODEL_XXX constants
*/
private $mContentModel = false;
/**
* @var bool If a content model was forced via setContentModel()
* this will be true to avoid having other code paths reset it
*/
private $mForcedContentModel = false;
/** @var int|null Estimated number of revisions; null of not loaded */
private $mEstimateRevisions;
/**
* Text form including namespace/interwiki, initialised on demand
*
* Only public to share cache with TitleFormatter
*
* @internal
* @var string|null
*/
public $prefixedText = null;
/**
* Namespace to assume when no namespace was passed to factory methods.
* This must be NS_MAIN, as it's hardcoded in several places. See T2696.
* Used primarily for {{transclusion}} tags.
*/
private const DEFAULT_NAMESPACE = NS_MAIN;
/** @var int The page length, 0 for special pages */
protected $mLength = -1;
/** @var null|bool Is the article at this title a redirect? */
public $mRedirect = null;
/** @var bool Whether a page has any subpages */
private $mHasSubpages;
/** @var array|null The (string) language code of the page's language and content code. */
private $mPageLanguage;
/** @var string|false|null The page language code from the database, null if not saved in
* the database or false if not loaded, yet.
*/
private $mDbPageLanguage = false;
/** @var TitleValue|null */
private $mTitleValue = null;
/** @var bool|null Would deleting this page be a big deletion? */
private $mIsBigDeletion = null;
/** @var bool|null Is the title known to be valid? */
private $mIsValid = null;
/** @var string|null The key of this instance in the internal Title instance cache */
private $mInstanceCacheKey = null;
// endregion -- end of private member variables
/** @} */
/***************************************************************************/
/**
* Shorthand for getting a Language Converter for specific language
* @param Language $language Language of converter
* @return ILanguageConverter
*/
private function getLanguageConverter( $language ): ILanguageConverter {
return MediaWikiServices::getInstance()->getLanguageConverterFactory()
->getLanguageConverter( $language );
}
/**
* Shorthand for getting a Language Converter for page's language
* @return ILanguageConverter
*/
private function getPageLanguageConverter(): ILanguageConverter {
return $this->getLanguageConverter( $this->getPageLanguage() );
}
/**
* Shorthand for getting a database connection provider
* @return IConnectionProvider
*/
private function getDbProvider(): IConnectionProvider {
return MediaWikiServices::getInstance()->getConnectionProvider();
}
/**
* B/C kludge: provide a TitleParser for use by Title.
* Ideally, Title would have no methods that need this.
* Avoid usage of this singleton by using TitleValue
* and the associated services when possible.
*
* @return TitleFormatter
*/
private static function getTitleFormatter() {
return MediaWikiServices::getInstance()->getTitleFormatter();
}
/**
* B/C kludge: provide an InterwikiLookup for use by Title.
* Ideally, Title would have no methods that need this.
* Avoid usage of this singleton by using TitleValue
* and the associated services when possible.
*
* @return InterwikiLookup
*/
private static function getInterwikiLookup() {
return MediaWikiServices::getInstance()->getInterwikiLookup();
}
private function __construct() {
}
/**
* Create a new Title from a prefixed DB key
*
* @param string $key The database key, which has underscores
* instead of spaces, possibly including namespace and
* interwiki prefixes
* @return Title|null Title, or null on an error
*/
public static function newFromDBkey( $key ) {
$t = new self();
try {
$t->secureAndSplit( $key );
return $t;
} catch ( MalformedTitleException $ex ) {
return null;
}
}
/**
* Returns a Title given a LinkTarget.
* If the given LinkTarget is already a Title instance, that instance is returned,
* unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
* is already a Title instance, that instance is copied using the clone operator.
*
* @since 1.27
* @param ParsoidLinkTarget $linkTarget Assumed to be safe.
* @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
* @return Title
*/
public static function newFromLinkTarget( ParsoidLinkTarget $linkTarget, $forceClone = '' ) {
if ( $linkTarget instanceof Title ) {
// Special case if it's already a Title object
if ( $forceClone === self::NEW_CLONE ) {
return clone $linkTarget;
} else {
return $linkTarget;
}
}
return self::makeTitle(
$linkTarget->getNamespace(),
$linkTarget->getText(),
$linkTarget->getFragment(),
$linkTarget->getInterwiki()
);
}
/**
* Same as newFromLinkTarget(), but if passed null, returns null.
*
* @since 1.34
* @param ParsoidLinkTarget|null $linkTarget Assumed to be safe (if not null).
* @return Title|null
*/
public static function castFromLinkTarget( ?ParsoidLinkTarget $linkTarget ) {
if ( !$linkTarget ) {
return null;
}
return self::newFromLinkTarget( $linkTarget );
}
/**
* Return a Title for a given PageIdentity. If $pageIdentity is a Title,
* that Title is returned unchanged.
*
* @since 1.41
* @param PageIdentity $pageIdentity
* @return Title
*/
public static function newFromPageIdentity( PageIdentity $pageIdentity ): Title {
return self::newFromPageReference( $pageIdentity );
}
/**
* Same as newFromPageIdentity(), but if passed null, returns null.
*
* @since 1.36
* @param PageIdentity|null $pageIdentity
* @return Title|null
*/
public static function castFromPageIdentity( ?PageIdentity $pageIdentity ): ?Title {
return self::castFromPageReference( $pageIdentity );
}
/**
* Return a Title for a given Reference. If $pageReference is a Title,
* that Title is returned unchanged.
*
* @since 1.41
* @param PageReference $pageReference
* @return Title
*/
public static function newFromPageReference( PageReference $pageReference ): Title {
if ( $pageReference instanceof Title ) {
return $pageReference;
}
$pageReference->assertWiki( self::LOCAL );
$title = self::makeTitle( $pageReference->getNamespace(), $pageReference->getDBkey() );
if ( $pageReference instanceof PageIdentity ) {
$title->mArticleID = $pageReference->getId();
}
return $title;
}
/**
* Same as newFromPageReference(), but if passed null, returns null.
*
* @since 1.37
* @param PageReference|null $pageReference
* @return Title|null
*/
public static function castFromPageReference( ?PageReference $pageReference ): ?Title {
if ( !$pageReference ) {
return null;
}
return self::newFromPageReference( $pageReference );
}
/**
* Create a new Title from text, such as what one would find in a link.
* Decodes any HTML entities in the text.
* Titles returned by this method are guaranteed to be valid.
* Call canExist() to check if the Title represents an editable page.
*
* @note The Title instance returned by this method is not guaranteed to be a fresh instance.
* It may instead be a cached instance created previously, with references to it remaining
* elsewhere.
*
* @param string|int|null $text The link text; spaces, prefixes, and an
* initial ':' indicating the main namespace are accepted.
* @param int $defaultNamespace The namespace to use if none is specified
* by a prefix. If you want to force a specific namespace even if
* $text might begin with a namespace prefix, use makeTitle() or
* makeTitleSafe().
* @return Title|null Title or null if the Title could not be parsed because
* it is invalid.
*/
public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
// DWIM: Integers can be passed in here when page titles are used as array keys.
if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
throw new InvalidArgumentException( '$text must be a string.' );
}
if ( $text === null || $text === '' ) {
return null;
}
try {
return self::newFromTextThrow( (string)$text, (int)$defaultNamespace );
} catch ( MalformedTitleException $ex ) {
return null;
}
}
/**
* Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
* rather than returning null.
*
* Titles returned by this method are guaranteed to be valid.
* Call canExist() to check if the Title represents an editable page.
*
* @note The Title instance returned by this method is not guaranteed to be a fresh instance.
* It may instead be a cached instance created previously, with references to it remaining
* elsewhere.
*
* @see Title::newFromText
*
* @since 1.25
* @param string $text Title text to check
* @param int $defaultNamespace
* @throws MalformedTitleException If the title is invalid.
* @return Title
*/
public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
if ( is_object( $text ) ) {
throw new InvalidArgumentException( '$text must be a string, given an object' );
} elseif ( $text === null ) {
// Legacy code relies on MalformedTitleException being thrown in this case
// TODO: fix(happens when URL with no title in it is parsed).
throw new MalformedTitleException( 'title-invalid-empty' );
}
$titleCache = self::getTitleCache();
// Wiki pages often contain multiple links to the same page.
// Title normalization and parsing can become expensive on pages with many
// links, so we can save a little time by caching them.
if ( $defaultNamespace === NS_MAIN ) {
$t = $titleCache->get( $text );
if ( $t ) {
return $t;
}
}
// Convert things like é ā or 〗 into normalized (T16952) text
$filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
$t = new Title();
$dbKeyForm = strtr( $filteredText, ' ', '_' );
$t->secureAndSplit( $dbKeyForm, (int)$defaultNamespace );
if ( $defaultNamespace === NS_MAIN ) {
$t->mInstanceCacheKey = $text;
$titleCache->set( $text, $t );
}
return $t;
}
/**
* Removes this instance from the internal title cache, so it can be modified in-place
* without polluting the cache (see T281337).
*/
private function uncache() {
if ( $this->mInstanceCacheKey !== null ) {
$titleCache = self::getTitleCache();
$titleCache->clear( $this->mInstanceCacheKey );
$this->mInstanceCacheKey = null;
}
}
/**
* THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
*
* Example of wrong and broken code:
* $title = Title::newFromURL( $request->getText( 'title' ) );
*
* Example of right code:
* $title = Title::newFromText( $request->getText( 'title' ) );
*
* Create a new Title from URL-encoded text. Ensures that
* the given title's length does not exceed the maximum.
*
* @param string $url The title, as might be taken from a URL
* @return Title|null The new object, or null on an error
*/
public static function newFromURL( $url ) {
$t = new Title();
# For compatibility with old buggy URLs. "+" is usually not valid in titles,
# but some URLs used it as a space replacement and they still come
# from some external search tools.
if ( !str_contains( self::legalChars(), '+' ) ) {
$url = strtr( $url, '+', ' ' );
}
$dbKeyForm = strtr( $url, ' ', '_' );
try {
$t->secureAndSplit( $dbKeyForm );
return $t;
} catch ( MalformedTitleException $ex ) {
return null;
}
}
/**
* @return MapCacheLRU
*/
private static function getTitleCache() {
if ( self::$titleCache === null ) {
self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
}
return self::$titleCache;
}
/**
* Create a new Title from an article ID
*
* @param int $id The page_id corresponding to the Title to create
* @param int $flags Bitfield of IDBAccessObject::READ_* constants
* @return Title|null The new object, or null on an error
*/
public static function newFromID( $id, $flags = 0 ) {
$pageStore = MediaWikiServices::getInstance()->getPageStore();
$dbr = DBAccessObjectUtils::getDBFromRecency(
MediaWikiServices::getInstance()->getConnectionProvider(),
$flags
);
$row = $dbr->newSelectQueryBuilder()
->select( $pageStore->getSelectFields() )
->from( 'page' )
->where( [ 'page_id' => $id ] )
->recency( $flags )
->caller( __METHOD__ )->fetchRow();
if ( $row !== false ) {
$title = self::newFromRow( $row );
} else {
$title = null;
}
return $title;
}
/**
* Make a Title object from a DB row
*
* @param stdClass $row Object database row (needs at least page_title,page_namespace)
* @return Title
*/
public static function newFromRow( $row ) {
$t = self::makeTitle( $row->page_namespace, $row->page_title );
$t->loadFromRow( $row );
return $t;
}
/**
* Load Title object fields from a DB row.
* If false is given, the title will be treated as non-existing.
*
* @param stdClass|false $row Database row
*/
public function loadFromRow( $row ) {
if ( $row ) { // page found
if ( isset( $row->page_id ) ) {
$this->mArticleID = (int)$row->page_id;
}
if ( isset( $row->page_len ) ) {
$this->mLength = (int)$row->page_len;
}
if ( isset( $row->page_is_redirect ) ) {
$this->mRedirect = (bool)$row->page_is_redirect;
}
if ( isset( $row->page_latest ) ) {
$this->mLatestID = (int)$row->page_latest;
}
if ( isset( $row->page_content_model ) ) {
$this->lazyFillContentModel( $row->page_content_model );
} else {
$this->lazyFillContentModel( false ); // lazily-load getContentModel()
}
if ( isset( $row->page_lang ) ) {
$this->mDbPageLanguage = (string)$row->page_lang;
}
} else { // page not found
$this->mArticleID = 0;
$this->mLength = 0;
$this->mRedirect = false;
$this->mLatestID = 0;
$this->lazyFillContentModel( false ); // lazily-load getContentModel()
}
}
/**
* Create a new Title from a namespace index and a DB key.
*
* It's assumed that $ns and $title are safe, for instance when
* they came directly from the database or a special page name,
* not from user input.
*
* No validation is applied. For convenience, spaces are normalized
* to underscores, so that e.g. user_text fields can be used directly.
*
* @note This method may return Title objects that are "invalid"
* according to the isValid() method. This is usually caused by
* configuration changes: e.g. a namespace that was once defined is
* no longer configured, or a character that was once allowed in
* titles is now forbidden.
*
* @param int $ns The namespace of the article
* @param string $title The unprefixed database key form
* @param string $fragment The link fragment (after the "#")
* @param string $interwiki The interwiki prefix
* @return Title The new object
*/
public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
$t = new Title();
$t->mInterwiki = $interwiki;
$t->mFragment = self::normalizeFragment( $fragment );
$t->mNamespace = $ns = (int)$ns;
$t->mDbkeyform = strtr( $title, ' ', '_' );
$t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
$t->mUrlform = wfUrlencode( $t->mDbkeyform );
$t->mTextform = strtr( $title, '_', ' ' );
return $t;
}
/**
* Create a new Title from a namespace index and a DB key.
* The parameters will be checked for validity, which is a bit slower
* than makeTitle() but safer for user-provided data.
*
* The Title object returned by this method is guaranteed to be valid.
* Call canExist() to check if the Title represents an editable page.
*
* @param int $ns The namespace of the article
* @param string $title Database key form
* @param string $fragment The link fragment (after the "#")
* @param string $interwiki Interwiki prefix
* @return Title|null The new object, or null on an error
*/
public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
// NOTE: ideally, this would just call makeTitle() and then isValid(),
// but presently, that means more overhead on a potential performance hotspot.
if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
return null;
}
$t = new Title();
$dbKeyForm = self::makeName( $ns, $title, $fragment, $interwiki, true );
try {
$t->secureAndSplit( $dbKeyForm );
return $t;
} catch ( MalformedTitleException $ex ) {
return null;
}
}
/**
* Create a new Title for the Main Page
*
* This uses the 'mainpage' interface message, which could be specified in
* `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
* will use the user language, which would involve initialising the session
* via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
* be sure to pass in a MessageLocalizer (such as your own RequestContext or
* ResourceLoader Context) to prevent an error.
*
* @note The Title instance returned by this method is not guaranteed to be a fresh instance.
* It may instead be a cached instance created previously, with references to it remaining
* elsewhere.
*
* @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
* @return Title
*/
public static function newMainPage( ?MessageLocalizer $localizer = null ) {
static $recursionGuard = false;
$title = null;
if ( !$recursionGuard ) {
$msg = $localizer ? $localizer->msg( 'mainpage' ) : wfMessage( 'mainpage' );
$recursionGuard = true;
$title = self::newFromText( $msg->inContentLanguage()->text() );
$recursionGuard = false;
}
// Every page renders at least one link to the Main Page (e.g. sidebar).
// Don't produce fatal errors that would make the wiki inaccessible, and hard to fix the
// invalid message.
//
// Fallback scenarios:
// * Recursion guard
// If the message contains a bare local interwiki (T297571), then
// Title::newFromText via MediaWikiTitleCodec::splitTitleString can get back here.
// * Invalid title
// If the 'mainpage' message contains something that is invalid, Title::newFromText
// will return null.
return $title ?? self::makeTitle( NS_MAIN, 'Main Page' );
}
/**
* Get a regex character class describing the legal characters in a link
*
* @return string The list of characters, not delimited
*/
public static function legalChars() {
global $wgLegalTitleChars;
return $wgLegalTitleChars;
}
/**
* Utility method for converting a character sequence from bytes to Unicode.
*
* Primary usecase being converting $wgLegalTitleChars to a sequence usable in
* javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
*
* @param string $byteClass
* @return string
*/
public static function convertByteClassToUnicodeClass( $byteClass ) {
$length = strlen( $byteClass );
// Input token queue
$x0 = $x1 = $x2 = '';
// Decoded queue
$d0 = $d1 = '';
// Decoded integer codepoints
$ord0 = $ord1 = $ord2 = 0;
// Re-encoded queue
$r0 = $r1 = $r2 = '';
// Output
$out = '';
// Flags
$allowUnicode = false;
for ( $pos = 0; $pos < $length; $pos++ ) {
// Shift the queues down
$x2 = $x1;
$x1 = $x0;
$d1 = $d0;
$ord2 = $ord1;
$ord1 = $ord0;
$r2 = $r1;
$r1 = $r0;
// Load the current input token and decoded values
$inChar = $byteClass[$pos];
if ( $inChar === '\\' ) {
if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
$x0 = $inChar . $m[0];
$d0 = chr( hexdec( $m[1] ) );
$pos += strlen( $m[0] );
} elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
$x0 = $inChar . $m[0];
$d0 = chr( octdec( $m[0] ) );
$pos += strlen( $m[0] );
} elseif ( $pos + 1 >= $length ) {
$x0 = $d0 = '\\';
} else {
$d0 = $byteClass[$pos + 1];
$x0 = $inChar . $d0;
$pos++;
}
} else {
$x0 = $d0 = $inChar;
}
$ord0 = ord( $d0 );
// Load the current re-encoded value
if ( $ord0 < 32 || $ord0 == 0x7f ) {
$r0 = sprintf( '\x%02x', $ord0 );
} elseif ( $ord0 >= 0x80 ) {
// Allow unicode if a single high-bit character appears
$r0 = sprintf( '\x%02x', $ord0 );
$allowUnicode = true;
// @phan-suppress-next-line PhanParamSuspiciousOrder false positive
} elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
$r0 = '\\' . $d0;
} else {
$r0 = $d0;
}
// Do the output
if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
// Range
if ( $ord2 > $ord0 ) {
// Empty range
} elseif ( $ord0 >= 0x80 ) {
// Unicode range
$allowUnicode = true;
if ( $ord2 < 0x80 ) {
// Keep the non-unicode section of the range
$out .= "$r2-\\x7F";
}
} else {
// Normal range
$out .= "$r2-$r0";
}
// Reset state to the initial value
// @phan-suppress-next-line PhanPluginRedundantAssignmentInLoop
$x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
} elseif ( $ord2 < 0x80 ) {
// ASCII character
$out .= $r2;
}
}
// @phan-suppress-next-line PhanSuspiciousValueComparison
if ( $ord1 < 0x80 ) {
$out .= $r1;
}
if ( $ord0 < 0x80 ) {
$out .= $r0;
}
if ( $allowUnicode ) {
$out .= '\u0080-\uFFFF';
}
return $out;
}
/**
* Make a prefixed DB key from a DB key and a namespace index
*
* @param int $ns Numerical representation of the namespace
* @param string $title The DB key form the title
* @param string $fragment The link fragment (after the "#")
* @param string $interwiki The interwiki prefix
* @param bool $canonicalNamespace If true, use the canonical name for
* $ns instead of the localized version.
* @return string The prefixed form of the title
*/
public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
$canonicalNamespace = false
) {
if ( $canonicalNamespace ) {
$namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
getCanonicalName( $ns );
} else {
$namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
}
if ( $namespace === false ) {
// See T165149. Awkward, but better than erroneously linking to the main namespace.
$namespace = self::makeName( NS_SPECIAL, "Badtitle/NS$ns", '', '', $canonicalNamespace );
}
$name = $namespace === '' ? $title : "$namespace:$title";
if ( strval( $interwiki ) != '' ) {
$name = "$interwiki:$name";
}
if ( strval( $fragment ) != '' ) {
$name .= '#' . $fragment;
}
return $name;
}
/**
* Callback for usort() to do title sorts by (namespace, title)
*
* @param LinkTarget|PageReference $a
* @param LinkTarget|PageReference $b
*
* @return int Result of string comparison, or namespace comparison
*/
public static function compare( $a, $b ) {
return $a->getNamespace() <=> $b->getNamespace()
?: strcmp( $a->getDBkey(), $b->getDBkey() );
}
/**
* Returns true if the title is a valid link target, and that it has been
* properly normalized. This method checks that the title is syntactically valid,
* and that the namespace it refers to exists.
*
* Titles constructed using newFromText() or makeTitleSafe() are always valid.
*
* @note Code that wants to check whether the title can represent a page that can
* be created and edited should use canExist() instead. Examples of valid titles
* that cannot "exist" are Special pages, interwiki links, and on-page section links
* that only have the fragment part set.
*
* @see canExist()
*
* @return bool
*/
public function isValid() {
if ( $this->mIsValid !== null ) {
return $this->mIsValid;
}
try {
// Optimization: Avoid Title::getFullText because that involves GenderCache
// and (unbatched) database queries. For validation, canonical namespace suffices.
$text = self::makeName( $this->mNamespace, $this->mDbkeyform, $this->mFragment, $this->mInterwiki, true );
$titleCodec = MediaWikiServices::getInstance()->getTitleParser();
'@phan-var MediaWikiTitleCodec $titleCodec';
$parts = $titleCodec->splitTitleString( $text, $this->mNamespace );
// Check that nothing changed!
// This ensures that $text was already properly normalized.
if ( $parts['fragment'] !== $this->mFragment
|| $parts['interwiki'] !== $this->mInterwiki
|| $parts['local_interwiki'] !== $this->mLocalInterwiki
|| $parts['namespace'] !== $this->mNamespace
|| $parts['dbkey'] !== $this->mDbkeyform
) {
$this->mIsValid = false;
return $this->mIsValid;
}
} catch ( MalformedTitleException $ex ) {
$this->mIsValid = false;
return $this->mIsValid;
}
$this->mIsValid = true;
return $this->mIsValid;
}
/**
* Determine whether the object refers to a page within
* this project (either this wiki or a wiki with a local
* interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
*
* @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
*/
public function isLocal() {
if ( $this->isExternal() ) {
$iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
if ( $iw ) {
return $iw->isLocal();
}
}
return true;
}
/**
* Get the interwiki prefix
*
* Use Title::isExternal to check if a interwiki is set
*
* @return string Interwiki prefix
*/
public function getInterwiki(): string {
return $this->mInterwiki;
}
/**
* Was this a local interwiki link?
*
* @return bool
*/
public function wasLocalInterwiki() {
return $this->mLocalInterwiki;
}
/**
* Determine whether the object refers to a page within
* this project and is transcludable.
*
* @return bool True if this is transcludable
*/
public function isTrans() {
if ( !$this->isExternal() ) {
return false;
}
return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
}
/**
* Returns the DB name of the distant wiki which owns the object.
*
* @return string|false The DB name
*/
public function getTransWikiID() {
if ( !$this->isExternal() ) {
return false;
}
return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
}
/**
* Get a TitleValue object representing this Title.
*
* @note Not all valid Titles have a corresponding valid TitleValue
* (e.g. TitleValues cannot represent page-local links that have a
* fragment but no title text).
*
* @return TitleValue|null
*/
public function getTitleValue() {
if ( $this->mTitleValue === null ) {
try {
$this->mTitleValue = new TitleValue(
$this->mNamespace,
$this->mDbkeyform,
$this->mFragment,
$this->mInterwiki