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