]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/title/MediaWikiTitleCodec.php
MediaWiki 1.30.2-scripts2
[autoinstalls/mediawiki.git] / includes / title / MediaWikiTitleCodec.php
1 <?php
2 /**
3  * A codec for %MediaWiki page titles.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  * http://www.gnu.org/copyleft/gpl.html
19  *
20  * @file
21  * @license GPL 2+
22  * @author Daniel Kinzler
23  */
24 use MediaWiki\Interwiki\InterwikiLookup;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Linker\LinkTarget;
27
28 /**
29  * A codec for %MediaWiki page titles.
30  *
31  * @note Normalization and validation is applied while parsing, not when formatting.
32  * It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
33  * to generate an (invalid) title string from it. TitleValues should be constructed only
34  * via parseTitle() or from a (semi)trusted source, such as the database.
35  *
36  * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
37  * @since 1.23
38  */
39 class MediaWikiTitleCodec implements TitleFormatter, TitleParser {
40         /**
41          * @var Language
42          */
43         protected $language;
44
45         /**
46          * @var GenderCache
47          */
48         protected $genderCache;
49
50         /**
51          * @var string[]
52          */
53         protected $localInterwikis;
54
55         /**
56          * @var InterwikiLookup
57          */
58         protected $interwikiLookup;
59
60         /**
61          * @param Language $language The language object to use for localizing namespace names.
62          * @param GenderCache $genderCache The gender cache for generating gendered namespace names
63          * @param string[]|string $localInterwikis
64          * @param InterwikiLookup|null $interwikiLookup
65          */
66         public function __construct( Language $language, GenderCache $genderCache,
67                 $localInterwikis = [], $interwikiLookup = null
68         ) {
69                 $this->language = $language;
70                 $this->genderCache = $genderCache;
71                 $this->localInterwikis = (array)$localInterwikis;
72                 $this->interwikiLookup = $interwikiLookup ?:
73                         MediaWikiServices::getInstance()->getInterwikiLookup();
74         }
75
76         /**
77          * @see TitleFormatter::getNamespaceName()
78          *
79          * @param int $namespace
80          * @param string $text
81          *
82          * @throws InvalidArgumentException If the namespace is invalid
83          * @return string
84          */
85         public function getNamespaceName( $namespace, $text ) {
86                 if ( $this->language->needsGenderDistinction() &&
87                         MWNamespace::hasGenderDistinction( $namespace )
88                 ) {
89                         // NOTE: we are assuming here that the title text is a user name!
90                         $gender = $this->genderCache->getGenderOf( $text, __METHOD__ );
91                         $name = $this->language->getGenderNsText( $namespace, $gender );
92                 } else {
93                         $name = $this->language->getNsText( $namespace );
94                 }
95
96                 if ( $name === false ) {
97                         throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
98                 }
99
100                 return $name;
101         }
102
103         /**
104          * @see TitleFormatter::formatTitle()
105          *
106          * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
107          * @param string $text The page title. Should be valid. Only minimal normalization is applied.
108          *        Underscores will be replaced.
109          * @param string $fragment The fragment name (may be empty).
110          * @param string $interwiki The interwiki name (may be empty).
111          *
112          * @throws InvalidArgumentException If the namespace is invalid
113          * @return string
114          */
115         public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
116                 if ( $namespace !== false ) {
117                         // Try to get a namespace name, but fallback
118                         // to empty string if it doesn't exist
119                         try {
120                                 $nsName = $this->getNamespaceName( $namespace, $text );
121                         } catch ( InvalidArgumentException $e ) {
122                                 $nsName = '';
123                         }
124
125                         if ( $namespace !== 0 ) {
126                                 $text = $nsName . ':' . $text;
127                         }
128                 }
129
130                 if ( $fragment !== '' ) {
131                         $text = $text . '#' . $fragment;
132                 }
133
134                 if ( $interwiki !== '' ) {
135                         $text = $interwiki . ':' . $text;
136                 }
137
138                 $text = str_replace( '_', ' ', $text );
139
140                 return $text;
141         }
142
143         /**
144          * Parses the given text and constructs a TitleValue. Normalization
145          * is applied according to the rules appropriate for the form specified by $form.
146          *
147          * @param string $text The text to parse
148          * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
149          *
150          * @throws MalformedTitleException
151          * @return TitleValue
152          */
153         public function parseTitle( $text, $defaultNamespace ) {
154                 // NOTE: this is an ugly cludge that allows this class to share the
155                 // code for parsing with the old Title class. The parser code should
156                 // be refactored to avoid this.
157                 $parts = $this->splitTitleString( $text, $defaultNamespace );
158
159                 // Relative fragment links are not supported by TitleValue
160                 if ( $parts['dbkey'] === '' ) {
161                         throw new MalformedTitleException( 'title-invalid-empty', $text );
162                 }
163
164                 return new TitleValue(
165                         $parts['namespace'],
166                         $parts['dbkey'],
167                         $parts['fragment'],
168                         $parts['interwiki']
169                 );
170         }
171
172         /**
173          * @see TitleFormatter::getText()
174          *
175          * @param LinkTarget $title
176          *
177          * @return string $title->getText()
178          */
179         public function getText( LinkTarget $title ) {
180                 return $this->formatTitle( false, $title->getText(), '' );
181         }
182
183         /**
184          * @see TitleFormatter::getText()
185          *
186          * @param LinkTarget $title
187          *
188          * @return string
189          */
190         public function getPrefixedText( LinkTarget $title ) {
191                 return $this->formatTitle(
192                         $title->getNamespace(),
193                         $title->getText(),
194                         '',
195                         $title->getInterwiki()
196                 );
197         }
198
199         /**
200          * @since 1.27
201          * @see TitleFormatter::getPrefixedDBkey()
202          * @param LinkTarget $target
203          * @return string
204          */
205         public function getPrefixedDBkey( LinkTarget $target ) {
206                 $key = '';
207                 if ( $target->isExternal() ) {
208                         $key .= $target->getInterwiki() . ':';
209                 }
210                 // Try to get a namespace name, but fallback
211                 // to empty string if it doesn't exist
212                 try {
213                         $nsName = $this->getNamespaceName(
214                                 $target->getNamespace(),
215                                 $target->getText()
216                         );
217                 } catch ( InvalidArgumentException $e ) {
218                         $nsName = '';
219                 }
220
221                 if ( $target->getNamespace() !== 0 ) {
222                         $key .= $nsName . ':';
223                 }
224
225                 $key .= $target->getText();
226
227                 return strtr( $key, ' ', '_' );
228         }
229
230         /**
231          * @see TitleFormatter::getText()
232          *
233          * @param LinkTarget $title
234          *
235          * @return string
236          */
237         public function getFullText( LinkTarget $title ) {
238                 return $this->formatTitle(
239                         $title->getNamespace(),
240                         $title->getText(),
241                         $title->getFragment(),
242                         $title->getInterwiki()
243                 );
244         }
245
246         /**
247          * Normalizes and splits a title string.
248          *
249          * This function removes illegal characters, splits off the interwiki and
250          * namespace prefixes, sets the other forms, and canonicalizes
251          * everything.
252          *
253          * @todo this method is only exposed as a temporary measure to ease refactoring.
254          * It was copied with minimal changes from Title::secureAndSplit().
255          *
256          * @todo This method should be split up and an appropriate interface
257          * defined for use by the Title class.
258          *
259          * @param string $text
260          * @param int $defaultNamespace
261          *
262          * @throws MalformedTitleException If $text is not a valid title string.
263          * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
264          *         'user_case_dbkey', and 'dbkey'.
265          */
266         public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
267                 $dbkey = str_replace( ' ', '_', $text );
268
269                 # Initialisation
270                 $parts = [
271                         'interwiki' => '',
272                         'local_interwiki' => false,
273                         'fragment' => '',
274                         'namespace' => $defaultNamespace,
275                         'dbkey' => $dbkey,
276                         'user_case_dbkey' => $dbkey,
277                 ];
278
279                 # Strip Unicode bidi override characters.
280                 # Sometimes they slip into cut-n-pasted page titles, where the
281                 # override chars get included in list displays.
282                 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
283
284                 # Clean up whitespace
285                 # Note: use of the /u option on preg_replace here will cause
286                 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
287                 # conveniently disabling them.
288                 $dbkey = preg_replace(
289                         '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
290                         '_',
291                         $dbkey
292                 );
293                 $dbkey = trim( $dbkey, '_' );
294
295                 if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
296                         # Contained illegal UTF-8 sequences or forbidden Unicode chars.
297                         throw new MalformedTitleException( 'title-invalid-utf8', $text );
298                 }
299
300                 $parts['dbkey'] = $dbkey;
301
302                 # Initial colon indicates main namespace rather than specified default
303                 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
304                 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
305                         $parts['namespace'] = NS_MAIN;
306                         $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
307                         $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
308                 }
309
310                 if ( $dbkey == '' ) {
311                         throw new MalformedTitleException( 'title-invalid-empty', $text );
312                 }
313
314                 # Namespace or interwiki prefix
315                 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
316                 do {
317                         $m = [];
318                         if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
319                                 $p = $m[1];
320                                 $ns = $this->language->getNsIndex( $p );
321                                 if ( $ns !== false ) {
322                                         # Ordinary namespace
323                                         $dbkey = $m[2];
324                                         $parts['namespace'] = $ns;
325                                         # For Talk:X pages, check if X has a "namespace" prefix
326                                         if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
327                                                 if ( $this->language->getNsIndex( $x[1] ) ) {
328                                                         # Disallow Talk:File:x type titles...
329                                                         throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
330                                                 } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
331                                                         # Disallow Talk:Interwiki:x type titles...
332                                                         throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
333                                                 }
334                                         }
335                                 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
336                                         # Interwiki link
337                                         $dbkey = $m[2];
338                                         $parts['interwiki'] = $this->language->lc( $p );
339
340                                         # Redundant interwiki prefix to the local wiki
341                                         foreach ( $this->localInterwikis as $localIW ) {
342                                                 if ( 0 == strcasecmp( $parts['interwiki'], $localIW ) ) {
343                                                         if ( $dbkey == '' ) {
344                                                                 # Empty self-links should point to the Main Page, to ensure
345                                                                 # compatibility with cross-wiki transclusions and the like.
346                                                                 $mainPage = Title::newMainPage();
347                                                                 return [
348                                                                         'interwiki' => $mainPage->getInterwiki(),
349                                                                         'local_interwiki' => true,
350                                                                         'fragment' => $mainPage->getFragment(),
351                                                                         'namespace' => $mainPage->getNamespace(),
352                                                                         'dbkey' => $mainPage->getDBkey(),
353                                                                         'user_case_dbkey' => $mainPage->getUserCaseDBKey()
354                                                                 ];
355                                                         }
356                                                         $parts['interwiki'] = '';
357                                                         # local interwikis should behave like initial-colon links
358                                                         $parts['local_interwiki'] = true;
359
360                                                         # Do another namespace split...
361                                                         continue 2;
362                                                 }
363                                         }
364
365                                         # If there's an initial colon after the interwiki, that also
366                                         # resets the default namespace
367                                         if ( $dbkey !== '' && $dbkey[0] == ':' ) {
368                                                 $parts['namespace'] = NS_MAIN;
369                                                 $dbkey = substr( $dbkey, 1 );
370                                                 $dbkey = trim( $dbkey, '_' );
371                                         }
372                                 }
373                                 # If there's no recognized interwiki or namespace,
374                                 # then let the colon expression be part of the title.
375                         }
376                         break;
377                 } while ( true );
378
379                 $fragment = strstr( $dbkey, '#' );
380                 if ( false !== $fragment ) {
381                         $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
382                         $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
383                         # remove whitespace again: prevents "Foo_bar_#"
384                         # becoming "Foo_bar_"
385                         $dbkey = preg_replace( '/_*$/', '', $dbkey );
386                 }
387
388                 # Reject illegal characters.
389                 $rxTc = self::getTitleInvalidRegex();
390                 $matches = [];
391                 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
392                         throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
393                 }
394
395                 # Pages with "/./" or "/../" appearing in the URLs will often be un-
396                 # reachable due to the way web browsers deal with 'relative' URLs.
397                 # Also, they conflict with subpage syntax.  Forbid them explicitly.
398                 if (
399                         strpos( $dbkey, '.' ) !== false &&
400                         (
401                                 $dbkey === '.' || $dbkey === '..' ||
402                                 strpos( $dbkey, './' ) === 0 ||
403                                 strpos( $dbkey, '../' ) === 0 ||
404                                 strpos( $dbkey, '/./' ) !== false ||
405                                 strpos( $dbkey, '/../' ) !== false ||
406                                 substr( $dbkey, -2 ) == '/.' ||
407                                 substr( $dbkey, -3 ) == '/..'
408                         )
409                 ) {
410                         throw new MalformedTitleException( 'title-invalid-relative', $text );
411                 }
412
413                 # Magic tilde sequences? Nu-uh!
414                 if ( strpos( $dbkey, '~~~' ) !== false ) {
415                         throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
416                 }
417
418                 # Limit the size of titles to 255 bytes. This is typically the size of the
419                 # underlying database field. We make an exception for special pages, which
420                 # don't need to be stored in the database, and may edge over 255 bytes due
421                 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
422                 $maxLength = ( $parts['namespace'] != NS_SPECIAL ) ? 255 : 512;
423                 if ( strlen( $dbkey ) > $maxLength ) {
424                         throw new MalformedTitleException( 'title-invalid-too-long', $text,
425                                 [ Message::numParam( $maxLength ) ] );
426                 }
427
428                 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
429                 # and [[Foo]] point to the same place.  Don't force it for interwikis, since the
430                 # other site might be case-sensitive.
431                 $parts['user_case_dbkey'] = $dbkey;
432                 if ( $parts['interwiki'] === '' ) {
433                         $dbkey = Title::capitalize( $dbkey, $parts['namespace'] );
434                 }
435
436                 # Can't make a link to a namespace alone... "empty" local links can only be
437                 # self-links with a fragment identifier.
438                 if ( $dbkey == '' && $parts['interwiki'] === '' ) {
439                         if ( $parts['namespace'] != NS_MAIN ) {
440                                 throw new MalformedTitleException( 'title-invalid-empty', $text );
441                         }
442                 }
443
444                 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
445                 // IP names are not allowed for accounts, and can only be referring to
446                 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
447                 // there are numerous ways to present the same IP. Having sp:contribs scan
448                 // them all is silly and having some show the edits and others not is
449                 // inconsistent. Same for talk/userpages. Keep them normalized instead.
450                 if ( $parts['namespace'] == NS_USER || $parts['namespace'] == NS_USER_TALK ) {
451                         $dbkey = IP::sanitizeIP( $dbkey );
452                 }
453
454                 // Any remaining initial :s are illegal.
455                 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
456                         throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
457                 }
458
459                 # Fill fields
460                 $parts['dbkey'] = $dbkey;
461
462                 return $parts;
463         }
464
465         /**
466          * Returns a simple regex that will match on characters and sequences invalid in titles.
467          * Note that this doesn't pick up many things that could be wrong with titles, but that
468          * replacing this regex with something valid will make many titles valid.
469          * Previously Title::getTitleInvalidRegex()
470          *
471          * @return string Regex string
472          * @since 1.25
473          */
474         public static function getTitleInvalidRegex() {
475                 static $rxTc = false;
476                 if ( !$rxTc ) {
477                         # Matching titles will be held as illegal.
478                         $rxTc = '/' .
479                                 # Any character not allowed is forbidden...
480                                 '[^' . Title::legalChars() . ']' .
481                                 # URL percent encoding sequences interfere with the ability
482                                 # to round-trip titles -- you can't link to them consistently.
483                                 '|%[0-9A-Fa-f]{2}' .
484                                 # XML/HTML character references produce similar issues.
485                                 '|&[A-Za-z0-9\x80-\xff]+;' .
486                                 '|&#[0-9]+;' .
487                                 '|&#x[0-9A-Fa-f]+;' .
488                                 '/S';
489                 }
490
491                 return $rxTc;
492         }
493 }