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