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