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