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