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