API * Minor fixes to user contribs and logevents. Paging is still broken.
[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 = '', $page = null )
460 {
461 global $wgContLang, $wgUser, $wgThumbLimits, $wgGenerateThumbnailOnParse;
462
463 $img = new Image( $nt );
464
465 if ( ! is_null( $page ) ) {
466 $img->selectPage( $page );
467 }
468
469 if ( !$img->allowInlineDisplay() && $img->exists() ) {
470 return $this->makeKnownLinkObj( $nt );
471 }
472
473 $url = $img->getViewURL();
474 $error = $prefix = $postfix = '';
475
476 wfDebug( "makeImageLinkObj: '$width'x'$height', \"$label\"\n" );
477
478 if ( 'center' == $align )
479 {
480 $prefix = '<div class="center">';
481 $postfix = '</div>';
482 $align = 'none';
483 }
484
485 if ( $thumb || $framed ) {
486
487 # Create a thumbnail. Alignment depends on language
488 # writing direction, # right aligned for left-to-right-
489 # languages ("Western languages"), left-aligned
490 # for right-to-left-languages ("Semitic languages")
491 #
492 # If thumbnail width has not been provided, it is set
493 # to the default user option as specified in Language*.php
494 if ( $align == '' ) {
495 $align = $wgContLang->isRTL() ? 'left' : 'right';
496 }
497
498
499 if ( $width === false ) {
500 $wopt = $wgUser->getOption( 'thumbsize' );
501
502 if( !isset( $wgThumbLimits[$wopt] ) ) {
503 $wopt = User::getDefaultOption( 'thumbsize' );
504 }
505
506 $width = min( $img->getWidth(), $wgThumbLimits[$wopt] );
507 }
508
509 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $width, $height, $framed, $manual_thumb ).$postfix;
510 }
511
512 if ( $width && $img->exists() ) {
513
514 # Create a resized image, without the additional thumbnail
515 # features
516
517 if ( $height == false )
518 $height = -1;
519 if ( $manual_thumb == '') {
520 $thumb = $img->getThumbnail( $width, $height, $wgGenerateThumbnailOnParse );
521 if ( $thumb ) {
522 // In most cases, $width = $thumb->width or $height = $thumb->height.
523 // If not, we're scaling the image larger than it can be scaled,
524 // so we send to the browser a smaller thumbnail, and let the client do the scaling.
525
526 if ($height != -1 && $width > $thumb->width * $height / $thumb->height) {
527 // $height is the limiting factor, not $width
528 // set $width to the largest it can be, such that the resulting
529 // scaled height is at most $height
530 $width = floor($thumb->width * $height / $thumb->height);
531 }
532 $height = round($thumb->height * $width / $thumb->width);
533
534 wfDebug( "makeImageLinkObj: client-size set to '$width x $height'\n" );
535 $url = $thumb->getUrl();
536 } else {
537 $error = htmlspecialchars( $img->getLastError() );
538 }
539 }
540 } else {
541 $width = $img->width;
542 $height = $img->height;
543 }
544
545 wfDebug( "makeImageLinkObj2: '$width'x'$height'\n" );
546 $u = $nt->escapeLocalURL();
547 if ( $error ) {
548 $s = $error;
549 } elseif ( $url == '' ) {
550 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
551 //$s .= "<br />{$alt}<br />{$url}<br />\n";
552 } else {
553 $s = '<a href="'.$u.'" class="image" title="'.$alt.'">' .
554 '<img src="'.$url.'" alt="'.$alt.'" ' .
555 ( $width
556 ? ( 'width="'.$width.'" height="'.$height.'" ' )
557 : '' ) .
558 'longdesc="'.$u.'" /></a>';
559 }
560 if ( '' != $align ) {
561 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
562 }
563 return str_replace("\n", ' ',$prefix.$s.$postfix);
564 }
565
566 /**
567 * Make HTML for a thumbnail including image, border and caption
568 * $img is an Image object
569 */
570 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $boxwidth = 180, $boxheight=false, $framed=false , $manual_thumb = "" ) {
571 global $wgStylePath, $wgContLang, $wgGenerateThumbnailOnParse;
572 $thumbUrl = '';
573 $error = '';
574
575 $width = $height = 0;
576 if ( $img->exists() ) {
577 $width = $img->getWidth();
578 $height = $img->getHeight();
579 }
580 if ( 0 == $width || 0 == $height ) {
581 $width = $height = 180;
582 }
583 if ( $boxwidth == 0 ) {
584 $boxwidth = 180;
585 }
586 if ( $framed ) {
587 // Use image dimensions, don't scale
588 $boxwidth = $width;
589 $boxheight = $height;
590 $thumbUrl = $img->getViewURL();
591 } else {
592 if ( $boxheight === false )
593 $boxheight = -1;
594 if ( '' == $manual_thumb ) {
595 $thumb = $img->getThumbnail( $boxwidth, $boxheight, $wgGenerateThumbnailOnParse );
596 if ( $thumb ) {
597 $thumbUrl = $thumb->getUrl();
598 $boxwidth = $thumb->width;
599 $boxheight = $thumb->height;
600 } else {
601 $error = $img->getLastError();
602 }
603 }
604 }
605 $oboxwidth = $boxwidth + 2;
606
607 if ( $manual_thumb != '' ) # Use manually specified thumbnail
608 {
609 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb ); #new Title ( $manual_thumb ) ;
610 if( $manual_title ) {
611 $manual_img = new Image( $manual_title );
612 $thumbUrl = $manual_img->getViewURL();
613 if ( $manual_img->exists() )
614 {
615 $width = $manual_img->getWidth();
616 $height = $manual_img->getHeight();
617 $boxwidth = $width ;
618 $boxheight = $height ;
619 $oboxwidth = $boxwidth + 2 ;
620 }
621 }
622 }
623
624 $u = $img->getEscapeLocalURL();
625
626 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
627 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
628 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
629
630 $s = "<div class=\"thumb t{$align}\"><div style=\"width:{$oboxwidth}px;\">";
631 if( $thumbUrl == '' ) {
632 // Couldn't generate thumbnail? Scale the image client-side.
633 $thumbUrl = $img->getViewURL();
634 }
635 if ( $error ) {
636 $s .= htmlspecialchars( $error );
637 $zoomicon = '';
638 } elseif( !$img->exists() ) {
639 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
640 $zoomicon = '';
641 } else {
642 $s .= '<a href="'.$u.'" class="internal" title="'.$alt.'">'.
643 '<img src="'.$thumbUrl.'" alt="'.$alt.'" ' .
644 'width="'.$boxwidth.'" height="'.$boxheight.'" ' .
645 'longdesc="'.$u.'" /></a>';
646 if ( $framed ) {
647 $zoomicon="";
648 } else {
649 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
650 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
651 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
652 'width="15" height="11" alt="'.$more.'" /></a></div>';
653 }
654 }
655 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
656 return str_replace("\n", ' ', $s);
657 }
658
659 /**
660 * Pass a title object, not a title string
661 */
662 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
663 # Fail gracefully
664 if ( ! isset($nt) ) {
665 # throw new MWException();
666 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
667 }
668
669 $fname = 'Linker::makeBrokenImageLinkObj';
670 wfProfileIn( $fname );
671
672 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
673 if ( '' != $query ) {
674 $q .= "&$query";
675 }
676 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
677 $url = $uploadTitle->escapeLocalURL( $q );
678
679 if ( '' == $text ) {
680 $text = htmlspecialchars( $nt->getPrefixedText() );
681 }
682 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
683 list( $inside, $trail ) = Linker::splitTrail( $trail );
684 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
685
686 wfProfileOut( $fname );
687 return $s;
688 }
689
690 /** @todo document */
691 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
692 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
693 return $this->makeMediaLinkObj( $nt, $alt );
694 }
695
696 /**
697 * Create a direct link to a given uploaded file.
698 *
699 * @param $title Title object.
700 * @param $text String: pre-sanitized HTML
701 * @param $nourl Boolean: Mask absolute URLs, so the parser doesn't
702 * linkify them (it is currently not context-aware)
703 * @return string HTML
704 *
705 * @public
706 * @todo Handle invalid or missing images better.
707 */
708 function makeMediaLinkObj( $title, $text = '' ) {
709 if( is_null( $title ) ) {
710 ### HOTFIX. Instead of breaking, return empty string.
711 return $text;
712 } else {
713 $name = $title->getDBKey();
714 $img = new Image( $title );
715 if( $img->exists() ) {
716 $url = $img->getURL();
717 $class = 'internal';
718 } else {
719 $upload = SpecialPage::getTitleFor( 'Upload' );
720 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
721 $class = 'new';
722 }
723 $alt = htmlspecialchars( $title->getText() );
724 if( $text == '' ) {
725 $text = $alt;
726 }
727 $u = htmlspecialchars( $url );
728 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
729 }
730 }
731
732 /** @todo document */
733 function specialLink( $name, $key = '' ) {
734 global $wgContLang;
735
736 if ( '' == $key ) { $key = strtolower( $name ); }
737 $pn = $wgContLang->ucfirst( $name );
738 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
739 wfMsg( $key ) );
740 }
741
742 /** @todo document */
743 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
744 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
745 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
746 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
747 $style .= ' rel="nofollow"';
748 }
749 $url = htmlspecialchars( $url );
750 if( $escape ) {
751 $text = htmlspecialchars( $text );
752 }
753 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
754 }
755
756 /**
757 * Make user link (or user contributions for unregistered users)
758 * @param $userId Integer: user id in database.
759 * @param $userText String: user name in database
760 * @return string HTML fragment
761 * @private
762 */
763 function userLink( $userId, $userText ) {
764 $encName = htmlspecialchars( $userText );
765 if( $userId == 0 ) {
766 $contribsPage = SpecialPage::getTitleFor( 'Contributions' );
767 return $this->makeKnownLinkObj( $contribsPage,
768 $encName, 'target=' . urlencode( $userText ) );
769 } else {
770 $userPage = Title::makeTitle( NS_USER, $userText );
771 return $this->makeLinkObj( $userPage, $encName );
772 }
773 }
774
775 /**
776 * @param $userId Integer: user id in database.
777 * @param $userText String: user name in database.
778 * @return string HTML fragment with talk and/or block links
779 * @private
780 */
781 function userToolLinks( $userId, $userText ) {
782 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
783 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
784 $blockable = ( $wgSysopUserBans || 0 == $userId );
785
786 $items = array();
787 if( $talkable ) {
788 $items[] = $this->userTalkLink( $userId, $userText );
789 }
790 if( $userId ) {
791 $contribsPage = SpecialPage::getTitleFor( 'Contributions' );
792 $items[] = $this->makeKnownLinkObj( $contribsPage,
793 wfMsgHtml( 'contribslink' ), 'target=' . urlencode( $userText ) );
794 }
795 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
796 $items[] = $this->blockLink( $userId, $userText );
797 }
798
799 if( $items ) {
800 return ' (' . implode( ' | ', $items ) . ')';
801 } else {
802 return '';
803 }
804 }
805
806 /**
807 * @param $userId Integer: user id in database.
808 * @param $userText String: user name in database.
809 * @return string HTML fragment with user talk link
810 * @private
811 */
812 function userTalkLink( $userId, $userText ) {
813 global $wgLang;
814 $talkname = $wgLang->getNsText( NS_TALK ); # use the shorter name
815
816 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
817 $userTalkLink = $this->makeLinkObj( $userTalkPage, $talkname );
818 return $userTalkLink;
819 }
820
821 /**
822 * @param $userId Integer: userid
823 * @param $userText String: user name in database.
824 * @return string HTML fragment with block link
825 * @private
826 */
827 function blockLink( $userId, $userText ) {
828 $blockPage = SpecialPage::getTitleFor( 'Blockip' );
829 $blockLink = $this->makeKnownLinkObj( $blockPage,
830 wfMsgHtml( 'blocklink' ), 'ip=' . urlencode( $userText ) );
831 return $blockLink;
832 }
833
834 /**
835 * Generate a user link if the current user is allowed to view it
836 * @param $rev Revision object.
837 * @return string HTML
838 */
839 function revUserLink( $rev ) {
840 if( $rev->userCan( Revision::DELETED_USER ) ) {
841 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
842 } else {
843 $link = wfMsgHtml( 'rev-deleted-user' );
844 }
845 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
846 return '<span class="history-deleted">' . $link . '</span>';
847 }
848 return $link;
849 }
850
851 /**
852 * Generate a user tool link cluster if the current user is allowed to view it
853 * @param $rev Revision object.
854 * @return string HTML
855 */
856 function revUserTools( $rev ) {
857 if( $rev->userCan( Revision::DELETED_USER ) ) {
858 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
859 ' ' .
860 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
861 } else {
862 $link = wfMsgHtml( 'rev-deleted-user' );
863 }
864 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
865 return '<span class="history-deleted">' . $link . '</span>';
866 }
867 return $link;
868 }
869
870 /**
871 * This function is called by all recent changes variants, by the page history,
872 * and by the user contributions list. It is responsible for formatting edit
873 * comments. It escapes any HTML in the comment, but adds some CSS to format
874 * auto-generated comments (from section editing) and formats [[wikilinks]].
875 *
876 * The $title parameter must be a title OBJECT. It is used to generate a
877 * direct link to the section in the autocomment.
878 * @author Erik Moeller <moeller@scireview.de>
879 *
880 * Note: there's not always a title to pass to this function.
881 * Since you can't set a default parameter for a reference, I've turned it
882 * temporarily to a value pass. Should be adjusted further. --brion
883 */
884 function formatComment($comment, $title = NULL) {
885 $fname = 'Linker::formatComment';
886 wfProfileIn( $fname );
887
888 global $wgContLang;
889 $comment = str_replace( "\n", " ", $comment );
890 $comment = htmlspecialchars( $comment );
891
892 # The pattern for autogen comments is / * foo * /, which makes for
893 # some nasty regex.
894 # We look for all comments, match any text before and after the comment,
895 # add a separator where needed and format the comment itself with CSS
896 while (preg_match('/(.*)\/\*\s*(.*?)\s*\*\/(.*)/', $comment,$match)) {
897 $pre=$match[1];
898 $auto=$match[2];
899 $post=$match[3];
900 $link='';
901 if( $title ) {
902 $section = $auto;
903
904 # Generate a valid anchor name from the section title.
905 # Hackish, but should generally work - we strip wiki
906 # syntax, including the magic [[: that is used to
907 # "link rather than show" in case of images and
908 # interlanguage links.
909 $section = str_replace( '[[:', '', $section );
910 $section = str_replace( '[[', '', $section );
911 $section = str_replace( ']]', '', $section );
912 $sectionTitle = wfClone( $title );
913 $sectionTitle->mFragment = $section;
914 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
915 }
916 $sep='-';
917 $auto=$link.$auto;
918 if($pre) { $auto = $sep.' '.$auto; }
919 if($post) { $auto .= ' '.$sep; }
920 $auto='<span class="autocomment">'.$auto.'</span>';
921 $comment=$pre.$auto.$post;
922 }
923
924 # format regular and media links - all other wiki formatting
925 # is ignored
926 $medians = $wgContLang->getNsText( NS_MEDIA ) . ':';
927 while(preg_match('/\[\[(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
928 # Handle link renaming [[foo|text]] will show link as "text"
929 if( "" != $match[3] ) {
930 $text = $match[3];
931 } else {
932 $text = $match[1];
933 }
934 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
935 # Media link; trail not supported.
936 $linkRegexp = '/\[\[(.*?)\]\]/';
937 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
938 } else {
939 # Other kind of link
940 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
941 $trail = $submatch[1];
942 } else {
943 $trail = "";
944 }
945 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
946 if ($match[1][0] == ':')
947 $match[1] = substr($match[1], 1);
948 $thelink = $this->makeLink( $match[1], $text, "", $trail );
949 }
950 $comment = preg_replace( $linkRegexp, wfRegexReplacement( $thelink ), $comment, 1 );
951 }
952 wfProfileOut( $fname );
953 return $comment;
954 }
955
956 /**
957 * Wrap a comment in standard punctuation and formatting if
958 * it's non-empty, otherwise return empty string.
959 *
960 * @param $comment String: the comment.
961 * @param $title Title object.
962 *
963 * @return string
964 */
965 function commentBlock( $comment, $title = NULL ) {
966 // '*' used to be the comment inserted by the software way back
967 // in antiquity in case none was provided, here for backwards
968 // compatability, acc. to brion -ævar
969 if( $comment == '' || $comment == '*' ) {
970 return '';
971 } else {
972 $formatted = $this->formatComment( $comment, $title );
973 return " <span class=\"comment\">($formatted)</span>";
974 }
975 }
976
977 /**
978 * Wrap and format the given revision's comment block, if the current
979 * user is allowed to view it.
980 * @param $rev Revision object.
981 * @return string HTML
982 */
983 function revComment( $rev ) {
984 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
985 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle() );
986 } else {
987 $block = " <span class=\"comment\">" .
988 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
989 }
990 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
991 return " <span class=\"history-deleted\">$block</span>";
992 }
993 return $block;
994 }
995
996 /** @todo document */
997 function tocIndent() {
998 return "\n<ul>";
999 }
1000
1001 /** @todo document */
1002 function tocUnindent($level) {
1003 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1004 }
1005
1006 /**
1007 * parameter level defines if we are on an indentation level
1008 */
1009 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1010 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1011 $anchor . '"><span class="tocnumber">' .
1012 $tocnumber . '</span> <span class="toctext">' .
1013 $tocline . '</span></a>';
1014 }
1015
1016 /** @todo document */
1017 function tocLineEnd() {
1018 return "</li>\n";
1019 }
1020
1021 /** @todo document */
1022 function tocList($toc) {
1023 global $wgJsMimeType;
1024 $title = wfMsgForContent('toc') ;
1025 return
1026 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1027 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1028 . $toc
1029 # no trailing newline, script should not be wrapped in a
1030 # paragraph
1031 . "</ul>\n</td></tr></table>"
1032 . '<script type="' . $wgJsMimeType . '">'
1033 . ' if (window.showTocToggle) {'
1034 . ' var tocShowText = "' . wfEscapeJsString( wfMsgForContent('showtoc') ) . '";'
1035 . ' var tocHideText = "' . wfEscapeJsString( wfMsgForContent('hidetoc') ) . '";'
1036 . ' showTocToggle();'
1037 . ' } '
1038 . "</script>\n";
1039 }
1040
1041 /** @todo document */
1042 function editSectionLinkForOther( $title, $section ) {
1043 global $wgContLang;
1044
1045 $title = Title::newFromText( $title );
1046 $editurl = '&section='.$section;
1047 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1048
1049 return "<span class=\"editsection\">[".$url."]</span>";
1050
1051 }
1052
1053 /**
1054 * @param $title Title object.
1055 * @param $section Integer: section number.
1056 * @param $hint Link String: title, or default if omitted or empty
1057 */
1058 function editSectionLink( $nt, $section, $hint='' ) {
1059 global $wgContLang;
1060
1061 $editurl = '&section='.$section;
1062 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1063 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1064
1065 return "<span class=\"editsection\">[".$url."]</span>";
1066 }
1067
1068 /**
1069 * Split a link trail, return the "inside" portion and the remainder of the trail
1070 * as a two-element array
1071 *
1072 * @static
1073 */
1074 static function splitTrail( $trail ) {
1075 static $regex = false;
1076 if ( $regex === false ) {
1077 global $wgContLang;
1078 $regex = $wgContLang->linkTrail();
1079 }
1080 $inside = '';
1081 if ( '' != $trail ) {
1082 if ( preg_match( $regex, $trail, $m ) ) {
1083 $inside = $m[1];
1084 $trail = $m[2];
1085 }
1086 }
1087 return array( $inside, $trail );
1088 }
1089
1090 }
1091 ?>