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