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