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