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