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