Clean up last commit: OutputPage::formatTemplates + EditPage::formatTemplates ->...
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php.
4 * These functions are used for primarily page content:
5 * links, embedded images, table of contents. Links are
6 * also used in the skin.
7 * @package MediaWiki
8 */
9
10 /**
11 * For the moment, Skin is a descendent class of Linker.
12 * In the future, it should probably be further split
13 * so that ever other bit of the wiki doesn't have to
14 * go loading up Skin to get at it.
15 *
16 * @package MediaWiki
17 */
18 class Linker {
19
20 function Linker() {}
21
22 /**
23 * @deprecated
24 */
25 function postParseLinkColour( $s = NULL ) {
26 return NULL;
27 }
28
29 /** @todo document */
30 function getExternalLinkAttributes( $link, $text, $class='' ) {
31 $link = htmlspecialchars( $link );
32
33 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
34
35 $r .= " title=\"{$link}\"";
36 return $r;
37 }
38
39 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
40 global $wgContLang;
41
42 $same = ($link == $text);
43 $link = urldecode( $link );
44 $link = $wgContLang->checkTitleEncoding( $link );
45 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
46 $link = htmlspecialchars( $link );
47
48 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
49
50 $r .= " title=\"{$link}\"";
51 return $r;
52 }
53
54 /** @todo document */
55 function getInternalLinkAttributes( $link, $text, $broken = false ) {
56 $link = urldecode( $link );
57 $link = str_replace( '_', ' ', $link );
58 $link = htmlspecialchars( $link );
59
60 if( $broken == 'stub' ) {
61 $r = ' class="stub"';
62 } else if ( $broken == 'yes' ) {
63 $r = ' class="new"';
64 } else {
65 $r = '';
66 }
67
68 $r .= " title=\"{$link}\"";
69 return $r;
70 }
71
72 /**
73 * @param $nt Title object.
74 * @param $text String: FIXME
75 * @param $broken Boolean: FIXME, default 'false'.
76 */
77 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
78 if( $broken == 'stub' ) {
79 $r = ' class="stub"';
80 } else if ( $broken == 'yes' ) {
81 $r = ' class="new"';
82 } else {
83 $r = '';
84 }
85
86 $r .= ' title="' . $nt->getEscapedText() . '"';
87 return $r;
88 }
89
90 /**
91 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
92 * it if you already have a title object handy. See makeLinkObj for further documentation.
93 *
94 * @param $title String: the text of the title
95 * @param $text String: link text
96 * @param $query String: optional query part
97 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
98 * be included in the link text. Other characters will be appended after
99 * the end of the link.
100 */
101 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
102 wfProfileIn( 'Linker::makeLink' );
103 $nt = Title::newFromText( $title );
104 if ($nt) {
105 $result = $this->makeLinkObj( Title::newFromText( $title ), $text, $query, $trail );
106 } else {
107 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
108 $result = $text == "" ? $title : $text;
109 }
110
111 wfProfileOut( 'Linker::makeLink' );
112 return $result;
113 }
114
115 /**
116 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
117 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
118 *
119 * @param $title String: the text of the title
120 * @param $text String: link text
121 * @param $query String: optional query part
122 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
123 * be included in the link text. Other characters will be appended after
124 * the end of the link.
125 */
126 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
127 $nt = Title::newFromText( $title );
128 if ($nt) {
129 return $this->makeKnownLinkObj( Title::newFromText( $title ), $text, $query, $trail, $prefix , $aprops );
130 } else {
131 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
132 return $text == '' ? $title : $text;
133 }
134 }
135
136 /**
137 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
138 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
139 *
140 * @param string $title The text of the title
141 * @param string $text Link text
142 * @param string $query Optional query part
143 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
144 * be included in the link text. Other characters will be appended after
145 * the end of the link.
146 */
147 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
148 $nt = Title::newFromText( $title );
149 if ($nt) {
150 return $this->makeBrokenLinkObj( Title::newFromText( $title ), $text, $query, $trail );
151 } else {
152 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
153 return $text == '' ? $title : $text;
154 }
155 }
156
157 /**
158 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
159 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
160 *
161 * @param $title String: the text of the title
162 * @param $text String: link text
163 * @param $query String: optional query part
164 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
165 * be included in the link text. Other characters will be appended after
166 * the end of the link.
167 */
168 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
169 $nt = Title::newFromText( $title );
170 if ($nt) {
171 return $this->makeStubLinkObj( Title::newFromText( $title ), $text, $query, $trail );
172 } else {
173 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
174 return $text == '' ? $title : $text;
175 }
176 }
177
178 /**
179 * Make a link for a title which may or may not be in the database. If you need to
180 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
181 * call to this will result in a DB query.
182 *
183 * @param $nt Title: the title object to make the link from, e.g. from
184 * Title::newFromText.
185 * @param $text String: link text
186 * @param $query String: optional query part
187 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
188 * be included in the link text. Other characters will be appended after
189 * the end of the link.
190 * @param $prefix String: optional prefix. As trail, only before instead of after.
191 */
192 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
193 global $wgUser;
194 $fname = 'Linker::makeLinkObj';
195 wfProfileIn( $fname );
196
197 # Fail gracefully
198 if ( ! is_object($nt) ) {
199 # throw new MWException();
200 wfProfileOut( $fname );
201 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
202 }
203
204 $ns = $nt->getNamespace();
205 $dbkey = $nt->getDBkey();
206 if ( $nt->isExternal() ) {
207 $u = $nt->getFullURL();
208 $link = $nt->getPrefixedURL();
209 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
210 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
211
212 $inside = '';
213 if ( '' != $trail ) {
214 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
215 $inside = $m[1];
216 $trail = $m[2];
217 }
218 }
219
220 # Check for anchors, normalize the anchor
221
222 $parts = explode( '#', $u, 2 );
223 if ( count( $parts ) == 2 ) {
224 $anchor = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $parts[1] ) ) );
225 $replacearray = array(
226 '%3A' => ':',
227 '%' => '.'
228 );
229 $u = $parts[0] . '#' .
230 str_replace( array_keys( $replacearray ),
231 array_values( $replacearray ),
232 $anchor );
233 }
234
235 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
236
237 wfProfileOut( $fname );
238 return $t;
239 } elseif ( $nt->isAlwaysKnown() ) {
240 # Image links, special page links and self-links with fragements are always known.
241 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
242 } else {
243 wfProfileIn( $fname.'-immediate' );
244 # Work out link colour immediately
245 $aid = $nt->getArticleID() ;
246 if ( 0 == $aid ) {
247 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
248 } else {
249 $threshold = $wgUser->getOption('stubthreshold') ;
250 if ( $threshold > 0 ) {
251 $dbr =& wfGetDB( DB_SLAVE );
252 $s = $dbr->selectRow(
253 array( 'page' ),
254 array( 'page_len',
255 'page_namespace',
256 'page_is_redirect' ),
257 array( 'page_id' => $aid ), $fname ) ;
258 if ( $s !== false ) {
259 $size = $s->page_len;
260 if ( $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
261 $size = $threshold*2 ; # Really big
262 }
263 } else {
264 $size = $threshold*2 ; # Really big
265 }
266 } else {
267 $size = 1 ;
268 }
269 if ( $size < $threshold ) {
270 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
271 } else {
272 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
273 }
274 }
275 wfProfileOut( $fname.'-immediate' );
276 }
277 wfProfileOut( $fname );
278 return $retVal;
279 }
280
281 /**
282 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
283 * it doesn't have to do a database query. It's also valid for interwiki titles and special
284 * pages.
285 *
286 * @param $nt Title object of target page
287 * @param $text String: text to replace the title
288 * @param $query String: link target
289 * @param $trail String: text after link
290 * @param $prefix String: text before link text
291 * @param $aprops String: extra attributes to the a-element
292 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
293 * @return the a-element
294 */
295 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
296
297 $fname = 'Linker::makeKnownLinkObj';
298 wfProfileIn( $fname );
299
300 if ( !is_object( $nt ) ) {
301 wfProfileOut( $fname );
302 return $text;
303 }
304
305 $u = $nt->escapeLocalURL( $query );
306 if ( $nt->getFragment() != '' ) {
307 if( $nt->getPrefixedDbkey() == '' ) {
308 $u = '';
309 if ( '' == $text ) {
310 $text = htmlspecialchars( $nt->getFragment() );
311 }
312 }
313 $anchor = urlencode( Sanitizer::decodeCharReferences( str_replace( ' ', '_', $nt->getFragment() ) ) );
314 $replacearray = array(
315 '%3A' => ':',
316 '%' => '.'
317 );
318 $u .= '#' . str_replace(array_keys($replacearray),array_values($replacearray),$anchor);
319 }
320 if ( $text == '' ) {
321 $text = htmlspecialchars( $nt->getPrefixedText() );
322 }
323 if ( $style == '' ) {
324 $style = $this->getInternalLinkAttributesObj( $nt, $text );
325 }
326
327 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
328
329 list( $inside, $trail ) = Linker::splitTrail( $trail );
330 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
331 wfProfileOut( $fname );
332 return $r;
333 }
334
335 /**
336 * Make a red link to the edit page of a given title.
337 *
338 * @param $title String: The text of the title
339 * @param $text String: Link text
340 * @param $query String: Optional query part
341 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
342 * be included in the link text. Other characters will be appended after
343 * the end of the link.
344 */
345 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
346 # Fail gracefully
347 if ( ! isset($nt) ) {
348 # throw new MWException();
349 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
350 }
351
352 $fname = 'Linker::makeBrokenLinkObj';
353 wfProfileIn( $fname );
354
355 if ( '' == $query ) {
356 $q = 'action=edit';
357 } else {
358 $q = 'action=edit&'.$query;
359 }
360 $u = $nt->escapeLocalURL( $q );
361
362 if ( '' == $text ) {
363 $text = htmlspecialchars( $nt->getPrefixedText() );
364 }
365 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
366
367 list( $inside, $trail ) = Linker::splitTrail( $trail );
368 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
369
370 wfProfileOut( $fname );
371 return $s;
372 }
373
374 /**
375 * Make a brown link to a short article.
376 *
377 * @param $title String: the text of the title
378 * @param $text String: link text
379 * @param $query String: optional query part
380 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
381 * be included in the link text. Other characters will be appended after
382 * the end of the link.
383 */
384 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
385 $link = $nt->getPrefixedURL();
386
387 $u = $nt->escapeLocalURL( $query );
388
389 if ( '' == $text ) {
390 $text = htmlspecialchars( $nt->getPrefixedText() );
391 }
392 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
393
394 list( $inside, $trail ) = Linker::splitTrail( $trail );
395 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
396 return $s;
397 }
398
399 /**
400 * Generate either a normal exists-style link or a stub link, depending
401 * on the given page size.
402 *
403 * @param $size Integer
404 * @param $nt Title object.
405 * @param $text String
406 * @param $query String
407 * @param $trail String
408 * @param $prefix String
409 * @return string HTML of link
410 */
411 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
412 global $wgUser;
413 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
414 if( $size < $threshold ) {
415 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
416 } else {
417 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
418 }
419 }
420
421 /**
422 * Make appropriate markup for a link to the current article. This is currently rendered
423 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
424 * despite $query not being used.
425 */
426 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
427 if ( '' == $text ) {
428 $text = htmlspecialchars( $nt->getPrefixedText() );
429 }
430 list( $inside, $trail ) = Linker::splitTrail( $trail );
431 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
432 }
433
434 /** @todo document */
435 function fnamePart( $url ) {
436 $basename = strrchr( $url, '/' );
437 if ( false === $basename ) {
438 $basename = $url;
439 } else {
440 $basename = substr( $basename, 1 );
441 }
442 return htmlspecialchars( $basename );
443 }
444
445 /** Obsolete alias */
446 function makeImage( $url, $alt = '' ) {
447 return $this->makeExternalImage( $url, $alt );
448 }
449
450 /** @todo document */
451 function makeExternalImage( $url, $alt = '' ) {
452 if ( '' == $alt ) {
453 $alt = $this->fnamePart( $url );
454 }
455 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
456 return $s;
457 }
458
459 /** @todo document */
460 function makeImageLinkObj( $nt, $label, $alt, $align = '', $width = false, $height = false, $framed = false,
461 $thumb = false, $manual_thumb = '', $page = null )
462 {
463 global $wgContLang, $wgUser, $wgThumbLimits, $wgGenerateThumbnailOnParse;
464
465 $img = new Image( $nt );
466
467 if ( ! is_null( $page ) ) {
468 $img->selectPage( $page );
469 }
470
471 if ( !$img->allowInlineDisplay() && $img->exists() ) {
472 return $this->makeKnownLinkObj( $nt );
473 }
474
475 $url = $img->getViewURL();
476 $error = $prefix = $postfix = '';
477
478 wfDebug( "makeImageLinkObj: '$width'x'$height', \"$label\"\n" );
479
480 if ( 'center' == $align )
481 {
482 $prefix = '<div class="center">';
483 $postfix = '</div>';
484 $align = 'none';
485 }
486
487 if ( $thumb || $framed ) {
488
489 # Create a thumbnail. Alignment depends on language
490 # writing direction, # right aligned for left-to-right-
491 # languages ("Western languages"), left-aligned
492 # for right-to-left-languages ("Semitic languages")
493 #
494 # If thumbnail width has not been provided, it is set
495 # to the default user option as specified in Language*.php
496 if ( $align == '' ) {
497 $align = $wgContLang->isRTL() ? 'left' : 'right';
498 }
499
500
501 if ( $width === false ) {
502 $wopt = $wgUser->getOption( 'thumbsize' );
503
504 if( !isset( $wgThumbLimits[$wopt] ) ) {
505 $wopt = User::getDefaultOption( 'thumbsize' );
506 }
507
508 $width = min( $img->getWidth(), $wgThumbLimits[$wopt] );
509 }
510
511 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $width, $height, $framed, $manual_thumb ).$postfix;
512 }
513
514 if ( $width && $img->exists() ) {
515
516 # Create a resized image, without the additional thumbnail
517 # features
518
519 if ( $height == false )
520 $height = -1;
521 if ( $manual_thumb == '') {
522 $thumb = $img->getThumbnail( $width, $height, $wgGenerateThumbnailOnParse );
523 if ( $thumb ) {
524 // In most cases, $width = $thumb->width or $height = $thumb->height.
525 // If not, we're scaling the image larger than it can be scaled,
526 // so we send to the browser a smaller thumbnail, and let the client do the scaling.
527
528 if ($height != -1 && $width > $thumb->width * $height / $thumb->height) {
529 // $height is the limiting factor, not $width
530 // set $width to the largest it can be, such that the resulting
531 // scaled height is at most $height
532 $width = floor($thumb->width * $height / $thumb->height);
533 }
534 $height = round($thumb->height * $width / $thumb->width);
535
536 wfDebug( "makeImageLinkObj: client-size set to '$width x $height'\n" );
537 $url = $thumb->getUrl();
538 } else {
539 $error = htmlspecialchars( $img->getLastError() );
540 // Do client-side scaling...
541 $height = intval( $img->getHeight() * $width / $img->getWidth() );
542 }
543 }
544 } else {
545 $width = $img->width;
546 $height = $img->height;
547 }
548
549 wfDebug( "makeImageLinkObj2: '$width'x'$height'\n" );
550 $u = $nt->escapeLocalURL();
551 if ( $error ) {
552 $s = $error;
553 } elseif ( $url == '' ) {
554 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
555 //$s .= "<br />{$alt}<br />{$url}<br />\n";
556 } else {
557 $s = '<a href="'.$u.'" class="image" title="'.$alt.'">' .
558 '<img src="'.$url.'" alt="'.$alt.'" ' .
559 ( $width
560 ? ( 'width="'.$width.'" height="'.$height.'" ' )
561 : '' ) .
562 'longdesc="'.$u.'" /></a>';
563 }
564 if ( '' != $align ) {
565 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
566 }
567 return str_replace("\n", ' ',$prefix.$s.$postfix);
568 }
569
570 /**
571 * Make HTML for a thumbnail including image, border and caption
572 * $img is an Image object
573 */
574 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $boxwidth = 180, $boxheight=false, $framed=false , $manual_thumb = "" ) {
575 global $wgStylePath, $wgContLang, $wgGenerateThumbnailOnParse;
576 $thumbUrl = '';
577 $error = '';
578
579 $width = $height = 0;
580 if ( $img->exists() ) {
581 $width = $img->getWidth();
582 $height = $img->getHeight();
583 }
584 if ( 0 == $width || 0 == $height ) {
585 $width = $height = 180;
586 }
587 if ( $boxwidth == 0 ) {
588 $boxwidth = 180;
589 }
590 if ( $framed ) {
591 // Use image dimensions, don't scale
592 $boxwidth = $width;
593 $boxheight = $height;
594 $thumbUrl = $img->getViewURL();
595 } else {
596 if ( $boxheight === false )
597 $boxheight = -1;
598 if ( '' == $manual_thumb ) {
599 $thumb = $img->getThumbnail( $boxwidth, $boxheight, $wgGenerateThumbnailOnParse );
600 if ( $thumb ) {
601 $thumbUrl = $thumb->getUrl();
602 $boxwidth = $thumb->width;
603 $boxheight = $thumb->height;
604 } else {
605 $error = $img->getLastError();
606 }
607 }
608 }
609 $oboxwidth = $boxwidth + 2;
610
611 if ( $manual_thumb != '' ) # Use manually specified thumbnail
612 {
613 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb ); #new Title ( $manual_thumb ) ;
614 if( $manual_title ) {
615 $manual_img = new Image( $manual_title );
616 $thumbUrl = $manual_img->getViewURL();
617 if ( $manual_img->exists() )
618 {
619 $width = $manual_img->getWidth();
620 $height = $manual_img->getHeight();
621 $boxwidth = $width ;
622 $boxheight = $height ;
623 $oboxwidth = $boxwidth + 2 ;
624 }
625 }
626 }
627
628 $u = $img->getEscapeLocalURL();
629
630 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
631 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
632 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
633
634 $s = "<div class=\"thumb t{$align}\"><div style=\"width:{$oboxwidth}px;\">";
635 if( $thumbUrl == '' ) {
636 // Couldn't generate thumbnail? Scale the image client-side.
637 $thumbUrl = $img->getViewURL();
638 if( $boxheight == -1 ) {
639 // Approximate...
640 $boxheight = intval( $height * $boxwidth / $width );
641 }
642 }
643 if ( $error ) {
644 $s .= htmlspecialchars( $error );
645 $zoomicon = '';
646 } elseif( !$img->exists() ) {
647 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
648 $zoomicon = '';
649 } else {
650 $s .= '<a href="'.$u.'" class="internal" title="'.$alt.'">'.
651 '<img src="'.$thumbUrl.'" alt="'.$alt.'" ' .
652 'width="'.$boxwidth.'" height="'.$boxheight.'" ' .
653 'longdesc="'.$u.'" /></a>';
654 if ( $framed ) {
655 $zoomicon="";
656 } else {
657 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
658 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
659 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
660 'width="15" height="11" alt="'.$more.'" /></a></div>';
661 }
662 }
663 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
664 return str_replace("\n", ' ', $s);
665 }
666
667 /**
668 * Pass a title object, not a title string
669 */
670 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
671 # Fail gracefully
672 if ( ! isset($nt) ) {
673 # throw new MWException();
674 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
675 }
676
677 $fname = 'Linker::makeBrokenImageLinkObj';
678 wfProfileIn( $fname );
679
680 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
681 if ( '' != $query ) {
682 $q .= "&$query";
683 }
684 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
685 $url = $uploadTitle->escapeLocalURL( $q );
686
687 if ( '' == $text ) {
688 $text = htmlspecialchars( $nt->getPrefixedText() );
689 }
690 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
691 list( $inside, $trail ) = Linker::splitTrail( $trail );
692 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
693
694 wfProfileOut( $fname );
695 return $s;
696 }
697
698 /** @todo document */
699 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
700 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
701 return $this->makeMediaLinkObj( $nt, $alt );
702 }
703
704 /**
705 * Create a direct link to a given uploaded file.
706 *
707 * @param $title Title object.
708 * @param $text String: pre-sanitized HTML
709 * @param $nourl Boolean: Mask absolute URLs, so the parser doesn't
710 * linkify them (it is currently not context-aware)
711 * @return string HTML
712 *
713 * @public
714 * @todo Handle invalid or missing images better.
715 */
716 function makeMediaLinkObj( $title, $text = '' ) {
717 if( is_null( $title ) ) {
718 ### HOTFIX. Instead of breaking, return empty string.
719 return $text;
720 } else {
721 $name = $title->getDBKey();
722 $img = new Image( $title );
723 if( $img->exists() ) {
724 $url = $img->getURL();
725 $class = 'internal';
726 } else {
727 $upload = SpecialPage::getTitleFor( 'Upload' );
728 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
729 $class = 'new';
730 }
731 $alt = htmlspecialchars( $title->getText() );
732 if( $text == '' ) {
733 $text = $alt;
734 }
735 $u = htmlspecialchars( $url );
736 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
737 }
738 }
739
740 /** @todo document */
741 function specialLink( $name, $key = '' ) {
742 global $wgContLang;
743
744 if ( '' == $key ) { $key = strtolower( $name ); }
745 $pn = $wgContLang->ucfirst( $name );
746 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
747 wfMsg( $key ) );
748 }
749
750 /** @todo document */
751 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
752 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
753 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
754 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
755 $style .= ' rel="nofollow"';
756 }
757 $url = htmlspecialchars( $url );
758 if( $escape ) {
759 $text = htmlspecialchars( $text );
760 }
761 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
762 }
763
764 /**
765 * Make user link (or user contributions for unregistered users)
766 * @param $userId Integer: user id in database.
767 * @param $userText String: user name in database
768 * @return string HTML fragment
769 * @private
770 */
771 function userLink( $userId, $userText ) {
772 $encName = htmlspecialchars( $userText );
773 if( $userId == 0 ) {
774 $contribsPage = SpecialPage::getTitleFor( 'Contributions' );
775 return $this->makeKnownLinkObj( $contribsPage,
776 $encName, 'target=' . urlencode( $userText ) );
777 } else {
778 $userPage = Title::makeTitle( NS_USER, $userText );
779 return $this->makeLinkObj( $userPage, $encName );
780 }
781 }
782
783 /**
784 * @param $userId Integer: user id in database.
785 * @param $userText String: user name in database.
786 * @return string HTML fragment with talk and/or block links
787 * @private
788 */
789 function userToolLinks( $userId, $userText ) {
790 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
791 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
792 $blockable = ( $wgSysopUserBans || 0 == $userId );
793
794 $items = array();
795 if( $talkable ) {
796 $items[] = $this->userTalkLink( $userId, $userText );
797 }
798 if( $userId ) {
799 $contribsPage = SpecialPage::getTitleFor( 'Contributions' );
800 $items[] = $this->makeKnownLinkObj( $contribsPage,
801 wfMsgHtml( 'contribslink' ), 'target=' . urlencode( $userText ) );
802 }
803 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
804 $items[] = $this->blockLink( $userId, $userText );
805 }
806
807 if( $items ) {
808 return ' (' . implode( ' | ', $items ) . ')';
809 } else {
810 return '';
811 }
812 }
813
814 /**
815 * @param $userId Integer: user id in database.
816 * @param $userText String: user name in database.
817 * @return string HTML fragment with user talk link
818 * @private
819 */
820 function userTalkLink( $userId, $userText ) {
821 global $wgLang;
822 $talkname = $wgLang->getNsText( NS_TALK ); # use the shorter name
823
824 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
825 $userTalkLink = $this->makeLinkObj( $userTalkPage, $talkname );
826 return $userTalkLink;
827 }
828
829 /**
830 * @param $userId Integer: userid
831 * @param $userText String: user name in database.
832 * @return string HTML fragment with block link
833 * @private
834 */
835 function blockLink( $userId, $userText ) {
836 $blockPage = SpecialPage::getTitleFor( 'Blockip' );
837 $blockLink = $this->makeKnownLinkObj( $blockPage,
838 wfMsgHtml( 'blocklink' ), 'ip=' . urlencode( $userText ) );
839 return $blockLink;
840 }
841
842 /**
843 * Generate a user link if the current user is allowed to view it
844 * @param $rev Revision object.
845 * @return string HTML
846 */
847 function revUserLink( $rev ) {
848 if( $rev->userCan( Revision::DELETED_USER ) ) {
849 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
850 } else {
851 $link = wfMsgHtml( 'rev-deleted-user' );
852 }
853 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
854 return '<span class="history-deleted">' . $link . '</span>';
855 }
856 return $link;
857 }
858
859 /**
860 * Generate a user tool link cluster if the current user is allowed to view it
861 * @param $rev Revision object.
862 * @return string HTML
863 */
864 function revUserTools( $rev ) {
865 if( $rev->userCan( Revision::DELETED_USER ) ) {
866 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
867 ' ' .
868 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
869 } else {
870 $link = wfMsgHtml( 'rev-deleted-user' );
871 }
872 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
873 return '<span class="history-deleted">' . $link . '</span>';
874 }
875 return $link;
876 }
877
878 /**
879 * This function is called by all recent changes variants, by the page history,
880 * and by the user contributions list. It is responsible for formatting edit
881 * comments. It escapes any HTML in the comment, but adds some CSS to format
882 * auto-generated comments (from section editing) and formats [[wikilinks]].
883 *
884 * The $title parameter must be a title OBJECT. It is used to generate a
885 * direct link to the section in the autocomment.
886 * @author Erik Moeller <moeller@scireview.de>
887 *
888 * Note: there's not always a title to pass to this function.
889 * Since you can't set a default parameter for a reference, I've turned it
890 * temporarily to a value pass. Should be adjusted further. --brion
891 */
892 function formatComment($comment, $title = NULL) {
893 $fname = 'Linker::formatComment';
894 wfProfileIn( $fname );
895
896 global $wgContLang;
897 $comment = str_replace( "\n", " ", $comment );
898 $comment = htmlspecialchars( $comment );
899
900 # The pattern for autogen comments is / * foo * /, which makes for
901 # some nasty regex.
902 # We look for all comments, match any text before and after the comment,
903 # add a separator where needed and format the comment itself with CSS
904 while (preg_match('/(.*)\/\*\s*(.*?)\s*\*\/(.*)/', $comment,$match)) {
905 $pre=$match[1];
906 $auto=$match[2];
907 $post=$match[3];
908 $link='';
909 if( $title ) {
910 $section = $auto;
911
912 # Generate a valid anchor name from the section title.
913 # Hackish, but should generally work - we strip wiki
914 # syntax, including the magic [[: that is used to
915 # "link rather than show" in case of images and
916 # interlanguage links.
917 $section = str_replace( '[[:', '', $section );
918 $section = str_replace( '[[', '', $section );
919 $section = str_replace( ']]', '', $section );
920 $sectionTitle = wfClone( $title );
921 $sectionTitle->mFragment = $section;
922 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
923 }
924 $sep='-';
925 $auto=$link.$auto;
926 if($pre) { $auto = $sep.' '.$auto; }
927 if($post) { $auto .= ' '.$sep; }
928 $auto='<span class="autocomment">'.$auto.'</span>';
929 $comment=$pre.$auto.$post;
930 }
931
932 # format regular and media links - all other wiki formatting
933 # is ignored
934 $medians = $wgContLang->getNsText( NS_MEDIA ) . ':';
935 while(preg_match('/\[\[(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
936 # Handle link renaming [[foo|text]] will show link as "text"
937 if( "" != $match[3] ) {
938 $text = $match[3];
939 } else {
940 $text = $match[1];
941 }
942 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
943 # Media link; trail not supported.
944 $linkRegexp = '/\[\[(.*?)\]\]/';
945 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
946 } else {
947 # Other kind of link
948 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
949 $trail = $submatch[1];
950 } else {
951 $trail = "";
952 }
953 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
954 if (isset($match[1][0]) && $match[1][0] == ':')
955 $match[1] = substr($match[1], 1);
956 $thelink = $this->makeLink( $match[1], $text, "", $trail );
957 }
958 $comment = preg_replace( $linkRegexp, wfRegexReplacement( $thelink ), $comment, 1 );
959 }
960 wfProfileOut( $fname );
961 return $comment;
962 }
963
964 /**
965 * Wrap a comment in standard punctuation and formatting if
966 * it's non-empty, otherwise return empty string.
967 *
968 * @param $comment String: the comment.
969 * @param $title Title object.
970 *
971 * @return string
972 */
973 function commentBlock( $comment, $title = NULL ) {
974 // '*' used to be the comment inserted by the software way back
975 // in antiquity in case none was provided, here for backwards
976 // compatability, acc. to brion -ævar
977 if( $comment == '' || $comment == '*' ) {
978 return '';
979 } else {
980 $formatted = $this->formatComment( $comment, $title );
981 return " <span class=\"comment\">($formatted)</span>";
982 }
983 }
984
985 /**
986 * Wrap and format the given revision's comment block, if the current
987 * user is allowed to view it.
988 * @param $rev Revision object.
989 * @return string HTML
990 */
991 function revComment( $rev ) {
992 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
993 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle() );
994 } else {
995 $block = " <span class=\"comment\">" .
996 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
997 }
998 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
999 return " <span class=\"history-deleted\">$block</span>";
1000 }
1001 return $block;
1002 }
1003
1004 /** @todo document */
1005 function tocIndent() {
1006 return "\n<ul>";
1007 }
1008
1009 /** @todo document */
1010 function tocUnindent($level) {
1011 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1012 }
1013
1014 /**
1015 * parameter level defines if we are on an indentation level
1016 */
1017 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1018 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1019 $anchor . '"><span class="tocnumber">' .
1020 $tocnumber . '</span> <span class="toctext">' .
1021 $tocline . '</span></a>';
1022 }
1023
1024 /** @todo document */
1025 function tocLineEnd() {
1026 return "</li>\n";
1027 }
1028
1029 /** @todo document */
1030 function tocList($toc) {
1031 global $wgJsMimeType;
1032 $title = wfMsgForContent('toc') ;
1033 return
1034 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1035 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1036 . $toc
1037 # no trailing newline, script should not be wrapped in a
1038 # paragraph
1039 . "</ul>\n</td></tr></table>"
1040 . '<script type="' . $wgJsMimeType . '">'
1041 . ' if (window.showTocToggle) {'
1042 . ' var tocShowText = "' . wfEscapeJsString( wfMsgForContent('showtoc') ) . '";'
1043 . ' var tocHideText = "' . wfEscapeJsString( wfMsgForContent('hidetoc') ) . '";'
1044 . ' showTocToggle();'
1045 . ' } '
1046 . "</script>\n";
1047 }
1048
1049 /** @todo document */
1050 function editSectionLinkForOther( $title, $section ) {
1051 global $wgContLang;
1052
1053 $title = Title::newFromText( $title );
1054 $editurl = '&section='.$section;
1055 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1056
1057 return "<span class=\"editsection\">[".$url."]</span>";
1058
1059 }
1060
1061 /**
1062 * @param $title Title object.
1063 * @param $section Integer: section number.
1064 * @param $hint Link String: title, or default if omitted or empty
1065 */
1066 function editSectionLink( $nt, $section, $hint='' ) {
1067 global $wgContLang;
1068
1069 $editurl = '&section='.$section;
1070 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1071 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1072
1073 return "<span class=\"editsection\">[".$url."]</span>";
1074 }
1075
1076 /**
1077 * Split a link trail, return the "inside" portion and the remainder of the trail
1078 * as a two-element array
1079 *
1080 * @static
1081 */
1082 static function splitTrail( $trail ) {
1083 static $regex = false;
1084 if ( $regex === false ) {
1085 global $wgContLang;
1086 $regex = $wgContLang->linkTrail();
1087 }
1088 $inside = '';
1089 if ( '' != $trail ) {
1090 if ( preg_match( $regex, $trail, $m ) ) {
1091 $inside = $m[1];
1092 $trail = $m[2];
1093 }
1094 }
1095 return array( $inside, $trail );
1096 }
1097
1098 /**
1099 * Generate a rollback link for a given revision. Currently it's the
1100 * caller's responsibility to ensure that the revision is the top one. If
1101 * it's not, of course, the user will get an error message.
1102 *
1103 * If the calling page is called with the parameter &bot=1, all rollback
1104 * links also get that parameter. It causes the edit itself and the rollback
1105 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1106 * changes, so this allows sysops to combat a busy vandal without bothering
1107 * other users.
1108 *
1109 * @param Revision $rev
1110 */
1111 function generateRollback( $rev ) {
1112 global $wgUser, $wgRequest;
1113 $title = $rev->getTitle();
1114
1115 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1116 $extraRollback .= '&token=' . urlencode(
1117 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1118 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1119 wfMsg('rollbacklink'),
1120 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1121 }
1122
1123 /**
1124 * Returns HTML for the "templates used on this page" list.
1125 *
1126 * @param array $templates Array of templates from Article::getUsedTemplate
1127 * or similar
1128 * @return string HTML output
1129 */
1130 public function formatTemplates($templates) {
1131 global $wgUser;
1132 wfProfileIn( __METHOD__ );
1133
1134 $sk =& $wgUser->getSkin();
1135
1136 $outText = '';
1137 if ( count( $templates ) > 0 ) {
1138 # Do a batch existence check
1139 $batch = new LinkBatch;
1140 foreach( $templates as $title ) {
1141 $batch->addObj( $title );
1142 }
1143 $batch->execute();
1144
1145 # Construct the HTML
1146 $outText = '<div class="mw-templatesUsedExplanation">' .
1147 wfMsgExt( 'templatesused', array( 'parse' ) ) .
1148 '</div><ul>';
1149 foreach ( $templates as $titleObj ) {
1150 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1151 }
1152 $outText .= '</ul>';
1153 }
1154 wfProfileOut( __METHOD__ );
1155 return $outText;
1156 }
1157 }
1158 ?>