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