* Skip additional setting of include_path in commandLine.inc (for non-Wikimedia mode)
[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( $nt->getNamespace() == NS_SPECIAL ) {
335 $q = $query;
336 } else if ( '' == $query ) {
337 $q = 'action=edit';
338 } else {
339 $q = 'action=edit&'.$query;
340 }
341 $u = $nt->escapeLocalURL( $q );
342
343 if ( '' == $text ) {
344 $text = htmlspecialchars( $nt->getPrefixedText() );
345 }
346 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
347
348 list( $inside, $trail ) = Linker::splitTrail( $trail );
349 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
350
351 wfProfileOut( $fname );
352 return $s;
353 }
354
355 /**
356 * Make a brown link to a short article.
357 *
358 * @param $title String: the text of the title
359 * @param $text String: link text
360 * @param $query String: optional query part
361 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
362 * be included in the link text. Other characters will be appended after
363 * the end of the link.
364 */
365 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
366 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
367 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
368 }
369
370 /**
371 * Generate either a normal exists-style link or a stub link, depending
372 * on the given page size.
373 *
374 * @param $size Integer
375 * @param $nt Title object.
376 * @param $text String
377 * @param $query String
378 * @param $trail String
379 * @param $prefix String
380 * @return string HTML of link
381 */
382 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
383 global $wgUser;
384 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
385 if( $size < $threshold ) {
386 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
387 } else {
388 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
389 }
390 }
391
392 /**
393 * Make appropriate markup for a link to the current article. This is currently rendered
394 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
395 * despite $query not being used.
396 */
397 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
398 if ( '' == $text ) {
399 $text = htmlspecialchars( $nt->getPrefixedText() );
400 }
401 list( $inside, $trail ) = Linker::splitTrail( $trail );
402 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
403 }
404
405 /** @todo document */
406 function fnamePart( $url ) {
407 $basename = strrchr( $url, '/' );
408 if ( false === $basename ) {
409 $basename = $url;
410 } else {
411 $basename = substr( $basename, 1 );
412 }
413 return htmlspecialchars( $basename );
414 }
415
416 /** Obsolete alias */
417 function makeImage( $url, $alt = '' ) {
418 return $this->makeExternalImage( $url, $alt );
419 }
420
421 /** @todo document */
422 function makeExternalImage( $url, $alt = '' ) {
423 if ( '' == $alt ) {
424 $alt = $this->fnamePart( $url );
425 }
426 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
427 return $s;
428 }
429
430 /** Creates the HTML source for images
431 * @param object $nt
432 * @param string $label label text
433 * @param string $alt alt text
434 * @param string $align horizontal alignment: none, left, center, right)
435 * @param array $params some format keywords: width, height, page, upright, upright_factor, frameless, border
436 * @param boolean $framed shows image in original size in a frame
437 * @param boolean $thumb shows image as thumbnail in a frame
438 * @param string $manual_thumb image name for the manual thumbnail
439 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
440 * @return string
441 */
442 function makeImageLinkObj( $nt, $label, $alt, $align = '', $params = array(), $framed = false,
443 $thumb = false, $manual_thumb = '', $valign = '', $time = false )
444 {
445 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
446
447 $img = wfFindFile( $nt, $time );
448
449 if ( $img && !$img->allowInlineDisplay() ) {
450 wfDebug( __METHOD__.': '.$nt->getPrefixedDBkey()." does not allow inline display\n" );
451 return $this->makeKnownLinkObj( $nt );
452 }
453
454 $error = $prefix = $postfix = '';
455 $page = isset( $params['page'] ) ? $params['page'] : false;
456
457 if ( 'center' == $align )
458 {
459 $prefix = '<div class="center">';
460 $postfix = '</div>';
461 $align = 'none';
462 }
463 if ( $img && !isset( $params['width'] ) ) {
464 $params['width'] = $img->getWidth( $page );
465 if( $thumb || $framed || isset( $params['frameless'] ) ) {
466 $wopt = $wgUser->getOption( 'thumbsize' );
467
468 if( !isset( $wgThumbLimits[$wopt] ) ) {
469 $wopt = User::getDefaultOption( 'thumbsize' );
470 }
471
472 // Reduce width for upright images when parameter 'upright' is used
473 if ( !isset( $params['upright_factor'] ) || $params['upright_factor'] == 0 ) {
474 $params['upright_factor'] = $wgThumbUpright;
475 }
476 // Use width which is smaller: real image width or user preference width
477 // 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
478 $params['width'] = min( $params['width'], isset( $params['upright'] ) ? round( $wgThumbLimits[$wopt] * $params['upright_factor'], -1 ) : $wgThumbLimits[$wopt] );
479 }
480 }
481
482 if ( $thumb || $framed ) {
483
484 # Create a thumbnail. Alignment depends on language
485 # writing direction, # right aligned for left-to-right-
486 # languages ("Western languages"), left-aligned
487 # for right-to-left-languages ("Semitic languages")
488 #
489 # If thumbnail width has not been provided, it is set
490 # to the default user option as specified in Language*.php
491 if ( $align == '' ) {
492 $align = $wgContLang->isRTL() ? 'left' : 'right';
493 }
494 return $prefix.$this->makeThumbLinkObj( $nt, $img, $label, $alt, $align, $params, $framed, $manual_thumb ).$postfix;
495 }
496
497 if ( $img && $params['width'] ) {
498 # Create a resized image, without the additional thumbnail features
499 $thumb = $img->transform( $params );
500 } else {
501 $thumb = false;
502 }
503
504 if ( $page ) {
505 $query = 'page=' . urlencode( $page );
506 } else {
507 $query = '';
508 }
509 $u = $nt->getLocalURL( $query );
510 $imgAttribs = array(
511 'alt' => $alt,
512 'longdesc' => $u
513 );
514
515 if ( $valign ) {
516 $imgAttribs['style'] = "vertical-align: $valign";
517 }
518 if ( isset( $params['border'] ) ) {
519 $imgAttribs['class'] = "thumbborder";
520 }
521 $linkAttribs = array(
522 'href' => $u,
523 'class' => 'image',
524 'title' => $alt
525 );
526
527 if ( !$thumb ) {
528 $s = $this->makeBrokenImageLinkObj( $nt );
529 } else {
530 $s = $thumb->toHtml( $imgAttribs, $linkAttribs );
531 }
532 if ( '' != $align ) {
533 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
534 }
535 return str_replace("\n", ' ',$prefix.$s.$postfix);
536 }
537
538 /**
539 * Make HTML for a thumbnail including image, border and caption
540 * @param Title $nt
541 * @param Image $img Image object or false if it doesn't exist
542 */
543 function makeThumbLinkObj( Title $nt, $img, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manual_thumb = "" ) {
544 global $wgStylePath, $wgContLang;
545 $exists = $img && $img->exists();
546
547 $page = isset( $params['page'] ) ? $params['page'] : false;
548
549 if ( empty( $params['width'] ) ) {
550 // Reduce width for upright images when parameter 'upright' is used
551 $params['width'] = isset( $params['upright'] ) ? 130 : 180;
552 }
553 $thumb = false;
554
555 if ( !$exists ) {
556 $outerWidth = $params['width'] + 2;
557 } else {
558 if ( $manual_thumb != '' ) {
559 # Use manually specified thumbnail
560 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb );
561 if( $manual_title ) {
562 $manual_img = wfFindFile( $manual_title );
563 if ( $manual_img ) {
564 $thumb = $manual_img->getUnscaledThumb();
565 } else {
566 $exists = false;
567 }
568 }
569 } elseif ( $framed ) {
570 // Use image dimensions, don't scale
571 $thumb = $img->getUnscaledThumb( $page );
572 } else {
573 # Do not present an image bigger than the source, for bitmap-style images
574 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
575 $srcWidth = $img->getWidth( $page );
576 if ( $srcWidth && !$img->mustRender() && $params['width'] > $srcWidth ) {
577 $params['width'] = $srcWidth;
578 }
579 $thumb = $img->transform( $params );
580 }
581
582 if ( $thumb ) {
583 $outerWidth = $thumb->getWidth() + 2;
584 } else {
585 $outerWidth = $params['width'] + 2;
586 }
587 }
588
589 $query = $page ? 'page=' . urlencode( $page ) : '';
590 $u = $nt->getLocalURL( $query );
591
592 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
593 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
594 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
595
596 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
597 if( !$exists ) {
598 $s .= $this->makeBrokenImageLinkObj( $nt );
599 $zoomicon = '';
600 } elseif ( !$thumb ) {
601 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
602 $zoomicon = '';
603 } else {
604 $imgAttribs = array(
605 'alt' => $alt,
606 'longdesc' => $u,
607 'class' => 'thumbimage'
608 );
609 $linkAttribs = array(
610 'href' => $u,
611 'class' => 'internal',
612 'title' => $alt
613 );
614
615 $s .= $thumb->toHtml( $imgAttribs, $linkAttribs );
616 if ( $framed ) {
617 $zoomicon="";
618 } else {
619 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
620 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
621 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
622 'width="15" height="11" alt="" /></a></div>';
623 }
624 }
625 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
626 return str_replace("\n", ' ', $s);
627 }
628
629 /**
630 * Pass a title object, not a title string
631 */
632 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
633 # Fail gracefully
634 if ( ! isset($nt) ) {
635 # throw new MWException();
636 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
637 }
638
639 $fname = 'Linker::makeBrokenImageLinkObj';
640 wfProfileIn( $fname );
641
642 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
643 if ( '' != $query ) {
644 $q .= "&$query";
645 }
646 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
647 $url = $uploadTitle->escapeLocalURL( $q );
648
649 if ( '' == $text ) {
650 $text = htmlspecialchars( $nt->getPrefixedText() );
651 }
652 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
653 list( $inside, $trail ) = Linker::splitTrail( $trail );
654 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
655
656 wfProfileOut( $fname );
657 return $s;
658 }
659
660 /** @deprecated use Linker::makeMediaLinkObj() */
661 function makeMediaLink( $name, $unused = '', $text = '' ) {
662 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
663 return $this->makeMediaLinkObj( $nt, $text );
664 }
665
666 /**
667 * Create a direct link to a given uploaded file.
668 *
669 * @param $title Title object.
670 * @param $text String: pre-sanitized HTML
671 * @return string HTML
672 *
673 * @public
674 * @todo Handle invalid or missing images better.
675 */
676 function makeMediaLinkObj( $title, $text = '' ) {
677 if( is_null( $title ) ) {
678 ### HOTFIX. Instead of breaking, return empty string.
679 return $text;
680 } else {
681 $img = wfFindFile( $title );
682 if( $img ) {
683 $url = $img->getURL();
684 $class = 'internal';
685 } else {
686 $upload = SpecialPage::getTitleFor( 'Upload' );
687 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
688 $class = 'new';
689 }
690 $alt = htmlspecialchars( $title->getText() );
691 if( $text == '' ) {
692 $text = $alt;
693 }
694 $u = htmlspecialchars( $url );
695 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
696 }
697 }
698
699 /** @todo document */
700 function specialLink( $name, $key = '' ) {
701 global $wgContLang;
702
703 if ( '' == $key ) { $key = strtolower( $name ); }
704 $pn = $wgContLang->ucfirst( $name );
705 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
706 wfMsg( $key ) );
707 }
708
709 /** @todo document */
710 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
711 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
712 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
713 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
714 $style .= ' rel="nofollow"';
715 }
716 $url = htmlspecialchars( $url );
717 if( $escape ) {
718 $text = htmlspecialchars( $text );
719 }
720 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
721 }
722
723 /**
724 * Make user link (or user contributions for unregistered users)
725 * @param $userId Integer: user id in database.
726 * @param $userText String: user name in database
727 * @return string HTML fragment
728 * @private
729 */
730 function userLink( $userId, $userText ) {
731 $encName = htmlspecialchars( $userText );
732 if( $userId == 0 ) {
733 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
734 return $this->makeKnownLinkObj( $contribsPage,
735 $encName);
736 } else {
737 $userPage = Title::makeTitle( NS_USER, $userText );
738 return $this->makeLinkObj( $userPage, $encName );
739 }
740 }
741
742 /**
743 * @param $userId Integer: user id in database.
744 * @param $userText String: user name in database.
745 * @param $redContribsWhenNoEdits Bool: return a red contribs link when the user had no edits and this is true.
746 * @return string HTML fragment with talk and/or block links
747 */
748 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false ) {
749 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
750 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
751 $blockable = ( $wgSysopUserBans || 0 == $userId );
752
753 $items = array();
754 if( $talkable ) {
755 $items[] = $this->userTalkLink( $userId, $userText );
756 }
757 if( $userId ) {
758 // check if the user has an edit
759 if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
760 $style = "class='new'";
761 } else {
762 $style = '';
763 }
764 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
765
766 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
767 }
768 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
769 $items[] = $this->blockLink( $userId, $userText );
770 }
771
772 if( $items ) {
773 return ' (' . implode( ' | ', $items ) . ')';
774 } else {
775 return '';
776 }
777 }
778
779 /**
780 * Alias for userToolLinks( $userId, $userText, true );
781 */
782 public function userToolLinksRedContribs( $userId, $userText ) {
783 return $this->userToolLinks( $userId, $userText, true );
784 }
785
786
787 /**
788 * @param $userId Integer: user id in database.
789 * @param $userText String: user name in database.
790 * @return string HTML fragment with user talk link
791 * @private
792 */
793 function userTalkLink( $userId, $userText ) {
794 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
795 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
796 return $userTalkLink;
797 }
798
799 /**
800 * @param $userId Integer: userid
801 * @param $userText String: user name in database.
802 * @return string HTML fragment with block link
803 * @private
804 */
805 function blockLink( $userId, $userText ) {
806 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
807 $blockLink = $this->makeKnownLinkObj( $blockPage,
808 wfMsgHtml( 'blocklink' ) );
809 return $blockLink;
810 }
811
812 /**
813 * Generate a user link if the current user is allowed to view it
814 * @param $rev Revision object.
815 * @return string HTML
816 */
817 function revUserLink( $rev ) {
818 if( $rev->userCan( Revision::DELETED_USER ) ) {
819 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
820 } else {
821 $link = wfMsgHtml( 'rev-deleted-user' );
822 }
823 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
824 return '<span class="history-deleted">' . $link . '</span>';
825 }
826 return $link;
827 }
828
829 /**
830 * Generate a user tool link cluster if the current user is allowed to view it
831 * @param $rev Revision object.
832 * @return string HTML
833 */
834 function revUserTools( $rev ) {
835 if( $rev->userCan( Revision::DELETED_USER ) ) {
836 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
837 ' ' .
838 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
839 } else {
840 $link = wfMsgHtml( 'rev-deleted-user' );
841 }
842 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
843 return '<span class="history-deleted">' . $link . '</span>';
844 }
845 return $link;
846 }
847
848 /**
849 * This function is called by all recent changes variants, by the page history,
850 * and by the user contributions list. It is responsible for formatting edit
851 * comments. It escapes any HTML in the comment, but adds some CSS to format
852 * auto-generated comments (from section editing) and formats [[wikilinks]].
853 *
854 * @author Erik Moeller <moeller@scireview.de>
855 *
856 * Note: there's not always a title to pass to this function.
857 * Since you can't set a default parameter for a reference, I've turned it
858 * temporarily to a value pass. Should be adjusted further. --brion
859 *
860 * @param string $comment
861 * @param mixed $title Title object (to generate link to the section in autocomment) or null
862 * @param bool $local Whether section links should refer to local page
863 */
864 function formatComment($comment, $title = NULL, $local = false) {
865 wfProfileIn( __METHOD__ );
866
867 # Sanitize text a bit:
868 $comment = str_replace( "\n", " ", $comment );
869 $comment = htmlspecialchars( $comment );
870
871 # Render autocomments and make links:
872 $comment = $this->formatAutoComments( $comment, $title, $local );
873 $comment = $this->formatLinksInComment( $comment );
874
875 wfProfileOut( __METHOD__ );
876 return $comment;
877 }
878
879 /**
880 * The pattern for autogen comments is / * foo * /, which makes for
881 * some nasty regex.
882 * We look for all comments, match any text before and after the comment,
883 * add a separator where needed and format the comment itself with CSS
884 * Called by Linker::formatComment.
885 *
886 * @param $comment Comment text
887 * @param $title An optional title object used to links to sections
888 *
889 * @todo Document the $local parameter.
890 */
891 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
892 $match = array();
893 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
894 $pre=$match[1];
895 $auto=$match[2];
896 $post=$match[3];
897 $link='';
898 if( $title ) {
899 $section = $auto;
900
901 # Generate a valid anchor name from the section title.
902 # Hackish, but should generally work - we strip wiki
903 # syntax, including the magic [[: that is used to
904 # "link rather than show" in case of images and
905 # interlanguage links.
906 $section = str_replace( '[[:', '', $section );
907 $section = str_replace( '[[', '', $section );
908 $section = str_replace( ']]', '', $section );
909 if ( $local ) {
910 $sectionTitle = Title::newFromText( '#' . $section);
911 } else {
912 $sectionTitle = wfClone( $title );
913 $sectionTitle->mFragment = $section;
914 }
915 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
916 }
917 $sep='-';
918 $auto=$link.$auto;
919 if($pre) { $auto = $sep.' '.$auto; }
920 if($post) { $auto .= ' '.$sep; }
921 $auto='<span class="autocomment">'.$auto.'</span>';
922 $comment=$pre.$auto.$post;
923 }
924
925 return $comment;
926 }
927
928 /**
929 * Format regular and media links - all other wiki formatting is ignored
930 * Called by Linker::formatComment.
931 * @param $comment The comment text.
932 * @return Comment text with links using HTML.
933 */
934 private function formatLinksInComment( $comment ) {
935 global $wgContLang;
936
937 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
938 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
939
940 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
941 # Handle link renaming [[foo|text]] will show link as "text"
942 if( "" != $match[3] ) {
943 $text = $match[3];
944 } else {
945 $text = $match[1];
946 }
947 $submatch = array();
948 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
949 # Media link; trail not supported.
950 $linkRegexp = '/\[\[(.*?)\]\]/';
951 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
952 } else {
953 # Other kind of link
954 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
955 $trail = $submatch[1];
956 } else {
957 $trail = "";
958 }
959 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
960 if (isset($match[1][0]) && $match[1][0] == ':')
961 $match[1] = substr($match[1], 1);
962 $thelink = $this->makeLink( $match[1], $text, "", $trail );
963 }
964 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
965 }
966
967 return $comment;
968 }
969
970 /**
971 * Wrap a comment in standard punctuation and formatting if
972 * it's non-empty, otherwise return empty string.
973 *
974 * @param string $comment
975 * @param mixed $title Title object (to generate link to section in autocomment) or null
976 * @param bool $local Whether section links should refer to local page
977 *
978 * @return string
979 */
980 function commentBlock( $comment, $title = NULL, $local = false ) {
981 // '*' used to be the comment inserted by the software way back
982 // in antiquity in case none was provided, here for backwards
983 // compatability, acc. to brion -ævar
984 if( $comment == '' || $comment == '*' ) {
985 return '';
986 } else {
987 $formatted = $this->formatComment( $comment, $title, $local );
988 return " <span class=\"comment\">($formatted)</span>";
989 }
990 }
991
992 /**
993 * Wrap and format the given revision's comment block, if the current
994 * user is allowed to view it.
995 *
996 * @param Revision $rev
997 * @param bool $local Whether section links should refer to local page
998 * @return string HTML
999 */
1000 function revComment( Revision $rev, $local = false ) {
1001 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1002 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1003 } else {
1004 $block = " <span class=\"comment\">" .
1005 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1006 }
1007 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1008 return " <span class=\"history-deleted\">$block</span>";
1009 }
1010 return $block;
1011 }
1012
1013 /** @todo document */
1014 function tocIndent() {
1015 return "\n<ul>";
1016 }
1017
1018 /** @todo document */
1019 function tocUnindent($level) {
1020 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1021 }
1022
1023 /**
1024 * parameter level defines if we are on an indentation level
1025 */
1026 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1027 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1028 $anchor . '"><span class="tocnumber">' .
1029 $tocnumber . '</span> <span class="toctext">' .
1030 $tocline . '</span></a>';
1031 }
1032
1033 /** @todo document */
1034 function tocLineEnd() {
1035 return "</li>\n";
1036 }
1037
1038 /** @todo document */
1039 function tocList($toc) {
1040 global $wgJsMimeType;
1041 $title = wfMsgHtml('toc') ;
1042 return
1043 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1044 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1045 . $toc
1046 # no trailing newline, script should not be wrapped in a
1047 # paragraph
1048 . "</ul>\n</td></tr></table>"
1049 . '<script type="' . $wgJsMimeType . '">'
1050 . ' if (window.showTocToggle) {'
1051 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1052 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1053 . ' showTocToggle();'
1054 . ' } '
1055 . "</script>\n";
1056 }
1057
1058 /** @todo document */
1059 public function editSectionLinkForOther( $title, $section ) {
1060 global $wgContLang;
1061 $title = Title::newFromText( $title );
1062 $editurl = '&section='.$section;
1063 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1064 $result = null;
1065 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $title, $section, $url, &$result ) );
1066 return is_null( $result )
1067 ? "<span class=\"editsection\">[{$url}]</span>"
1068 : "<span class=\"editsection\">[{$result}]</span>";
1069 }
1070
1071 /**
1072 * @param $title Title object.
1073 * @param $section Integer: section number.
1074 * @param $hint Link String: title, or default if omitted or empty
1075 */
1076 public function editSectionLink( $nt, $section, $hint='' ) {
1077 global $wgContLang;
1078 $editurl = '&section='.$section;
1079 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1080 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1081 $result = null;
1082 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1083 return is_null( $result )
1084 ? "<span class=\"editsection\">[{$url}]</span>"
1085 : "<span class=\"editsection\">[{$result}]</span>";
1086 }
1087
1088 /**
1089 * Create a headline for content
1090 *
1091 * @param int $level The level of the headline (1-6)
1092 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1093 * This *must* be at least '>' for no attribs
1094 * @param string $anchor The anchor to give the headline (the bit after the #)
1095 * @param string $text The text of the header
1096 * @param string $link HTML to add for the section edit link
1097 *
1098 * @return string HTML headline
1099 */
1100 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1101 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1102 }
1103
1104 /**
1105 * Split a link trail, return the "inside" portion and the remainder of the trail
1106 * as a two-element array
1107 *
1108 * @static
1109 */
1110 static function splitTrail( $trail ) {
1111 static $regex = false;
1112 if ( $regex === false ) {
1113 global $wgContLang;
1114 $regex = $wgContLang->linkTrail();
1115 }
1116 $inside = '';
1117 if ( '' != $trail ) {
1118 $m = array();
1119 if ( preg_match( $regex, $trail, $m ) ) {
1120 $inside = $m[1];
1121 $trail = $m[2];
1122 }
1123 }
1124 return array( $inside, $trail );
1125 }
1126
1127 /**
1128 * Generate a rollback link for a given revision. Currently it's the
1129 * caller's responsibility to ensure that the revision is the top one. If
1130 * it's not, of course, the user will get an error message.
1131 *
1132 * If the calling page is called with the parameter &bot=1, all rollback
1133 * links also get that parameter. It causes the edit itself and the rollback
1134 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1135 * changes, so this allows sysops to combat a busy vandal without bothering
1136 * other users.
1137 *
1138 * @param Revision $rev
1139 */
1140 function generateRollback( $rev ) {
1141 global $wgUser, $wgRequest;
1142 $title = $rev->getTitle();
1143
1144 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1145 $extraRollback .= '&token=' . urlencode(
1146 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1147 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1148 wfMsg('rollbacklink'),
1149 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1150 }
1151
1152 /**
1153 * Returns HTML for the "templates used on this page" list.
1154 *
1155 * @param array $templates Array of templates from Article::getUsedTemplate
1156 * or similar
1157 * @param bool $preview Whether this is for a preview
1158 * @param bool $section Whether this is for a section edit
1159 * @return string HTML output
1160 */
1161 public function formatTemplates( $templates, $preview = false, $section = false) {
1162 global $wgUser;
1163 wfProfileIn( __METHOD__ );
1164
1165 $sk = $wgUser->getSkin();
1166
1167 $outText = '';
1168 if ( count( $templates ) > 0 ) {
1169 # Do a batch existence check
1170 $batch = new LinkBatch;
1171 foreach( $templates as $title ) {
1172 $batch->addObj( $title );
1173 }
1174 $batch->execute();
1175
1176 # Construct the HTML
1177 $outText = '<div class="mw-templatesUsedExplanation">';
1178 if ( $preview ) {
1179 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1180 } elseif ( $section ) {
1181 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1182 } else {
1183 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1184 }
1185 $outText .= '</div><ul>';
1186
1187 foreach ( $templates as $titleObj ) {
1188 $r = $titleObj->getRestrictions( 'edit' );
1189 if ( in_array( 'sysop', $r ) ) {
1190 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1191 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1192 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1193 } else {
1194 $protected = '';
1195 }
1196 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1197 }
1198 $outText .= '</ul>';
1199 }
1200 wfProfileOut( __METHOD__ );
1201 return $outText;
1202 }
1203
1204 /**
1205 * Format a size in bytes for output, using an appropriate
1206 * unit (B, KB, MB or GB) according to the magnitude in question
1207 *
1208 * @param $size Size to format
1209 * @return string
1210 */
1211 public function formatSize( $size ) {
1212 global $wgLang;
1213 // For small sizes no decimal places necessary
1214 $round = 0;
1215 if( $size > 1024 ) {
1216 $size = $size / 1024;
1217 if( $size > 1024 ) {
1218 $size = $size / 1024;
1219 // For MB and bigger two decimal places are smarter
1220 $round = 2;
1221 if( $size > 1024 ) {
1222 $size = $size / 1024;
1223 $msg = 'size-gigabytes';
1224 } else {
1225 $msg = 'size-megabytes';
1226 }
1227 } else {
1228 $msg = 'size-kilobytes';
1229 }
1230 } else {
1231 $msg = 'size-bytes';
1232 }
1233 $size = round( $size, $round );
1234 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1235 }
1236
1237 /**
1238 * Given the id of an interface element, constructs the appropriate title
1239 * and accesskey attributes from the system messages. (Note, this is usu-
1240 * ally the id but isn't always, because sometimes the accesskey needs to
1241 * go on a different element than the id, for reverse-compatibility, etc.)
1242 *
1243 * @param string $name Id of the element, minus prefixes.
1244 * @return string title and accesskey attributes, ready to drop in an
1245 * element (e.g., ' title="This does something [x]" accesskey="x"').
1246 */
1247 public function tooltipAndAccesskey($name) {
1248 $out = '';
1249
1250 $tooltip = wfMsg('tooltip-'.$name);
1251 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1252 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1253 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1254 $out .= ' title="'.htmlspecialchars($tooltip);
1255 }
1256 $accesskey = wfMsg('accesskey-'.$name);
1257 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1258 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1259 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1260 } elseif ($out) {
1261 $out .= '"';
1262 }
1263 return $out;
1264 }
1265
1266 /**
1267 * Given the id of an interface element, constructs the appropriate title
1268 * attribute from the system messages. (Note, this is usually the id but
1269 * isn't always, because sometimes the accesskey needs to go on a different
1270 * element than the id, for reverse-compatibility, etc.)
1271 *
1272 * @param string $name Id of the element, minus prefixes.
1273 * @return string title attribute, ready to drop in an element
1274 * (e.g., ' title="This does something"').
1275 */
1276 public function tooltip($name) {
1277 $out = '';
1278
1279 $tooltip = wfMsg('tooltip-'.$name);
1280 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1281 $out = ' title="'.htmlspecialchars($tooltip).'"';
1282 }
1283
1284 return $out;
1285 }
1286 }
1287
1288 ?>