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