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