9cee79f2b3a6aaa9ed1e713d51803d72a79287ce
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
8 *
9 * @ingroup Skins
10 */
11 class Linker {
12
13 /**
14 * Flags for userToolLinks()
15 */
16 const TOOL_LINKS_NOBLOCK = 1;
17
18 function __construct() {}
19
20 /**
21 * @deprecated
22 */
23 function postParseLinkColour( $s = null ) {
24 wfDeprecated( __METHOD__ );
25 return null;
26 }
27
28 /**
29 * Get the appropriate HTML attributes to add to the "a" element of an ex-
30 * ternal link, as created by [wikisyntax].
31 *
32 * @param string $title The (unescaped) title text for the link
33 * @param string $unused Unused
34 * @param string $class The contents of the class attribute; if an empty
35 * string is passed, which is the default value, defaults to 'external'.
36 */
37 function getExternalLinkAttributes( $title, $unused = null, $class='' ) {
38 return $this->getLinkAttributesInternal( $title, $class, 'external' );
39 }
40
41 /**
42 * Get the appropriate HTML attributes to add to the "a" element of an in-
43 * terwiki link.
44 *
45 * @param string $title The title text for the link, URL-encoded (???) but
46 * not HTML-escaped
47 * @param string $unused Unused
48 * @param string $class The contents of the class attribute; if an empty
49 * string is passed, which is the default value, defaults to 'external'.
50 */
51 function getInterwikiLinkAttributes( $title, $unused = null, $class='' ) {
52 global $wgContLang;
53
54 # FIXME: We have a whole bunch of handling here that doesn't happen in
55 # getExternalLinkAttributes, why?
56 $title = urldecode( $title );
57 $title = $wgContLang->checkTitleEncoding( $title );
58 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
59
60 return $this->getLinkAttributesInternal( $title, $class, 'external' );
61 }
62
63 /**
64 * Get the appropriate HTML attributes to add to the "a" element of an in-
65 * ternal link.
66 *
67 * @param string $title The title text for the link, URL-encoded (???) but
68 * not HTML-escaped
69 * @param string $unused Unused
70 * @param string $class The contents of the class attribute, default none
71 */
72 function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
73 $title = urldecode( $title );
74 $title = str_replace( '_', ' ', $title );
75 return $this->getLinkAttributesInternal( $title, $class );
76 }
77
78 /**
79 * Get the appropriate HTML attributes to add to the "a" element of an in-
80 * ternal link, given the Title object for the page we want to link to.
81 *
82 * @param Title $nt The Title object
83 * @param string $unused Unused
84 * @param string $class The contents of the class attribute, default none
85 * @param mixed $title Optional (unescaped) string to use in the title
86 * attribute; if false, default to the name of the page we're linking to
87 */
88 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
89 if( $title === false ) {
90 $title = $nt->getPrefixedText();
91 }
92 return $this->getLinkAttributesInternal( $title, $class );
93 }
94
95 /**
96 * Common code for getLinkAttributesX functions
97 */
98 private function getLinkAttributesInternal( $title, $class, $classDefault = false ) {
99 $title = htmlspecialchars( $title );
100 if( $class === '' and $classDefault !== false ) {
101 # FIXME: Parameter defaults the hard way! We should just have
102 # $class = 'external' or whatever as the default in the externally-
103 # exposed functions, not $class = ''.
104 $class = $classDefault;
105 }
106 $class = htmlspecialchars( $class );
107 $r = '';
108 if( $class !== '' ) {
109 $r .= " class=\"$class\"";
110 }
111 $r .= " title=\"$title\"";
112 return $r;
113 }
114
115 /**
116 * Return the CSS colour of a known link
117 *
118 * @param Title $t
119 * @param integer $threshold user defined threshold
120 * @return string CSS class
121 */
122 function getLinkColour( $t, $threshold ) {
123 $colour = '';
124 if ( $t->isRedirect() ) {
125 # Page is a redirect
126 $colour = 'mw-redirect';
127 } elseif ( $threshold > 0 && $t->getLength() < $threshold && MWNamespace::isContent( $t->getNamespace() ) ) {
128 # Page is a stub
129 $colour = 'stub';
130 }
131 return $colour;
132 }
133
134 /**
135 * This function returns an HTML link to the given target. It serves a few
136 * purposes:
137 * 1) If $target is a Title, the correct URL to link to will be figured
138 * out automatically.
139 * 2) It automatically adds the usual classes for various types of link
140 * targets: "new" for red links, "stub" for short articles, etc.
141 * 3) It escapes all attribute values safely so there's no risk of XSS.
142 * 4) It provides a default tooltip if the target is a Title (the page
143 * name of the target).
144 * link() replaces the old functions in the makeLink() family.
145 *
146 * @param $target Title Can currently only be a Title, but this may
147 * change to support Images, literal URLs, etc.
148 * @param $text string The HTML contents of the <a> element, i.e.,
149 * the link text. This is raw HTML and will not be escaped. If null,
150 * defaults to the prefixed text of the Title; or if the Title is just a
151 * fragment, the contents of the fragment.
152 * @param $query array The query string to append to the URL
153 * you're linking to, in key => value array form. Query keys and values
154 * will be URL-encoded.
155 * @param $customAttribs array A key => value array of extra HTML attri-
156 * butes, such as title and class. (href is ignored.) Classes will be
157 * merged with the default classes, while other attributes will replace
158 * default attributes. All passed attribute values will be HTML-escaped.
159 * A false attribute value means to suppress that attribute.
160 * @param $options mixed String or array of strings:
161 * 'known': Page is known to exist, so don't check if it does.
162 * 'broken': Page is known not to exist, so don't check if it does.
163 * 'noclasses': Don't add any classes automatically (includes "new",
164 * "stub", "mw-redirect", "extiw"). Only use the class attribute
165 * provided, if any, so you get a simple blue link with no funny i-
166 * cons.
167 * @return string HTML <a> attribute
168 */
169 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
170 wfProfileIn( __METHOD__ );
171 $ret = null;
172 if( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
173 &$customAttribs, &$query, &$options, &$ret ) ) ) {
174 wfProfileOut( __METHOD__ );
175 return $ret;
176 }
177
178 if( !$target instanceof Title ) {
179 throw new MWException( 'Linker::link passed invalid target' );
180 }
181 $options = (array)$options;
182
183 # Normalize the Title if it's a special page
184 $target = $this->normaliseSpecialPage( $target );
185
186 # If we don't know whether the page exists, let's find out.
187 wfProfileIn( __METHOD__ . '-checkPageExistence' );
188 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
189 if( $target->getNamespace() == NS_SPECIAL ) {
190 if( SpecialPage::exists( $target->getDbKey() ) ) {
191 $options []= 'known';
192 } else {
193 $options []= 'broken';
194 }
195 } elseif( $target->isAlwaysKnown() or
196 ($target->getPrefixedText() == '' and $target->getFragment() != '')
197 or $target->exists() ) {
198 $options []= 'known';
199 } else {
200 $options []= 'broken';
201 }
202 }
203 wfProfileOut( __METHOD__ . '-checkPageExistence' );
204
205 # Note: we want the href attribute first, for prettiness.
206 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
207 $attribs = array_merge(
208 $attribs,
209 $this->linkAttribs( $target, $customAttribs, $options )
210 );
211 if( is_null( $text ) ) {
212 $text = $this->linkText( $target );
213 }
214
215 $ret = null;
216 if( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text,
217 &$attribs, &$ret ) ) ) {
218 $ret = Xml::openElement( 'a', $attribs )
219 . $text
220 . Xml::closeElement( 'a' );
221 }
222
223 wfProfileOut( __METHOD__ );
224 return $ret;
225 }
226
227 private function linkUrl( $target, $query, $options ) {
228 wfProfileIn( __METHOD__ );
229 # We don't want to include fragments for broken links, because they
230 # generally make no sense.
231 if( in_array( 'broken', $options ) and $target->mFragment !== '' ) {
232 $target = clone $target;
233 $target->mFragment = '';
234 }
235
236 # If it's a broken link, add the appropriate query pieces, unless
237 # there's already an action specified, or unless 'edit' makes no sense
238 # (i.e., for a nonexistent special page).
239 if( in_array( 'broken', $options ) and empty( $query['action'] )
240 and $target->getNamespace() != NS_SPECIAL ) {
241 $query['action'] = 'edit';
242 $query['redlink'] = '1';
243 }
244 $ret = $target->getLinkUrl( $query );
245 wfProfileOut( __METHOD__ );
246 return $ret;
247 }
248
249 private function linkAttribs( $target, $attribs, $options ) {
250 wfProfileIn( __METHOD__ );
251 global $wgUser;
252 $defaults = array();
253
254 if( !in_array( 'noclasses', $options ) ) {
255 wfProfileIn( __METHOD__ . '-getClasses' );
256 # Now build the classes.
257 $classes = array();
258
259 if( in_array( 'broken', $options ) ) {
260 $classes[] = 'new';
261 }
262
263 if( $target->isExternal() ) {
264 $classes[] = 'extiw';
265 }
266
267 # Note that redirects never count as stubs here.
268 if ( $target->isRedirect() ) {
269 $classes[] = 'mw-redirect';
270 } elseif( $target->isContentPage() ) {
271 # Check for stub.
272 $threshold = $wgUser->getOption( 'stubthreshold' );
273 if( $threshold > 0 and $target->getLength() < $threshold ) {
274 $classes[] = 'stub';
275 }
276 }
277 if( $classes != array() ) {
278 $defaults['class'] = implode( ' ', $classes );
279 }
280 wfProfileOut( __METHOD__ . '-getClasses' );
281 }
282
283 # Get a default title attribute.
284 if( in_array( 'known', $options ) ) {
285 $defaults['title'] = $target->getPrefixedText();
286 } else {
287 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
288 }
289
290 # Finally, merge the custom attribs with the default ones, and iterate
291 # over that, deleting all "false" attributes.
292 $ret = array();
293 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
294 foreach( $merged as $key => $val ) {
295 # A false value suppresses the attribute, and we don't want the
296 # href attribute to be overridden.
297 if( $key != 'href' and $val !== false ) {
298 $ret[$key] = $val;
299 }
300 }
301 wfProfileOut( __METHOD__ );
302 return $ret;
303 }
304
305 private function linkText( $target ) {
306 # If the target is just a fragment, with no title, we return the frag-
307 # ment text. Otherwise, we return the title text itself.
308 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
309 return htmlspecialchars( $target->getFragment() );
310 }
311 return htmlspecialchars( $target->getPrefixedText() );
312 }
313
314 /**
315 * @deprecated Use link()
316 *
317 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
318 * it if you already have a title object handy. See makeLinkObj for further documentation.
319 *
320 * @param $title String: the text of the title
321 * @param $text String: link text
322 * @param $query String: optional query part
323 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
324 * be included in the link text. Other characters will be appended after
325 * the end of the link.
326 */
327 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
328 wfDeprecated( __METHOD__ );
329 wfProfileIn( __METHOD__ );
330 $nt = Title::newFromText( $title );
331 if ( $nt instanceof Title ) {
332 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
333 } else {
334 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
335 $result = $text == "" ? $title : $text;
336 }
337
338 wfProfileOut( __METHOD__ );
339 return $result;
340 }
341
342 /**
343 * @deprecated Use link()
344 *
345 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
346 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
347 *
348 * @param $title String: the text of the title
349 * @param $text String: link text
350 * @param $query String: optional query part
351 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
352 * be included in the link text. Other characters will be appended after
353 * the end of the link.
354 */
355 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
356 wfDeprecated( __METHOD__ );
357 $nt = Title::newFromText( $title );
358 if ( $nt instanceof Title ) {
359 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
360 } else {
361 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
362 return $text == '' ? $title : $text;
363 }
364 }
365
366 /**
367 * @deprecated Use link()
368 *
369 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
370 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
371 *
372 * @param string $title The text of the title
373 * @param string $text Link text
374 * @param string $query Optional query part
375 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
376 * be included in the link text. Other characters will be appended after
377 * the end of the link.
378 */
379 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
380 wfDeprecated( __METHOD__ );
381 $nt = Title::newFromText( $title );
382 if ( $nt instanceof Title ) {
383 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
384 } else {
385 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
386 return $text == '' ? $title : $text;
387 }
388 }
389
390 /**
391 * @deprecated Use link()
392 *
393 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
394 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
395 *
396 * @param $title String: the text of the title
397 * @param $text String: link text
398 * @param $query String: optional query part
399 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
400 * be included in the link text. Other characters will be appended after
401 * the end of the link.
402 */
403 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
404 wfDeprecated( __METHOD__ );
405 $nt = Title::newFromText( $title );
406 if ( $nt instanceof Title ) {
407 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
408 } else {
409 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
410 return $text == '' ? $title : $text;
411 }
412 }
413
414 /**
415 * @deprecated Use link()
416 *
417 * Make a link for a title which may or may not be in the database. If you need to
418 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
419 * call to this will result in a DB query.
420 *
421 * @param $nt Title: the title object to make the link from, e.g. from
422 * Title::newFromText.
423 * @param $text String: link text
424 * @param $query String: optional query part
425 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
426 * be included in the link text. Other characters will be appended after
427 * the end of the link.
428 * @param $prefix String: optional prefix. As trail, only before instead of after.
429 */
430 function makeLinkObj( Title $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
431 wfDeprecated( __METHOD__ );
432 global $wgUser;
433 wfProfileIn( __METHOD__ );
434
435 $query = wfCgiToArray( $query );
436 list( $inside, $trail ) = Linker::splitTrail( $trail );
437 if( $text === '' ) {
438 $text = $this->linkText( $nt );
439 }
440
441 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query,
442 'noclasses' ) . $trail;
443
444 wfProfileOut( __METHOD__ );
445 return $ret;
446 }
447
448 /**
449 * @deprecated Use link()
450 *
451 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
452 * it doesn't have to do a database query. It's also valid for interwiki titles and special
453 * pages.
454 *
455 * @param $nt Title object of target page
456 * @param $text String: text to replace the title
457 * @param $query String: link target
458 * @param $trail String: text after link
459 * @param $prefix String: text before link text
460 * @param $aprops String: extra attributes to the a-element
461 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
462 * @return the a-element
463 */
464 function makeKnownLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
465 wfDeprecated( __METHOD__ );
466 wfProfileIn( __METHOD__ );
467
468 if ( $text == '' ) {
469 $text = $this->linkText( $title );
470 }
471 $attribs = Sanitizer::mergeAttributes(
472 Sanitizer::decodeTagAttributes( $aprops ),
473 Sanitizer::decodeTagAttributes( $style )
474 );
475 $query = wfCgiToArray( $query );
476 list( $inside, $trail ) = Linker::splitTrail( $trail );
477
478 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
479 array( 'known', 'noclasses' ) ) . $trail;
480
481 wfProfileOut( __METHOD__ );
482 return $ret;
483 }
484
485 /**
486 * @deprecated Use link()
487 *
488 * Make a red link to the edit page of a given title.
489 *
490 * @param $nt Title object of the target page
491 * @param $text String: Link text
492 * @param $query String: Optional query part
493 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
494 * be included in the link text. Other characters will be appended after
495 * the end of the link.
496 */
497 function makeBrokenLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
498 wfDeprecated( __METHOD__ );
499 wfProfileIn( __METHOD__ );
500
501 list( $inside, $trail ) = Linker::splitTrail( $trail );
502 if( $text === '' ) {
503 $text = $this->linkText( $title );
504 }
505 $nt = $this->normaliseSpecialPage( $title );
506
507 $ret = $this->link( $title, "$prefix$text$inside", array(),
508 wfCgiToArray( $query ), 'broken' ) . $trail;
509
510 wfProfileOut( __METHOD__ );
511 return $ret;
512 }
513
514 /**
515 * @deprecated Use link()
516 *
517 * Make a brown link to a short article.
518 *
519 * @param $nt Title object of the target page
520 * @param $text String: link text
521 * @param $query String: optional query part
522 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
523 * be included in the link text. Other characters will be appended after
524 * the end of the link.
525 */
526 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
527 wfDeprecated( __METHOD__ );
528 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
529 }
530
531 /**
532 * @deprecated Use link()
533 *
534 * Make a coloured link.
535 *
536 * @param $nt Title object of the target page
537 * @param $colour Integer: colour of the link
538 * @param $text String: link text
539 * @param $query String: optional query part
540 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
541 * be included in the link text. Other characters will be appended after
542 * the end of the link.
543 */
544 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
545 wfDeprecated( __METHOD__ );
546 if($colour != ''){
547 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
548 } else $style = '';
549 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
550 }
551
552 /**
553 * Generate either a normal exists-style link or a stub link, depending
554 * on the given page size.
555 *
556 * @param $size Integer
557 * @param $nt Title object.
558 * @param $text String
559 * @param $query String
560 * @param $trail String
561 * @param $prefix String
562 * @return string HTML of link
563 */
564 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
565 global $wgUser;
566 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
567 $colour = ( $size < $threshold ) ? 'stub' : '';
568 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
569 }
570
571 /**
572 * Make appropriate markup for a link to the current article. This is currently rendered
573 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
574 * despite $query not being used.
575 */
576 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
577 if ( '' == $text ) {
578 $text = htmlspecialchars( $nt->getPrefixedText() );
579 }
580 list( $inside, $trail ) = Linker::splitTrail( $trail );
581 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
582 }
583
584 function normaliseSpecialPage( Title $title ) {
585 if ( $title->getNamespace() == NS_SPECIAL ) {
586 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
587 if ( !$name ) return $title;
588 $ret = SpecialPage::getTitleFor( $name, $subpage );
589 $ret->mFragment = $title->getFragment();
590 return $ret;
591 } else {
592 return $title;
593 }
594 }
595
596 /** @todo document */
597 function fnamePart( $url ) {
598 $basename = strrchr( $url, '/' );
599 if ( false === $basename ) {
600 $basename = $url;
601 } else {
602 $basename = substr( $basename, 1 );
603 }
604 return $basename;
605 }
606
607 /** Obsolete alias */
608 function makeImage( $url, $alt = '' ) {
609 wfDeprecated( __METHOD__ );
610 return $this->makeExternalImage( $url, $alt );
611 }
612
613 /** @todo document */
614 function makeExternalImage( $url, $alt = '' ) {
615 if ( '' == $alt ) {
616 $alt = $this->fnamePart( $url );
617 }
618 $img = '';
619 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
620 if(!$success) {
621 wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}", true);
622 return $img;
623 }
624 return Xml::element( 'img',
625 array(
626 'src' => $url,
627 'alt' => $alt ) );
628 }
629
630 /**
631 * Creates the HTML source for images
632 * @deprecated use makeImageLink2
633 *
634 * @param object $title
635 * @param string $label label text
636 * @param string $alt alt text
637 * @param string $align horizontal alignment: none, left, center, right)
638 * @param array $handlerParams Parameters to be passed to the media handler
639 * @param boolean $framed shows image in original size in a frame
640 * @param boolean $thumb shows image as thumbnail in a frame
641 * @param string $manualthumb image name for the manual thumbnail
642 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
643 * @param string $time, timestamp of the file, set as false for current
644 * @return string
645 */
646 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
647 $thumb = false, $manualthumb = '', $valign = '', $time = false )
648 {
649 $frameParams = array( 'alt' => $alt, 'caption' => $label );
650 if ( $align ) {
651 $frameParams['align'] = $align;
652 }
653 if ( $framed ) {
654 $frameParams['framed'] = true;
655 }
656 if ( $thumb ) {
657 $frameParams['thumbnail'] = true;
658 }
659 if ( $manualthumb ) {
660 $frameParams['manualthumb'] = $manualthumb;
661 }
662 if ( $valign ) {
663 $frameParams['valign'] = $valign;
664 }
665 $file = wfFindFile( $title, $time );
666 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
667 }
668
669 /**
670 * Given parameters derived from [[Image:Foo|options...]], generate the
671 * HTML that that syntax inserts in the page.
672 *
673 * @param Title $title Title object
674 * @param File $file File object, or false if it doesn't exist
675 *
676 * @param array $frameParams Associative array of parameters external to the media handler.
677 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
678 * will often be false.
679 * thumbnail If present, downscale and frame
680 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
681 * framed Shows image in original size in a frame
682 * frameless Downscale but don't frame
683 * upright If present, tweak default sizes for portrait orientation
684 * upright_factor Fudge factor for "upright" tweak (default 0.75)
685 * border If present, show a border around the image
686 * align Horizontal alignment (left, right, center, none)
687 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
688 * bottom, text-bottom)
689 * alt Alternate text for image (i.e. alt attribute). Plain text.
690 * caption HTML for image caption.
691 *
692 * @param array $handlerParams Associative array of media handler parameters, to be passed
693 * to transform(). Typical keys are "width" and "page".
694 * @param string $time, timestamp of the file, set as false for current
695 * @param string $query, query params for desc url
696 * @return string HTML for an image, with links, wrappers, etc.
697 */
698 function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
699 $res = null;
700 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
701 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
702 return $res;
703 }
704
705 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
706 if ( $file && !$file->allowInlineDisplay() ) {
707 wfDebug( __METHOD__.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
708 return $this->link( $title );
709 }
710
711 // Shortcuts
712 $fp =& $frameParams;
713 $hp =& $handlerParams;
714
715 // Clean up parameters
716 $page = isset( $hp['page'] ) ? $hp['page'] : false;
717 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
718 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
719
720 $prefix = $postfix = '';
721
722 if ( 'center' == $fp['align'] )
723 {
724 $prefix = '<div class="center">';
725 $postfix = '</div>';
726 $fp['align'] = 'none';
727 }
728 if ( $file && !isset( $hp['width'] ) ) {
729 $hp['width'] = $file->getWidth( $page );
730
731 if( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
732 $wopt = $wgUser->getOption( 'thumbsize' );
733
734 if( !isset( $wgThumbLimits[$wopt] ) ) {
735 $wopt = User::getDefaultOption( 'thumbsize' );
736 }
737
738 // Reduce width for upright images when parameter 'upright' is used
739 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
740 $fp['upright'] = $wgThumbUpright;
741 }
742 // Use width which is smaller: real image width or user preference width
743 // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs
744 $prefWidth = isset( $fp['upright'] ) ?
745 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
746 $wgThumbLimits[$wopt];
747 if ( $hp['width'] <= 0 || $prefWidth < $hp['width'] ) {
748 $hp['width'] = $prefWidth;
749 }
750 }
751 }
752
753 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
754
755 # Create a thumbnail. Alignment depends on language
756 # writing direction, # right aligned for left-to-right-
757 # languages ("Western languages"), left-aligned
758 # for right-to-left-languages ("Semitic languages")
759 #
760 # If thumbnail width has not been provided, it is set
761 # to the default user option as specified in Language*.php
762 if ( $fp['align'] == '' ) {
763 $fp['align'] = $wgContLang->isRTL() ? 'left' : 'right';
764 }
765 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
766 }
767
768 if ( $file && isset( $fp['frameless'] ) ) {
769 $srcWidth = $file->getWidth( $page );
770 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
771 # This is the same behaviour as the "thumb" option does it already.
772 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
773 $hp['width'] = $srcWidth;
774 }
775 }
776
777 if ( $file && $hp['width'] ) {
778 # Create a resized image, without the additional thumbnail features
779 $thumb = $file->transform( $hp );
780 } else {
781 $thumb = false;
782 }
783
784 if ( !$thumb ) {
785 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
786 } else {
787 $s = $thumb->toHtml( array(
788 'desc-link' => true,
789 'desc-query' => $query,
790 'alt' => $fp['alt'],
791 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
792 'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false ) );
793 }
794 if ( '' != $fp['align'] ) {
795 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
796 }
797 return str_replace("\n", ' ',$prefix.$s.$postfix);
798 }
799
800 /**
801 * Make HTML for a thumbnail including image, border and caption
802 * @param Title $title
803 * @param File $file File object or false if it doesn't exist
804 */
805 function makeThumbLinkObj( Title $title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
806 $frameParams = array(
807 'alt' => $alt,
808 'caption' => $label,
809 'align' => $align
810 );
811 if ( $framed ) $frameParams['framed'] = true;
812 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
813 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
814 }
815
816 function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
817 global $wgStylePath, $wgContLang;
818 $exists = $file && $file->exists();
819
820 # Shortcuts
821 $fp =& $frameParams;
822 $hp =& $handlerParams;
823
824 $page = isset( $hp['page'] ) ? $hp['page'] : false;
825 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
826 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
827 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
828
829 if ( empty( $hp['width'] ) ) {
830 // Reduce width for upright images when parameter 'upright' is used
831 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
832 }
833 $thumb = false;
834
835 if ( !$exists ) {
836 $outerWidth = $hp['width'] + 2;
837 } else {
838 if ( isset( $fp['manualthumb'] ) ) {
839 # Use manually specified thumbnail
840 $manual_title = Title::makeTitleSafe( NS_IMAGE, $fp['manualthumb'] );
841 if( $manual_title ) {
842 $manual_img = wfFindFile( $manual_title );
843 if ( $manual_img ) {
844 $thumb = $manual_img->getUnscaledThumb();
845 } else {
846 $exists = false;
847 }
848 }
849 } elseif ( isset( $fp['framed'] ) ) {
850 // Use image dimensions, don't scale
851 $thumb = $file->getUnscaledThumb( $page );
852 } else {
853 # Do not present an image bigger than the source, for bitmap-style images
854 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
855 $srcWidth = $file->getWidth( $page );
856 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
857 $hp['width'] = $srcWidth;
858 }
859 $thumb = $file->transform( $hp );
860 }
861
862 if ( $thumb ) {
863 $outerWidth = $thumb->getWidth() + 2;
864 } else {
865 $outerWidth = $hp['width'] + 2;
866 }
867 }
868
869 if( $page ) {
870 $query = $query ? '&page=' . urlencode( $page ) : 'page=' . urlencode( $page );
871 }
872 $url = $title->getLocalURL( $query );
873
874 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
875
876 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
877 if( !$exists ) {
878 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
879 $zoomicon = '';
880 } elseif ( !$thumb ) {
881 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
882 $zoomicon = '';
883 } else {
884 $s .= $thumb->toHtml( array(
885 'alt' => $fp['alt'],
886 'img-class' => 'thumbimage',
887 'desc-link' => true,
888 'desc-query' => $query ) );
889 if ( isset( $fp['framed'] ) ) {
890 $zoomicon="";
891 } else {
892 $zoomicon = '<div class="magnify">'.
893 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
894 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
895 'width="15" height="11" alt="" /></a></div>';
896 }
897 }
898 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
899 return str_replace("\n", ' ', $s);
900 }
901
902 /**
903 * Make a "broken" link to an image
904 *
905 * @param Title $title Image title
906 * @param string $text Link label
907 * @param string $query Query string
908 * @param string $trail Link trail
909 * @param string $prefix Link prefix
910 * @param bool $time, a file of a certain timestamp was requested
911 * @return string
912 */
913 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
914 global $wgEnableUploads;
915 if( $title instanceof Title ) {
916 wfProfileIn( __METHOD__ );
917 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
918 if( $wgEnableUploads && !$currentExists ) {
919 $upload = SpecialPage::getTitleFor( 'Upload' );
920 if( $text == '' )
921 $text = htmlspecialchars( $title->getPrefixedText() );
922 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
923 if( $redir ) {
924 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
925 }
926 $q = 'wpDestFile=' . $title->getPartialUrl();
927 if( $query != '' )
928 $q .= '&' . $query;
929 list( $inside, $trail ) = self::splitTrail( $trail );
930 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
931 wfProfileOut( __METHOD__ );
932 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
933 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
934 } else {
935 wfProfileOut( __METHOD__ );
936 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
937 }
938 } else {
939 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
940 }
941 }
942
943 /** @deprecated use Linker::makeMediaLinkObj() */
944 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
945 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
946 return $this->makeMediaLinkObj( $nt, $text, $time );
947 }
948
949 /**
950 * Create a direct link to a given uploaded file.
951 *
952 * @param $title Title object.
953 * @param $text String: pre-sanitized HTML
954 * @param $time string: time image was created
955 * @return string HTML
956 *
957 * @public
958 * @todo Handle invalid or missing images better.
959 */
960 function makeMediaLinkObj( $title, $text = '', $time = false ) {
961 if( is_null( $title ) ) {
962 ### HOTFIX. Instead of breaking, return empty string.
963 return $text;
964 } else {
965 $img = wfFindFile( $title, $time );
966 if( $img ) {
967 $url = $img->getURL();
968 $class = 'internal';
969 } else {
970 $upload = SpecialPage::getTitleFor( 'Upload' );
971 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
972 $class = 'new';
973 }
974 $alt = htmlspecialchars( $title->getText() );
975 if( $text == '' ) {
976 $text = $alt;
977 }
978 $u = htmlspecialchars( $url );
979 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
980 }
981 }
982
983 /** @todo document */
984 function specialLink( $name, $key = '' ) {
985 global $wgContLang;
986
987 if ( '' == $key ) { $key = strtolower( $name ); }
988 $pn = $wgContLang->ucfirst( $name );
989 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
990 wfMsg( $key ) );
991 }
992
993 /** @todo document */
994 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
995 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
996 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
997 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
998 $style .= ' rel="nofollow"';
999 }
1000 $url = htmlspecialchars( $url );
1001 if( $escape ) {
1002 $text = htmlspecialchars( $text );
1003 }
1004 $link = '';
1005 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link ) );
1006 if(!$success) {
1007 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}", true);
1008 return $link;
1009 }
1010 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
1011 }
1012
1013 /**
1014 * Make user link (or user contributions for unregistered users)
1015 * @param $userId Integer: user id in database.
1016 * @param $userText String: user name in database
1017 * @return string HTML fragment
1018 * @private
1019 */
1020 function userLink( $userId, $userText ) {
1021 if( $userId == 0 ) {
1022 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
1023 } else {
1024 $page = Title::makeTitle( NS_USER, $userText );
1025 }
1026 return $this->link( $page, htmlspecialchars( $userText ) );
1027 }
1028
1029 /**
1030 * Generate standard user tool links (talk, contributions, block link, etc.)
1031 *
1032 * @param int $userId User identifier
1033 * @param string $userText User name or IP address
1034 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1035 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1036 * @param int $edits, user edit count (optional, for performance)
1037 * @return string
1038 */
1039 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1040 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
1041 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1042 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
1043
1044 $items = array();
1045 if( $talkable ) {
1046 $items[] = $this->userTalkLink( $userId, $userText );
1047 }
1048 if( $userId ) {
1049 // check if the user has an edit
1050 $attribs = array();
1051 if( $redContribsWhenNoEdits ) {
1052 $count = !is_null($edits) ? $edits : User::edits( $userId );
1053 if( $count == 0 ) {
1054 $attribs['class'] = 'new';
1055 }
1056 }
1057 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1058
1059 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1060 }
1061 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1062 $items[] = $this->blockLink( $userId, $userText );
1063 }
1064
1065 if( $items ) {
1066 return ' (' . implode( ' | ', $items ) . ')';
1067 } else {
1068 return '';
1069 }
1070 }
1071
1072 /**
1073 * Alias for userToolLinks( $userId, $userText, true );
1074 * @param int $userId User identifier
1075 * @param string $userText User name or IP address
1076 * @param int $edits, user edit count (optional, for performance)
1077 */
1078 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1079 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1080 }
1081
1082
1083 /**
1084 * @param $userId Integer: user id in database.
1085 * @param $userText String: user name in database.
1086 * @return string HTML fragment with user talk link
1087 * @private
1088 */
1089 function userTalkLink( $userId, $userText ) {
1090 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1091 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1092 return $userTalkLink;
1093 }
1094
1095 /**
1096 * @param $userId Integer: userid
1097 * @param $userText String: user name in database.
1098 * @return string HTML fragment with block link
1099 * @private
1100 */
1101 function blockLink( $userId, $userText ) {
1102 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
1103 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1104 return $blockLink;
1105 }
1106
1107 /**
1108 * Generate a user link if the current user is allowed to view it
1109 * @param $rev Revision object.
1110 * @param $isPublic, bool, show only if all users can see it
1111 * @return string HTML
1112 */
1113 function revUserLink( $rev, $isPublic = false ) {
1114 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1115 $link = wfMsgHtml( 'rev-deleted-user' );
1116 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1117 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
1118 } else {
1119 $link = wfMsgHtml( 'rev-deleted-user' );
1120 }
1121 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1122 return '<span class="history-deleted">' . $link . '</span>';
1123 }
1124 return $link;
1125 }
1126
1127 /**
1128 * Generate a user tool link cluster if the current user is allowed to view it
1129 * @param $rev Revision object.
1130 * @param $isPublic, bool, show only if all users can see it
1131 * @return string HTML
1132 */
1133 function revUserTools( $rev, $isPublic = false ) {
1134 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1135 $link = wfMsgHtml( 'rev-deleted-user' );
1136 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1137 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
1138 ' ' . $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
1139 } else {
1140 $link = wfMsgHtml( 'rev-deleted-user' );
1141 }
1142 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1143 return ' <span class="history-deleted">' . $link . '</span>';
1144 }
1145 return $link;
1146 }
1147
1148 /**
1149 * This function is called by all recent changes variants, by the page history,
1150 * and by the user contributions list. It is responsible for formatting edit
1151 * comments. It escapes any HTML in the comment, but adds some CSS to format
1152 * auto-generated comments (from section editing) and formats [[wikilinks]].
1153 *
1154 * @author Erik Moeller <moeller@scireview.de>
1155 *
1156 * Note: there's not always a title to pass to this function.
1157 * Since you can't set a default parameter for a reference, I've turned it
1158 * temporarily to a value pass. Should be adjusted further. --brion
1159 *
1160 * @param string $comment
1161 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1162 * @param bool $local Whether section links should refer to local page
1163 */
1164 function formatComment($comment, $title = NULL, $local = false) {
1165 wfProfileIn( __METHOD__ );
1166
1167 # Sanitize text a bit:
1168 $comment = str_replace( "\n", " ", $comment );
1169 $comment = htmlspecialchars( $comment );
1170
1171 # Render autocomments and make links:
1172 $comment = $this->formatAutoComments( $comment, $title, $local );
1173 $comment = $this->formatLinksInComment( $comment );
1174
1175 wfProfileOut( __METHOD__ );
1176 return $comment;
1177 }
1178
1179 /**
1180 * The pattern for autogen comments is / * foo * /, which makes for
1181 * some nasty regex.
1182 * We look for all comments, match any text before and after the comment,
1183 * add a separator where needed and format the comment itself with CSS
1184 * Called by Linker::formatComment.
1185 *
1186 * @param string $comment Comment text
1187 * @param object $title An optional title object used to links to sections
1188 * @return string $comment formatted comment
1189 *
1190 * @todo Document the $local parameter.
1191 */
1192 private function formatAutocomments( $comment, $title = null, $local = false ) {
1193 $match = array();
1194 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
1195 $pre=$match[1];
1196 $auto=$match[2];
1197 $post=$match[3];
1198 $link='';
1199 if( $title ) {
1200 $section = $auto;
1201
1202 # Generate a valid anchor name from the section title.
1203 # Hackish, but should generally work - we strip wiki
1204 # syntax, including the magic [[: that is used to
1205 # "link rather than show" in case of images and
1206 # interlanguage links.
1207 $section = str_replace( '[[:', '', $section );
1208 $section = str_replace( '[[', '', $section );
1209 $section = str_replace( ']]', '', $section );
1210 if ( $local ) {
1211 $sectionTitle = Title::newFromText( '#' . $section );
1212 } else {
1213 $sectionTitle = clone( $title );
1214 $sectionTitle->mFragment = $section;
1215 }
1216 $link = $this->link( $sectionTitle,
1217 wfMsgForContent( 'sectionlink' ), array(), array(),
1218 'noclasses' );
1219 }
1220 $auto = $link . $auto;
1221 if( $pre ) {
1222 # written summary $presep autocomment (summary /* section */)
1223 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1224 }
1225 if( $post ) {
1226 # autocomment $postsep written summary (/* section */ summary)
1227 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1228 }
1229 $auto = '<span class="autocomment">' . $auto . '</span>';
1230 $comment = $pre . $auto . $post;
1231 }
1232
1233 return $comment;
1234 }
1235
1236 /**
1237 * Formats wiki links and media links in text; all other wiki formatting
1238 * is ignored
1239 *
1240 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1241 * @param string $comment Text to format links in
1242 * @return string
1243 */
1244 public function formatLinksInComment( $comment ) {
1245 return preg_replace_callback(
1246 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1247 array( $this, 'formatLinksInCommentCallback' ),
1248 $comment );
1249 }
1250
1251 protected function formatLinksInCommentCallback( $match ) {
1252 global $wgContLang;
1253
1254 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1255 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1256
1257 $comment = $match[0];
1258
1259 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1260 if( strpos( $match[1], '%' ) !== false ) {
1261 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1262 }
1263
1264 # Handle link renaming [[foo|text]] will show link as "text"
1265 if( "" != $match[3] ) {
1266 $text = $match[3];
1267 } else {
1268 $text = $match[1];
1269 }
1270 $submatch = array();
1271 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1272 # Media link; trail not supported.
1273 $linkRegexp = '/\[\[(.*?)\]\]/';
1274 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1275 } else {
1276 # Other kind of link
1277 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1278 $trail = $submatch[1];
1279 } else {
1280 $trail = "";
1281 }
1282 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1283 if (isset($match[1][0]) && $match[1][0] == ':')
1284 $match[1] = substr($match[1], 1);
1285 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1286 }
1287 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1288
1289 return $comment;
1290 }
1291
1292 /**
1293 * Wrap a comment in standard punctuation and formatting if
1294 * it's non-empty, otherwise return empty string.
1295 *
1296 * @param string $comment
1297 * @param mixed $title Title object (to generate link to section in autocomment) or null
1298 * @param bool $local Whether section links should refer to local page
1299 *
1300 * @return string
1301 */
1302 function commentBlock( $comment, $title = NULL, $local = false ) {
1303 // '*' used to be the comment inserted by the software way back
1304 // in antiquity in case none was provided, here for backwards
1305 // compatability, acc. to brion -ævar
1306 if( $comment == '' || $comment == '*' ) {
1307 return '';
1308 } else {
1309 $formatted = $this->formatComment( $comment, $title, $local );
1310 return " <span class=\"comment\">($formatted)</span>";
1311 }
1312 }
1313
1314 /**
1315 * Wrap and format the given revision's comment block, if the current
1316 * user is allowed to view it.
1317 *
1318 * @param Revision $rev
1319 * @param bool $local Whether section links should refer to local page
1320 * @param $isPublic, show only if all users can see it
1321 * @return string HTML
1322 */
1323 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1324 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1325 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1326 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1327 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1328 } else {
1329 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1330 }
1331 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1332 return " <span class=\"history-deleted\">$block</span>";
1333 }
1334 return $block;
1335 }
1336
1337 public function formatRevisionSize( $size ) {
1338 if ( $size == 0 ) {
1339 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1340 } else {
1341 global $wgLang;
1342 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1343 $stxt = "($stxt)";
1344 }
1345 $stxt = htmlspecialchars( $stxt );
1346 return "<span class=\"history-size\">$stxt</span>";
1347 }
1348
1349 /** @todo document */
1350 function tocIndent() {
1351 return "\n<ul>";
1352 }
1353
1354 /** @todo document */
1355 function tocUnindent($level) {
1356 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1357 }
1358
1359 /**
1360 * parameter level defines if we are on an indentation level
1361 */
1362 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1363 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1364 $anchor . '"><span class="tocnumber">' .
1365 $tocnumber . '</span> <span class="toctext">' .
1366 $tocline . '</span></a>';
1367 }
1368
1369 /** @todo document */
1370 function tocLineEnd() {
1371 return "</li>\n";
1372 }
1373
1374 /** @todo document */
1375 function tocList($toc) {
1376 global $wgJsMimeType;
1377 $title = wfMsgHtml('toc') ;
1378 return
1379 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1380 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1381 . $toc
1382 # no trailing newline, script should not be wrapped in a
1383 # paragraph
1384 . "</ul>\n</td></tr></table>"
1385 . '<script type="' . $wgJsMimeType . '">'
1386 . ' if (window.showTocToggle) {'
1387 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1388 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1389 . ' showTocToggle();'
1390 . ' } '
1391 . "</script>\n";
1392 }
1393
1394 /**
1395 * Used to generate section edit links that point to "other" pages
1396 * (sections that are really part of included pages).
1397 *
1398 * @param $title Title string.
1399 * @param $section Integer: section number.
1400 */
1401 public function editSectionLinkForOther( $title, $section ) {
1402 wfDeprecated( __METHOD__ );
1403 $title = Title::newFromText( $title );
1404 return $this->doEditSectionLink( $title, $section );
1405 }
1406
1407 /**
1408 * @param $nt Title object.
1409 * @param $section Integer: section number.
1410 * @param $hint Link String: title, or default if omitted or empty
1411 */
1412 public function editSectionLink( Title $nt, $section, $hint = '' ) {
1413 wfDeprecated( __METHOD__ );
1414 if( $hint === '' ) {
1415 # No way to pass an actual empty $hint here! The new interface al-
1416 # lows this, so we have to do this for compatibility.
1417 $hint = null;
1418 }
1419 return $this->doEditSectionLink( $nt, $section, $hint );
1420 }
1421
1422 /**
1423 * Create a section edit link. This supersedes editSectionLink() and
1424 * editSectionLinkForOther().
1425 *
1426 * @param $nt Title The title being linked to (may not be the same as
1427 * $wgTitle, if the section is included from a template)
1428 * @param $section string The designation of the section being pointed to,
1429 * to be included in the link, like "&section=$section"
1430 * @param $tooltip string The tooltip to use for the link: will be escaped
1431 * and wrapped in the 'editsectionhint' message
1432 * @return string HTML to use for edit link
1433 */
1434 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1435 $attribs = array();
1436 if( !is_null( $tooltip ) ) {
1437 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1438 }
1439 $url = $this->link( $nt, wfMsg('editsection'),
1440 $attribs,
1441 array( 'action' => 'edit', 'section' => $section ),
1442 array( 'noclasses', 'known' )
1443 );
1444
1445 # Run the old hook. This takes up half of the function . . . hopefully
1446 # we can rid of it someday.
1447 $attribs = '';
1448 if( $tooltip ) {
1449 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1450 $attribs = " title=\"$attribs\"";
1451 }
1452 $result = null;
1453 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $url, &$result ) );
1454 if( !is_null( $result ) ) {
1455 # For reverse compatibility, add the brackets *after* the hook is
1456 # run, and even add them to hook-provided text. (This is the main
1457 # reason that the EditSectionLink hook is deprecated in favor of
1458 # DoEditSectionLink: it can't change the brackets or the span.)
1459 $result = wfMsgHtml( 'editsection-brackets', $url );
1460 return "<span class=\"editsection\">$result</span>";
1461 }
1462
1463 # Add the brackets and the span, and *then* run the nice new hook, with
1464 # clean and non-redundant arguments.
1465 $result = wfMsgHtml( 'editsection-brackets', $url );
1466 $result = "<span class=\"editsection\">$result</span>";
1467
1468 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1469 return $result;
1470 }
1471
1472 /**
1473 * Create a headline for content
1474 *
1475 * @param int $level The level of the headline (1-6)
1476 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1477 * This *must* be at least '>' for no attribs
1478 * @param string $anchor The anchor to give the headline (the bit after the #)
1479 * @param string $text The text of the header
1480 * @param string $link HTML to add for the section edit link
1481 *
1482 * @return string HTML headline
1483 */
1484 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1485 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1486 }
1487
1488 /**
1489 * Split a link trail, return the "inside" portion and the remainder of the trail
1490 * as a two-element array
1491 *
1492 * @static
1493 */
1494 static function splitTrail( $trail ) {
1495 static $regex = false;
1496 if ( $regex === false ) {
1497 global $wgContLang;
1498 $regex = $wgContLang->linkTrail();
1499 }
1500 $inside = '';
1501 if ( '' != $trail ) {
1502 $m = array();
1503 if ( preg_match( $regex, $trail, $m ) ) {
1504 $inside = $m[1];
1505 $trail = $m[2];
1506 }
1507 }
1508 return array( $inside, $trail );
1509 }
1510
1511 /**
1512 * Generate a rollback link for a given revision. Currently it's the
1513 * caller's responsibility to ensure that the revision is the top one. If
1514 * it's not, of course, the user will get an error message.
1515 *
1516 * If the calling page is called with the parameter &bot=1, all rollback
1517 * links also get that parameter. It causes the edit itself and the rollback
1518 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1519 * changes, so this allows sysops to combat a busy vandal without bothering
1520 * other users.
1521 *
1522 * @param Revision $rev
1523 */
1524 function generateRollback( $rev ) {
1525 return '<span class="mw-rollback-link">['
1526 . $this->buildRollbackLink( $rev )
1527 . ']</span>';
1528 }
1529
1530 /**
1531 * Build a raw rollback link, useful for collections of "tool" links
1532 *
1533 * @param Revision $rev
1534 * @return string
1535 */
1536 public function buildRollbackLink( $rev ) {
1537 global $wgRequest, $wgUser;
1538 $title = $rev->getTitle();
1539 $query = array(
1540 'action' => 'rollback',
1541 'from' => $rev->getUserText()
1542 );
1543 if( $wgRequest->getBool( 'bot' ) ) {
1544 $query['bot'] = '1';
1545 }
1546 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1547 $rev->getUserText() ) );
1548 return $this->link( $title, wfMsgHtml( 'rollbacklink' ), array(),
1549 $query, array( 'known', 'noclasses' ) );
1550 }
1551
1552 /**
1553 * Returns HTML for the "templates used on this page" list.
1554 *
1555 * @param array $templates Array of templates from Article::getUsedTemplate
1556 * or similar
1557 * @param bool $preview Whether this is for a preview
1558 * @param bool $section Whether this is for a section edit
1559 * @return string HTML output
1560 */
1561 public function formatTemplates( $templates, $preview = false, $section = false) {
1562 global $wgUser;
1563 wfProfileIn( __METHOD__ );
1564
1565 $sk = $wgUser->getSkin();
1566
1567 $outText = '';
1568 if ( count( $templates ) > 0 ) {
1569 # Do a batch existence check
1570 $batch = new LinkBatch;
1571 foreach( $templates as $title ) {
1572 $batch->addObj( $title );
1573 }
1574 $batch->execute();
1575
1576 # Construct the HTML
1577 $outText = '<div class="mw-templatesUsedExplanation">';
1578 if ( $preview ) {
1579 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1580 } elseif ( $section ) {
1581 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1582 } else {
1583 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1584 }
1585 $outText .= '</div><ul>';
1586
1587 usort( $templates, array( 'Title', 'compare' ) );
1588 foreach ( $templates as $titleObj ) {
1589 $r = $titleObj->getRestrictions( 'edit' );
1590 if ( in_array( 'sysop', $r ) ) {
1591 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1592 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1593 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1594 } else {
1595 $protected = '';
1596 }
1597 $outText .= '<li>' . $sk->link( $titleObj ) . ' ' . $protected . '</li>';
1598 }
1599 $outText .= '</ul>';
1600 }
1601 wfProfileOut( __METHOD__ );
1602 return $outText;
1603 }
1604
1605 /**
1606 * Returns HTML for the "hidden categories on this page" list.
1607 *
1608 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1609 * or similar
1610 * @return string HTML output
1611 */
1612 public function formatHiddenCategories( $hiddencats) {
1613 global $wgUser, $wgLang;
1614 wfProfileIn( __METHOD__ );
1615
1616 $sk = $wgUser->getSkin();
1617
1618 $outText = '';
1619 if ( count( $hiddencats ) > 0 ) {
1620 # Construct the HTML
1621 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1622 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1623 $outText .= '</div><ul>';
1624
1625 foreach ( $hiddencats as $titleObj ) {
1626 $outText .= '<li>' . $sk->link( $titleObj, null, array(), array(), 'known' ) . '</li>'; # If it's hidden, it must exist - no need to check with a LinkBatch
1627 }
1628 $outText .= '</ul>';
1629 }
1630 wfProfileOut( __METHOD__ );
1631 return $outText;
1632 }
1633
1634 /**
1635 * Format a size in bytes for output, using an appropriate
1636 * unit (B, KB, MB or GB) according to the magnitude in question
1637 *
1638 * @param $size Size to format
1639 * @return string
1640 */
1641 public function formatSize( $size ) {
1642 global $wgLang;
1643 return htmlspecialchars( $wgLang->formatSize( $size ) );
1644 }
1645
1646 /**
1647 * Given the id of an interface element, constructs the appropriate title
1648 * and accesskey attributes from the system messages. (Note, this is usu-
1649 * ally the id but isn't always, because sometimes the accesskey needs to
1650 * go on a different element than the id, for reverse-compatibility, etc.)
1651 *
1652 * @param string $name Id of the element, minus prefixes.
1653 * @return string title and accesskey attributes, ready to drop in an
1654 * element (e.g., ' title="This does something [x]" accesskey="x"').
1655 */
1656 public function tooltipAndAccesskey($name) {
1657 $fname="Linker::tooltipAndAccesskey";
1658 wfProfileIn($fname);
1659 $out = '';
1660
1661 $tooltip = wfMsg('tooltip-'.$name);
1662 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1663 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1664 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1665 $out .= ' title="'.htmlspecialchars($tooltip);
1666 }
1667 $accesskey = wfMsg('accesskey-'.$name);
1668 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1669 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1670 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1671 } elseif ($out) {
1672 $out .= '"';
1673 }
1674 wfProfileOut($fname);
1675 return $out;
1676 }
1677
1678 /**
1679 * Given the id of an interface element, constructs the appropriate title
1680 * attribute from the system messages. (Note, this is usually the id but
1681 * isn't always, because sometimes the accesskey needs to go on a different
1682 * element than the id, for reverse-compatibility, etc.)
1683 *
1684 * @param string $name Id of the element, minus prefixes.
1685 * @return string title attribute, ready to drop in an element
1686 * (e.g., ' title="This does something"').
1687 */
1688 public function tooltip($name) {
1689 $out = '';
1690
1691 $tooltip = wfMsg('tooltip-'.$name);
1692 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1693 $out = ' title="'.htmlspecialchars($tooltip).'"';
1694 }
1695
1696 return $out;
1697 }
1698 }