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