Made User::edits() use user_editcounts. If it has not been initialized, do so.
[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 function Linker() {}
20
21 /**
22 * @deprecated
23 */
24 function postParseLinkColour( $s = NULL ) {
25 return NULL;
26 }
27
28 /** @todo document */
29 function getExternalLinkAttributes( $link, $text, $class='' ) {
30 $link = htmlspecialchars( $link );
31
32 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
33
34 $r .= " title=\"{$link}\"";
35 return $r;
36 }
37
38 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
39 global $wgContLang;
40
41 $link = urldecode( $link );
42 $link = $wgContLang->checkTitleEncoding( $link );
43 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
44 $link = htmlspecialchars( $link );
45
46 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
47
48 $r .= " title=\"{$link}\"";
49 return $r;
50 }
51
52 /** @todo document */
53 function getInternalLinkAttributes( $link, $text, $broken = false ) {
54 $link = urldecode( $link );
55 $link = str_replace( '_', ' ', $link );
56 $link = htmlspecialchars( $link );
57
58 if( $broken == 'stub' ) {
59 $r = ' class="stub"';
60 } else if ( $broken == 'yes' ) {
61 $r = ' class="new"';
62 } else {
63 $r = '';
64 }
65
66 $r .= " title=\"{$link}\"";
67 return $r;
68 }
69
70 /**
71 * @param $nt Title object.
72 * @param $text String: FIXME
73 * @param $broken Boolean: FIXME, default 'false'.
74 */
75 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
76 if( $broken == 'stub' ) {
77 $r = ' class="stub"';
78 } else if ( $broken == 'yes' ) {
79 $r = ' class="new"';
80 } else {
81 $r = '';
82 }
83
84 $r .= ' title="' . $nt->getEscapedText() . '"';
85 return $r;
86 }
87
88 /**
89 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
90 * it if you already have a title object handy. See makeLinkObj for further documentation.
91 *
92 * @param $title String: the text of the title
93 * @param $text String: link text
94 * @param $query String: optional query part
95 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
96 * be included in the link text. Other characters will be appended after
97 * the end of the link.
98 */
99 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
100 wfProfileIn( 'Linker::makeLink' );
101 $nt = Title::newFromText( $title );
102 if ($nt) {
103 $result = $this->makeLinkObj( Title::newFromText( $title ), $text, $query, $trail );
104 } else {
105 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
106 $result = $text == "" ? $title : $text;
107 }
108
109 wfProfileOut( 'Linker::makeLink' );
110 return $result;
111 }
112
113 /**
114 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
115 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
116 *
117 * @param $title String: the text of the title
118 * @param $text String: link text
119 * @param $query String: optional query part
120 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
121 * be included in the link text. Other characters will be appended after
122 * the end of the link.
123 */
124 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
125 $nt = Title::newFromText( $title );
126 if ($nt) {
127 return $this->makeKnownLinkObj( Title::newFromText( $title ), $text, $query, $trail, $prefix , $aprops );
128 } else {
129 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
130 return $text == '' ? $title : $text;
131 }
132 }
133
134 /**
135 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
136 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
137 *
138 * @param string $title The text of the title
139 * @param string $text Link text
140 * @param string $query Optional query part
141 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
142 * be included in the link text. Other characters will be appended after
143 * the end of the link.
144 */
145 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
146 $nt = Title::newFromText( $title );
147 if ($nt) {
148 return $this->makeBrokenLinkObj( Title::newFromText( $title ), $text, $query, $trail );
149 } else {
150 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
151 return $text == '' ? $title : $text;
152 }
153 }
154
155 /**
156 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
157 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
158 *
159 * @param $title String: the text of the title
160 * @param $text String: link text
161 * @param $query String: optional query part
162 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
163 * be included in the link text. Other characters will be appended after
164 * the end of the link.
165 */
166 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
167 $nt = Title::newFromText( $title );
168 if ($nt) {
169 return $this->makeStubLinkObj( Title::newFromText( $title ), $text, $query, $trail );
170 } else {
171 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
172 return $text == '' ? $title : $text;
173 }
174 }
175
176 /**
177 * Make a link for a title which may or may not be in the database. If you need to
178 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
179 * call to this will result in a DB query.
180 *
181 * @param $nt Title: the title object to make the link from, e.g. from
182 * Title::newFromText.
183 * @param $text String: link text
184 * @param $query String: optional query part
185 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
186 * be included in the link text. Other characters will be appended after
187 * the end of the link.
188 * @param $prefix String: optional prefix. As trail, only before instead of after.
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 if ( $nt->isExternal() ) {
203 $u = $nt->getFullURL();
204 $link = $nt->getPrefixedURL();
205 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
206 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
207
208 $inside = '';
209 if ( '' != $trail ) {
210 $m = array();
211 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
212 $inside = $m[1];
213 $trail = $m[2];
214 }
215 }
216 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
217
218 wfProfileOut( $fname );
219 return $t;
220 } elseif ( $nt->isAlwaysKnown() ) {
221 # Image links, special page links and self-links with fragements are always known.
222 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
223 } else {
224 wfProfileIn( $fname.'-immediate' );
225 # Work out link colour immediately
226 $aid = $nt->getArticleID() ;
227 if ( 0 == $aid ) {
228 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
229 } else {
230 $threshold = $wgUser->getOption('stubthreshold') ;
231 if ( $threshold > 0 ) {
232 $dbr =& wfGetDB( DB_SLAVE );
233 $s = $dbr->selectRow(
234 array( 'page' ),
235 array( 'page_len',
236 'page_namespace',
237 'page_is_redirect' ),
238 array( 'page_id' => $aid ), $fname ) ;
239 if ( $s !== false ) {
240 $size = $s->page_len;
241 if ( $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
242 $size = $threshold*2 ; # Really big
243 }
244 } else {
245 $size = $threshold*2 ; # Really big
246 }
247 } else {
248 $size = 1 ;
249 }
250 if ( $size < $threshold ) {
251 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
252 } else {
253 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
254 }
255 }
256 wfProfileOut( $fname.'-immediate' );
257 }
258 wfProfileOut( $fname );
259 return $retVal;
260 }
261
262 /**
263 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
264 * it doesn't have to do a database query. It's also valid for interwiki titles and special
265 * pages.
266 *
267 * @param $nt Title object of target page
268 * @param $text String: text to replace the title
269 * @param $query String: link target
270 * @param $trail String: text after link
271 * @param $prefix String: text before link text
272 * @param $aprops String: extra attributes to the a-element
273 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
274 * @return the a-element
275 */
276 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
277
278 $fname = 'Linker::makeKnownLinkObj';
279 wfProfileIn( $fname );
280
281 if ( !is_object( $nt ) ) {
282 wfProfileOut( $fname );
283 return $text;
284 }
285
286 $u = $nt->escapeLocalURL( $query );
287 if ( $nt->getFragment() != '' ) {
288 if( $nt->getPrefixedDbkey() == '' ) {
289 $u = '';
290 if ( '' == $text ) {
291 $text = htmlspecialchars( $nt->getFragment() );
292 }
293 }
294 $u .= $nt->getFragmentForURL();
295 }
296 if ( $text == '' ) {
297 $text = htmlspecialchars( $nt->getPrefixedText() );
298 }
299 if ( $style == '' ) {
300 $style = $this->getInternalLinkAttributesObj( $nt, $text );
301 }
302
303 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
304
305 list( $inside, $trail ) = Linker::splitTrail( $trail );
306 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
307 wfProfileOut( $fname );
308 return $r;
309 }
310
311 /**
312 * Make a red link to the edit page of a given title.
313 *
314 * @param $title String: The text of the title
315 * @param $text String: Link text
316 * @param $query String: Optional query part
317 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
318 * be included in the link text. Other characters will be appended after
319 * the end of the link.
320 */
321 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
322 # Fail gracefully
323 if ( ! isset($nt) ) {
324 # throw new MWException();
325 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
326 }
327
328 $fname = 'Linker::makeBrokenLinkObj';
329 wfProfileIn( $fname );
330
331 if ( '' == $query ) {
332 $q = 'action=edit';
333 } else {
334 $q = 'action=edit&'.$query;
335 }
336 $u = $nt->escapeLocalURL( $q );
337
338 if ( '' == $text ) {
339 $text = htmlspecialchars( $nt->getPrefixedText() );
340 }
341 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
342
343 list( $inside, $trail ) = Linker::splitTrail( $trail );
344 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
345
346 wfProfileOut( $fname );
347 return $s;
348 }
349
350 /**
351 * Make a brown link to a short article.
352 *
353 * @param $title String: the text of the title
354 * @param $text String: link text
355 * @param $query String: optional query part
356 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
357 * be included in the link text. Other characters will be appended after
358 * the end of the link.
359 */
360 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
361 $u = $nt->escapeLocalURL( $query );
362
363 if ( '' == $text ) {
364 $text = htmlspecialchars( $nt->getPrefixedText() );
365 }
366 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
367
368 list( $inside, $trail ) = Linker::splitTrail( $trail );
369 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
370 return $s;
371 }
372
373 /**
374 * Generate either a normal exists-style link or a stub link, depending
375 * on the given page size.
376 *
377 * @param $size Integer
378 * @param $nt Title object.
379 * @param $text String
380 * @param $query String
381 * @param $trail String
382 * @param $prefix String
383 * @return string HTML of link
384 */
385 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
386 global $wgUser;
387 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
388 if( $size < $threshold ) {
389 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
390 } else {
391 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
392 }
393 }
394
395 /**
396 * Make appropriate markup for a link to the current article. This is currently rendered
397 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
398 * despite $query not being used.
399 */
400 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
401 if ( '' == $text ) {
402 $text = htmlspecialchars( $nt->getPrefixedText() );
403 }
404 list( $inside, $trail ) = Linker::splitTrail( $trail );
405 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
406 }
407
408 /** @todo document */
409 function fnamePart( $url ) {
410 $basename = strrchr( $url, '/' );
411 if ( false === $basename ) {
412 $basename = $url;
413 } else {
414 $basename = substr( $basename, 1 );
415 }
416 return htmlspecialchars( $basename );
417 }
418
419 /** Obsolete alias */
420 function makeImage( $url, $alt = '' ) {
421 return $this->makeExternalImage( $url, $alt );
422 }
423
424 /** @todo document */
425 function makeExternalImage( $url, $alt = '' ) {
426 if ( '' == $alt ) {
427 $alt = $this->fnamePart( $url );
428 }
429 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
430 return $s;
431 }
432
433 /** @todo document */
434 function makeImageLinkObj( $nt, $label, $alt, $align = '', $width = false, $height = false, $framed = false,
435 $thumb = false, $manual_thumb = '', $page = null )
436 {
437 global $wgContLang, $wgUser, $wgThumbLimits, $wgGenerateThumbnailOnParse;
438
439 $img = new Image( $nt );
440
441 if ( ! is_null( $page ) ) {
442 $img->selectPage( $page );
443 }
444
445 if ( !$img->allowInlineDisplay() && $img->exists() ) {
446 return $this->makeKnownLinkObj( $nt );
447 }
448
449 $url = $img->getViewURL();
450 $error = $prefix = $postfix = '';
451
452 wfDebug( "makeImageLinkObj: '$width'x'$height', \"$label\"\n" );
453
454 if ( 'center' == $align )
455 {
456 $prefix = '<div class="center">';
457 $postfix = '</div>';
458 $align = 'none';
459 }
460
461 if ( $thumb || $framed ) {
462
463 # Create a thumbnail. Alignment depends on language
464 # writing direction, # right aligned for left-to-right-
465 # languages ("Western languages"), left-aligned
466 # for right-to-left-languages ("Semitic languages")
467 #
468 # If thumbnail width has not been provided, it is set
469 # to the default user option as specified in Language*.php
470 if ( $align == '' ) {
471 $align = $wgContLang->isRTL() ? 'left' : 'right';
472 }
473
474
475 if ( $width === false ) {
476 $wopt = $wgUser->getOption( 'thumbsize' );
477
478 if( !isset( $wgThumbLimits[$wopt] ) ) {
479 $wopt = User::getDefaultOption( 'thumbsize' );
480 }
481
482 $width = min( $img->getWidth(), $wgThumbLimits[$wopt] );
483 }
484
485 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $width, $height, $framed, $manual_thumb ).$postfix;
486 }
487
488 if ( $width && $img->exists() ) {
489
490 # Create a resized image, without the additional thumbnail
491 # features
492
493 if ( $height == false )
494 $height = -1;
495 if ( $manual_thumb == '') {
496 $thumb = $img->getThumbnail( $width, $height, $wgGenerateThumbnailOnParse );
497 if ( $thumb ) {
498 // In most cases, $width = $thumb->width or $height = $thumb->height.
499 // If not, we're scaling the image larger than it can be scaled,
500 // so we send to the browser a smaller thumbnail, and let the client do the scaling.
501
502 if ($height != -1 && $width > $thumb->width * $height / $thumb->height) {
503 // $height is the limiting factor, not $width
504 // set $width to the largest it can be, such that the resulting
505 // scaled height is at most $height
506 $width = floor($thumb->width * $height / $thumb->height);
507 }
508 $height = round($thumb->height * $width / $thumb->width);
509
510 wfDebug( "makeImageLinkObj: client-size set to '$width x $height'\n" );
511 $url = $thumb->getUrl();
512 } else {
513 $error = htmlspecialchars( $img->getLastError() );
514 // Do client-side scaling...
515 $height = intval( $img->getHeight() * $width / $img->getWidth() );
516 }
517 }
518 } else {
519 $width = $img->width;
520 $height = $img->height;
521 }
522
523 wfDebug( "makeImageLinkObj2: '$width'x'$height'\n" );
524 $u = $nt->escapeLocalURL();
525 if ( $error ) {
526 $s = $error;
527 } elseif ( $url == '' ) {
528 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
529 //$s .= "<br />{$alt}<br />{$url}<br />\n";
530 } else {
531 $s = '<a href="'.$u.'" class="image" title="'.$alt.'">' .
532 '<img src="'.$url.'" alt="'.$alt.'" ' .
533 ( $width
534 ? ( 'width="'.$width.'" height="'.$height.'" ' )
535 : '' ) .
536 'longdesc="'.$u.'" /></a>';
537 }
538 if ( '' != $align ) {
539 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
540 }
541 return str_replace("\n", ' ',$prefix.$s.$postfix);
542 }
543
544 /**
545 * Make HTML for a thumbnail including image, border and caption
546 * $img is an Image object
547 */
548 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $boxwidth = 180, $boxheight=false, $framed=false , $manual_thumb = "" ) {
549 global $wgStylePath, $wgContLang, $wgGenerateThumbnailOnParse;
550 $thumbUrl = '';
551 $error = '';
552
553 $width = $height = 0;
554 if ( $img->exists() ) {
555 $width = $img->getWidth();
556 $height = $img->getHeight();
557 }
558 if ( 0 == $width || 0 == $height ) {
559 $width = $height = 180;
560 }
561 if ( $boxwidth == 0 ) {
562 $boxwidth = 180;
563 }
564 if ( $framed ) {
565 // Use image dimensions, don't scale
566 $boxwidth = $width;
567 $boxheight = $height;
568 $thumbUrl = $img->getViewURL();
569 } else {
570 if ( $boxheight === false )
571 $boxheight = -1;
572 if ( '' == $manual_thumb ) {
573 $thumb = $img->getThumbnail( $boxwidth, $boxheight, $wgGenerateThumbnailOnParse );
574 if ( $thumb ) {
575 $thumbUrl = $thumb->getUrl();
576 $boxwidth = $thumb->width;
577 $boxheight = $thumb->height;
578 } else {
579 $error = $img->getLastError();
580 }
581 }
582 }
583 $oboxwidth = $boxwidth + 2;
584
585 if ( $manual_thumb != '' ) # Use manually specified thumbnail
586 {
587 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb ); #new Title ( $manual_thumb ) ;
588 if( $manual_title ) {
589 $manual_img = new Image( $manual_title );
590 $thumbUrl = $manual_img->getViewURL();
591 if ( $manual_img->exists() )
592 {
593 $width = $manual_img->getWidth();
594 $height = $manual_img->getHeight();
595 $boxwidth = $width ;
596 $boxheight = $height ;
597 $oboxwidth = $boxwidth + 2 ;
598 }
599 }
600 }
601
602 $u = $img->getEscapeLocalURL();
603
604 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
605 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
606 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
607
608 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$oboxwidth}px;\">";
609 if( $thumbUrl == '' ) {
610 // Couldn't generate thumbnail? Scale the image client-side.
611 $thumbUrl = $img->getViewURL();
612 if( $boxheight == -1 ) {
613 // Approximate...
614 $boxheight = intval( $height * $boxwidth / $width );
615 }
616 }
617 if ( $error ) {
618 $s .= htmlspecialchars( $error );
619 $zoomicon = '';
620 } elseif( !$img->exists() ) {
621 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
622 $zoomicon = '';
623 } else {
624 $s .= '<a href="'.$u.'" class="internal" title="'.$alt.'">'.
625 '<img src="'.$thumbUrl.'" alt="'.$alt.'" ' .
626 'width="'.$boxwidth.'" height="'.$boxheight.'" ' .
627 'longdesc="'.$u.'" class="thumbimage" /></a>';
628 if ( $framed ) {
629 $zoomicon="";
630 } else {
631 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
632 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
633 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
634 'width="15" height="11" alt="" /></a></div>';
635 }
636 }
637 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
638 return str_replace("\n", ' ', $s);
639 }
640
641 /**
642 * Pass a title object, not a title string
643 */
644 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
645 # Fail gracefully
646 if ( ! isset($nt) ) {
647 # throw new MWException();
648 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
649 }
650
651 $fname = 'Linker::makeBrokenImageLinkObj';
652 wfProfileIn( $fname );
653
654 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
655 if ( '' != $query ) {
656 $q .= "&$query";
657 }
658 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
659 $url = $uploadTitle->escapeLocalURL( $q );
660
661 if ( '' == $text ) {
662 $text = htmlspecialchars( $nt->getPrefixedText() );
663 }
664 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
665 list( $inside, $trail ) = Linker::splitTrail( $trail );
666 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
667
668 wfProfileOut( $fname );
669 return $s;
670 }
671
672 /** @todo document */
673 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
674 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
675 return $this->makeMediaLinkObj( $nt, $alt );
676 }
677
678 /**
679 * Create a direct link to a given uploaded file.
680 *
681 * @param $title Title object.
682 * @param $text String: pre-sanitized HTML
683 * @param $nourl Boolean: Mask absolute URLs, so the parser doesn't
684 * linkify them (it is currently not context-aware)
685 * @return string HTML
686 *
687 * @public
688 * @todo Handle invalid or missing images better.
689 */
690 function makeMediaLinkObj( $title, $text = '' ) {
691 if( is_null( $title ) ) {
692 ### HOTFIX. Instead of breaking, return empty string.
693 return $text;
694 } else {
695 $img = new Image( $title );
696 if( $img->exists() ) {
697 $url = $img->getURL();
698 $class = 'internal';
699 } else {
700 $upload = SpecialPage::getTitleFor( 'Upload' );
701 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
702 $class = 'new';
703 }
704 $alt = htmlspecialchars( $title->getText() );
705 if( $text == '' ) {
706 $text = $alt;
707 }
708 $u = htmlspecialchars( $url );
709 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
710 }
711 }
712
713 /** @todo document */
714 function specialLink( $name, $key = '' ) {
715 global $wgContLang;
716
717 if ( '' == $key ) { $key = strtolower( $name ); }
718 $pn = $wgContLang->ucfirst( $name );
719 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
720 wfMsg( $key ) );
721 }
722
723 /** @todo document */
724 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
725 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
726 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
727 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
728 $style .= ' rel="nofollow"';
729 }
730 $url = htmlspecialchars( $url );
731 if( $escape ) {
732 $text = htmlspecialchars( $text );
733 }
734 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
735 }
736
737 /**
738 * Make user link (or user contributions for unregistered users)
739 * @param $userId Integer: user id in database.
740 * @param $userText String: user name in database
741 * @return string HTML fragment
742 * @private
743 */
744 function userLink( $userId, $userText ) {
745 $encName = htmlspecialchars( $userText );
746 if( $userId == 0 ) {
747 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
748 return $this->makeKnownLinkObj( $contribsPage,
749 $encName);
750 } else {
751 $userPage = Title::makeTitle( NS_USER, $userText );
752 return $this->makeLinkObj( $userPage, $encName );
753 }
754 }
755
756 /**
757 * @param $userId Integer: user id in database.
758 * @param $userText String: user name in database.
759 * @return string HTML fragment with talk and/or block links
760 * @private
761 */
762 function userToolLinks( $userId, $userText ) {
763 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
764 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
765 $blockable = ( $wgSysopUserBans || 0 == $userId );
766
767 $items = array();
768 if( $talkable ) {
769 $items[] = $this->userTalkLink( $userId, $userText );
770 }
771 if( $userId ) {
772 // check if the user has an edit
773 if( User::edits( $userId ) == 0 ) {
774 $style = "class='new'";
775 } else {
776 $style = '';
777 }
778 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
779 $items[] = $this->makeKnownLinkObj( $contribsPage ,
780 wfMsgHtml( 'contribslink' ),
781 '', '', '', '', $style
782 );
783 }
784 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
785 $items[] = $this->blockLink( $userId, $userText );
786 }
787
788 if( $items ) {
789 return ' (' . implode( ' | ', $items ) . ')';
790 } else {
791 return '';
792 }
793 }
794
795 /**
796 * @param $userId Integer: user id in database.
797 * @param $userText String: user name in database.
798 * @return string HTML fragment with user talk link
799 * @private
800 */
801 function userTalkLink( $userId, $userText ) {
802 global $wgLang;
803 $talkname = $wgLang->getNsText( NS_TALK ); # use the shorter name
804
805 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
806 $userTalkLink = $this->makeLinkObj( $userTalkPage, $talkname );
807 return $userTalkLink;
808 }
809
810 /**
811 * @param $userId Integer: userid
812 * @param $userText String: user name in database.
813 * @return string HTML fragment with block link
814 * @private
815 */
816 function blockLink( $userId, $userText ) {
817 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
818 $blockLink = $this->makeKnownLinkObj( $blockPage,
819 wfMsgHtml( 'blocklink' ) );
820 return $blockLink;
821 }
822
823 /**
824 * Generate a user link if the current user is allowed to view it
825 * @param $rev Revision object.
826 * @return string HTML
827 */
828 function revUserLink( $rev ) {
829 if( $rev->userCan( Revision::DELETED_USER ) ) {
830 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
831 } else {
832 $link = wfMsgHtml( 'rev-deleted-user' );
833 }
834 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
835 return '<span class="history-deleted">' . $link . '</span>';
836 }
837 return $link;
838 }
839
840 /**
841 * Generate a user tool link cluster if the current user is allowed to view it
842 * @param $rev Revision object.
843 * @return string HTML
844 */
845 function revUserTools( $rev ) {
846 if( $rev->userCan( Revision::DELETED_USER ) ) {
847 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
848 ' ' .
849 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
850 } else {
851 $link = wfMsgHtml( 'rev-deleted-user' );
852 }
853 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
854 return '<span class="history-deleted">' . $link . '</span>';
855 }
856 return $link;
857 }
858
859 /**
860 * This function is called by all recent changes variants, by the page history,
861 * and by the user contributions list. It is responsible for formatting edit
862 * comments. It escapes any HTML in the comment, but adds some CSS to format
863 * auto-generated comments (from section editing) and formats [[wikilinks]].
864 *
865 * @author Erik Moeller <moeller@scireview.de>
866 *
867 * Note: there's not always a title to pass to this function.
868 * Since you can't set a default parameter for a reference, I've turned it
869 * temporarily to a value pass. Should be adjusted further. --brion
870 *
871 * $param string $comment
872 * @param mixed $title Title object (to generate link to the section in autocomment) or null
873 * @param bool $local Whether section links should refer to local page
874 */
875 function formatComment($comment, $title = NULL, $local = false) {
876 wfProfileIn( __METHOD__ );
877
878 global $wgContLang;
879 $comment = str_replace( "\n", " ", $comment );
880 $comment = htmlspecialchars( $comment );
881
882 # The pattern for autogen comments is / * foo * /, which makes for
883 # some nasty regex.
884 # We look for all comments, match any text before and after the comment,
885 # add a separator where needed and format the comment itself with CSS
886 $match = array();
887 while (preg_match('/(.*)\/\*\s*(.*?)\s*\*\/(.*)/', $comment,$match)) {
888 $pre=$match[1];
889 $auto=$match[2];
890 $post=$match[3];
891 $link='';
892 if( $title ) {
893 $section = $auto;
894
895 # Generate a valid anchor name from the section title.
896 # Hackish, but should generally work - we strip wiki
897 # syntax, including the magic [[: that is used to
898 # "link rather than show" in case of images and
899 # interlanguage links.
900 $section = str_replace( '[[:', '', $section );
901 $section = str_replace( '[[', '', $section );
902 $section = str_replace( ']]', '', $section );
903 if ( $local ) {
904 $sectionTitle = Title::newFromText( '#' . $section);
905 } else {
906 $sectionTitle = wfClone( $title );
907 $sectionTitle->mFragment = $section;
908 }
909 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
910 }
911 $sep='-';
912 $auto=$link.$auto;
913 if($pre) { $auto = $sep.' '.$auto; }
914 if($post) { $auto .= ' '.$sep; }
915 $auto='<span class="autocomment">'.$auto.'</span>';
916 $comment=$pre.$auto.$post;
917 }
918
919 # format regular and media links - all other wiki formatting
920 # is ignored
921 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
922 $medians .= preg_quote( $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 $submatch = array();
931 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
932 # Media link; trail not supported.
933 $linkRegexp = '/\[\[(.*?)\]\]/';
934 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
935 } else {
936 # Other kind of link
937 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
938 $trail = $submatch[1];
939 } else {
940 $trail = "";
941 }
942 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
943 if (isset($match[1][0]) && $match[1][0] == ':')
944 $match[1] = substr($match[1], 1);
945 $thelink = $this->makeLink( $match[1], $text, "", $trail );
946 }
947 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
948 }
949 wfProfileOut( __METHOD__ );
950 return $comment;
951 }
952
953 /**
954 * Wrap a comment in standard punctuation and formatting if
955 * it's non-empty, otherwise return empty string.
956 *
957 * @param string $comment
958 * @param mixed $title Title object (to generate link to section in autocomment) or null
959 * @param bool $local Whether section links should refer to local page
960 *
961 * @return string
962 */
963 function commentBlock( $comment, $title = NULL, $local = false ) {
964 // '*' used to be the comment inserted by the software way back
965 // in antiquity in case none was provided, here for backwards
966 // compatability, acc. to brion -ævar
967 if( $comment == '' || $comment == '*' ) {
968 return '';
969 } else {
970 $formatted = $this->formatComment( $comment, $title, $local );
971 return " <span class=\"comment\">($formatted)</span>";
972 }
973 }
974
975 /**
976 * Wrap and format the given revision's comment block, if the current
977 * user is allowed to view it.
978 *
979 * @param Revision $rev
980 * @param bool $local Whether section links should refer to local page
981 * @return string HTML
982 */
983 function revComment( Revision $rev, $local = false ) {
984 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
985 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
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 public 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 public 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 * Create a headline for content
1070 *
1071 * @param int $level The level of the headline (1-6)
1072 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1073 * This *must* be at least '>' for no attribs
1074 * @param string $anchor The anchor to give the headline (the bit after the #)
1075 * @param string $text The text of the header
1076 * @param string $link HTML to add for the section edit link
1077 *
1078 * @return string HTML headline
1079 */
1080 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1081 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1082 }
1083
1084 /**
1085 * Split a link trail, return the "inside" portion and the remainder of the trail
1086 * as a two-element array
1087 *
1088 * @static
1089 */
1090 static function splitTrail( $trail ) {
1091 static $regex = false;
1092 if ( $regex === false ) {
1093 global $wgContLang;
1094 $regex = $wgContLang->linkTrail();
1095 }
1096 $inside = '';
1097 if ( '' != $trail ) {
1098 $m = array();
1099 if ( preg_match( $regex, $trail, $m ) ) {
1100 $inside = $m[1];
1101 $trail = $m[2];
1102 }
1103 }
1104 return array( $inside, $trail );
1105 }
1106
1107 /**
1108 * Generate a rollback link for a given revision. Currently it's the
1109 * caller's responsibility to ensure that the revision is the top one. If
1110 * it's not, of course, the user will get an error message.
1111 *
1112 * If the calling page is called with the parameter &bot=1, all rollback
1113 * links also get that parameter. It causes the edit itself and the rollback
1114 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1115 * changes, so this allows sysops to combat a busy vandal without bothering
1116 * other users.
1117 *
1118 * @param Revision $rev
1119 */
1120 function generateRollback( $rev ) {
1121 global $wgUser, $wgRequest;
1122 $title = $rev->getTitle();
1123
1124 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1125 $extraRollback .= '&token=' . urlencode(
1126 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1127 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1128 wfMsg('rollbacklink'),
1129 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1130 }
1131
1132 /**
1133 * Returns HTML for the "templates used on this page" list.
1134 *
1135 * @param array $templates Array of templates from Article::getUsedTemplate
1136 * or similar
1137 * @param bool $preview Whether this is for a preview
1138 * @param bool $section Whether this is for a section edit
1139 * @return string HTML output
1140 */
1141 public function formatTemplates( $templates, $preview = false, $section = false) {
1142 global $wgUser;
1143 wfProfileIn( __METHOD__ );
1144
1145 $sk =& $wgUser->getSkin();
1146
1147 $outText = '';
1148 if ( count( $templates ) > 0 ) {
1149 # Do a batch existence check
1150 $batch = new LinkBatch;
1151 foreach( $templates as $title ) {
1152 $batch->addObj( $title );
1153 }
1154 $batch->execute();
1155
1156 # Construct the HTML
1157 $outText = '<div class="mw-templatesUsedExplanation">';
1158 if ( $preview ) {
1159 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1160 } elseif ( $section ) {
1161 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1162 } else {
1163 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1164 }
1165 $outText .= '</div><ul>';
1166
1167 foreach ( $templates as $titleObj ) {
1168 $r = $titleObj->getRestrictions( 'edit' );
1169 if ( in_array( 'sysop', $r ) ) {
1170 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1171 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1172 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1173 } else {
1174 $protected = '';
1175 }
1176 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1177 }
1178 $outText .= '</ul>';
1179 }
1180 wfProfileOut( __METHOD__ );
1181 return $outText;
1182 }
1183
1184 /**
1185 * Format a size in bytes for output, using an appropriate
1186 * unit (B, KB, MB or GB) according to the magnitude in question
1187 *
1188 * @param $size Size to format
1189 * @return string
1190 */
1191 public function formatSize( $size ) {
1192 global $wgLang;
1193 if( $size > 1024 ) {
1194 $size = $size / 1024;
1195 if( $size > 1024 ) {
1196 $size = $size / 1024;
1197 if( $size > 1024 ) {
1198 $size = $size / 1024;
1199 $msg = 'size-gigabytes';
1200 } else {
1201 $msg = 'size-megabytes';
1202 }
1203 } else {
1204 $msg = 'size-kilobytes';
1205 }
1206 } else {
1207 $msg = 'size-bytes';
1208 }
1209 $size = round( $size, 0 );
1210 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1211 }
1212
1213 /**
1214 * Given the id of an interface element, constructs the appropriate title
1215 * and accesskey attributes from the system messages. (Note, this is usu-
1216 * ally the id but isn't always, because sometimes the accesskey needs to
1217 * go on a different element than the id, for reverse-compatibility, etc.)
1218 *
1219 * @param string $name Id of the element, minus prefixes.
1220 * @return string title and accesskey attributes, ready to drop in an
1221 * element (e.g., ' title="This does something [x]" accesskey="x"').
1222 */
1223 public function tooltipAndAccesskey($name) {
1224 $out = '';
1225
1226 $tooltip = wfMsg('tooltip-'.$name);
1227 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1228 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1229 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1230 $out .= ' title="'.htmlspecialchars($tooltip);
1231 }
1232 $accesskey = wfMsg('accesskey-'.$name);
1233 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1234 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1235 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1236 } elseif ($out) {
1237 $out .= '"';
1238 }
1239 return $out;
1240 }
1241
1242 /**
1243 * Given the id of an interface element, constructs the appropriate title
1244 * attribute from the system messages. (Note, this is usually the id but
1245 * isn't always, because sometimes the accesskey needs to go on a different
1246 * element than the id, for reverse-compatibility, etc.)
1247 *
1248 * @param string $name Id of the element, minus prefixes.
1249 * @return string title attribute, ready to drop in an element
1250 * (e.g., ' title="This does something"').
1251 */
1252 public function tooltip($name) {
1253 $out = '';
1254
1255 $tooltip = wfMsg('tooltip-'.$name);
1256 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1257 $out = ' title="'.htmlspecialchars($tooltip).'"';
1258 }
1259
1260 return $out;
1261 }
1262 }
1263
1264 ?>