]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/Linker.php
MediaWiki 1.16.4
[autoinstalls/mediawiki.git] / includes / Linker.php
1 <?php
2 /**
3  * Split off some of the internal bits from Skin.php. These functions are used
4  * for primarily page content: links, embedded images, table of contents. Links
5  * are also used in the skin. For the moment, Skin is a descendent class of
6  * Linker.  In the future, it should probably be further split so that every
7  * other bit of the wiki doesn't have to go loading up Skin to get at it.
8  *
9  * @ingroup Skins
10  */
11 class Linker {
12
13         /**
14          * Flags for userToolLinks()
15          */
16         const TOOL_LINKS_NOBLOCK = 1;
17
18         function __construct() {}
19
20         /**
21          * Get the appropriate HTML attributes to add to the "a" element of an ex-
22          * ternal link, as created by [wikisyntax].
23          *
24          * @param string $class  The contents of the class attribute; if an empty
25          *   string is passed, which is the default value, defaults to 'external'.
26          */
27         function getExternalLinkAttributes( $class = 'external' ) {
28                 return $this->getLinkAttributesInternal( '', $class );
29         }
30
31         /**
32          * Get the appropriate HTML attributes to add to the "a" element of an in-
33          * terwiki link.
34          *
35          * @param string $title  The title text for the link, URL-encoded (???) but
36          *   not HTML-escaped
37          * @param string $unused Unused
38          * @param string $class  The contents of the class attribute; if an empty
39          *   string is passed, which is the default value, defaults to 'external'.
40          */
41         function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
42                 global $wgContLang;
43
44                 # FIXME: We have a whole bunch of handling here that doesn't happen in
45                 # getExternalLinkAttributes, why?
46                 $title = urldecode( $title );
47                 $title = $wgContLang->checkTitleEncoding( $title );
48                 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
49
50                 return $this->getLinkAttributesInternal( $title, $class );
51         }
52
53         /**
54          * Get the appropriate HTML attributes to add to the "a" element of an in-
55          * ternal link.
56          *
57          * @param string $title  The title text for the link, URL-encoded (???) but
58          *   not HTML-escaped
59          * @param string $unused Unused
60          * @param string $class  The contents of the class attribute, default none
61          */
62         function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
63                 $title = urldecode( $title );
64                 $title = str_replace( '_', ' ', $title );
65                 return $this->getLinkAttributesInternal( $title, $class );
66         }
67
68         /**
69          * Get the appropriate HTML attributes to add to the "a" element of an in-
70          * ternal link, given the Title object for the page we want to link to.
71          *
72          * @param Title  $nt     The Title object
73          * @param string $unused Unused
74          * @param string $class  The contents of the class attribute, default none
75          * @param mixed  $title  Optional (unescaped) string to use in the title
76          *   attribute; if false, default to the name of the page we're linking to
77          */
78         function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
79                 if( $title === false ) {
80                         $title = $nt->getPrefixedText();
81                 }
82                 return $this->getLinkAttributesInternal( $title, $class );
83         }
84
85         /**
86          * Common code for getLinkAttributesX functions
87          */
88         private function getLinkAttributesInternal( $title, $class ) {
89                 $title = htmlspecialchars( $title );
90                 $class = htmlspecialchars( $class );
91                 $r = '';
92                 if ( $class != '' ) {
93                         $r .= " class=\"$class\"";
94                 }
95                 if ( $title != '') {
96                         $r .= " title=\"$title\"";
97                 }
98                 return $r;
99         }
100
101         /**
102          * Return the CSS colour of a known link
103          *
104          * @param Title $t
105          * @param integer $threshold user defined threshold
106          * @return string CSS class
107          */
108         function getLinkColour( $t, $threshold ) {
109                 $colour = '';
110                 if ( $t->isRedirect() ) {
111                         # Page is a redirect
112                         $colour = 'mw-redirect';
113                 } elseif ( $threshold > 0 &&
114                            $t->exists() && $t->getLength() < $threshold &&
115                            MWNamespace::isContent( $t->getNamespace() ) ) {
116                         # Page is a stub
117                         $colour = 'stub';
118                 }
119                 return $colour;
120         }
121
122         /**
123          * This function returns an HTML link to the given target.  It serves a few
124          * purposes:
125          *   1) If $target is a Title, the correct URL to link to will be figured
126          *      out automatically.
127          *   2) It automatically adds the usual classes for various types of link
128          *      targets: "new" for red links, "stub" for short articles, etc.
129          *   3) It escapes all attribute values safely so there's no risk of XSS.
130          *   4) It provides a default tooltip if the target is a Title (the page
131          *      name of the target).
132          * link() replaces the old functions in the makeLink() family.
133          *
134          * @param $target        Title  Can currently only be a Title, but this may
135          *   change to support Images, literal URLs, etc.
136          * @param $text          string The HTML contents of the <a> element, i.e.,
137          *   the link text.  This is raw HTML and will not be escaped.  If null,
138          *   defaults to the prefixed text of the Title; or if the Title is just a
139          *   fragment, the contents of the fragment.
140          * @param $customAttribs array  A key => value array of extra HTML attri-
141          *   butes, such as title and class.  (href is ignored.)  Classes will be
142          *   merged with the default classes, while other attributes will replace
143          *   default attributes.  All passed attribute values will be HTML-escaped.
144          *   A false attribute value means to suppress that attribute.
145          * @param $query         array  The query string to append to the URL
146          *   you're linking to, in key => value array form.  Query keys and values
147          *   will be URL-encoded.
148          * @param $options       mixed  String or array of strings:
149          *     'known': Page is known to exist, so don't check if it does.
150          *     'broken': Page is known not to exist, so don't check if it does.
151          *     'noclasses': Don't add any classes automatically (includes "new",
152          *       "stub", "mw-redirect", "extiw").  Only use the class attribute
153          *       provided, if any, so you get a simple blue link with no funny i-
154          *       cons.
155          *     'forcearticlepath': Use the article path always, even with a querystring.
156          *       Has compatibility issues on some setups, so avoid wherever possible.
157          * @return string HTML <a> attribute
158          */
159         public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
160                 wfProfileIn( __METHOD__ );
161                 if( !$target instanceof Title ) {
162                         return "<!-- ERROR -->$text";
163                 }
164                 $options = (array)$options;
165
166                 $ret = null;
167                 if( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
168                 &$customAttribs, &$query, &$options, &$ret ) ) ) {
169                         wfProfileOut( __METHOD__ );
170                         return $ret;
171                 }
172
173                 # Normalize the Title if it's a special page
174                 $target = $this->normaliseSpecialPage( $target );
175
176                 # If we don't know whether the page exists, let's find out.
177                 wfProfileIn( __METHOD__ . '-checkPageExistence' );
178                 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
179                         if( $target->isKnown() ) {
180                                 $options []= 'known';
181                         } else {
182                                 $options []= 'broken';
183                         }
184                 }
185                 wfProfileOut( __METHOD__ . '-checkPageExistence' );
186
187                 $oldquery = array();
188                 if( in_array( "forcearticlepath", $options ) && $query ){
189                         $oldquery = $query;
190                         $query = array();
191                 }
192
193                 # Note: we want the href attribute first, for prettiness.
194                 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
195                 if( in_array( 'forcearticlepath', $options ) && $oldquery ){
196                         $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
197                 }
198
199                 $attribs = array_merge(
200                         $attribs,
201                         $this->linkAttribs( $target, $customAttribs, $options )
202                 );
203                 if( is_null( $text ) ) {
204                         $text = $this->linkText( $target );
205                 }
206
207                 $ret = null;
208                 if( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
209                         $ret = Html::rawElement( 'a', $attribs, $text );
210                 }
211
212                 wfProfileOut( __METHOD__ );
213                 return $ret;
214         }
215
216         /**
217          * Identical to link(), except $options defaults to 'known'.
218          */
219         public function linkKnown( $target, $text = null, $customAttribs = array(), $query = array(), $options = array('known','noclasses') ) {
220                 return $this->link( $target, $text, $customAttribs, $query, $options );
221         }
222
223         /**
224          * Returns the Url used to link to a Title
225          */
226         private function linkUrl( $target, $query, $options ) {
227                 wfProfileIn( __METHOD__ );
228                 # We don't want to include fragments for broken links, because they
229                 # generally make no sense.
230                 if( in_array( 'broken', $options ) and $target->mFragment !== '' ) {
231                         $target = clone $target;
232                         $target->mFragment = '';
233                 }
234
235                 # If it's a broken link, add the appropriate query pieces, unless
236                 # there's already an action specified, or unless 'edit' makes no sense
237                 # (i.e., for a nonexistent special page).
238                 if( in_array( 'broken', $options ) and empty( $query['action'] )
239                 and $target->getNamespace() != NS_SPECIAL ) {
240                         $query['action'] = 'edit';
241                         $query['redlink'] = '1';
242                 }
243                 $ret = $target->getLinkUrl( $query );
244                 wfProfileOut( __METHOD__ );
245                 return $ret;
246         }
247
248         /**
249          * Returns the array of attributes used when linking to the Title $target
250          */
251         private function linkAttribs( $target, $attribs, $options ) {
252                 wfProfileIn( __METHOD__ );
253                 global $wgUser;
254                 $defaults = array();
255
256                 if( !in_array( 'noclasses', $options ) ) {
257                         wfProfileIn( __METHOD__ . '-getClasses' );
258                         # Now build the classes.
259                         $classes = array();
260
261                         if( in_array( 'broken', $options ) ) {
262                                 $classes[] = 'new';
263                         }
264
265                         if( $target->isExternal() ) {
266                                 $classes[] = 'extiw';
267                         }
268
269                         # Note that redirects never count as stubs here.
270                         if ( !in_array( 'broken', $options ) && $target->isRedirect() ) {
271                                 $classes[] = 'mw-redirect';
272                         } elseif( $target->isContentPage() ) {
273                                 # Check for stub.
274                                 $threshold = $wgUser->getOption( 'stubthreshold' );
275                                 if( $threshold > 0 and $target->exists() and $target->getLength() < $threshold ) {
276                                         $classes[] = 'stub';
277                                 }
278                         }
279                         if( $classes != array() ) {
280                                 $defaults['class'] = implode( ' ', $classes );
281                         }
282                         wfProfileOut( __METHOD__ . '-getClasses' );
283                 }
284
285                 # Get a default title attribute.
286                 if( $target->getPrefixedText() == '' ) {
287                         # A link like [[#Foo]].  This used to mean an empty title
288                         # attribute, but that's silly.  Just don't output a title.
289                 } elseif( in_array( 'known', $options ) ) {
290                         $defaults['title'] = $target->getPrefixedText();
291                 } else {
292                         $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
293                 }
294
295                 # Finally, merge the custom attribs with the default ones, and iterate
296                 # over that, deleting all "false" attributes.
297                 $ret = array();
298                 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
299                 foreach( $merged as $key => $val ) {
300                         # A false value suppresses the attribute, and we don't want the
301                         # href attribute to be overridden.
302                         if( $key != 'href' and $val !== false ) {
303                                 $ret[$key] = $val;
304                         }
305                 }
306                 wfProfileOut( __METHOD__ );
307                 return $ret;
308         }
309
310         /**
311          * Default text of the links to the Title $target
312          */
313         private function linkText( $target ) {
314                 # We might be passed a non-Title by make*LinkObj().  Fail gracefully.
315                 if( !$target instanceof Title ) {
316                         return '';
317                 }
318
319                 # If the target is just a fragment, with no title, we return the frag-
320                 # ment text.  Otherwise, we return the title text itself.
321                 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
322                         return htmlspecialchars( $target->getFragment() );
323                 }
324                 return htmlspecialchars( $target->getPrefixedText() );
325         }
326
327         /**
328          * Generate either a normal exists-style link or a stub link, depending
329          * on the given page size.
330          *
331          * @param $size Integer
332          * @param $nt Title object.
333          * @param $text String
334          * @param $query String
335          * @param $trail String
336          * @param $prefix String
337          * @return string HTML of link
338          */
339         function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
340                 global $wgUser;
341                 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
342                 $colour = ( $size < $threshold ) ? 'stub' : '';
343                 // FIXME: replace deprecated makeColouredLinkObj by link()
344                 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
345         }
346
347         /**
348          * Make appropriate markup for a link to the current article. This is currently rendered
349          * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
350          * despite $query not being used.
351          */
352         function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
353                 if ( $text == '' ) {
354                         $text = htmlspecialchars( $nt->getPrefixedText() );
355                 }
356                 list( $inside, $trail ) = Linker::splitTrail( $trail );
357                 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
358         }
359
360         function normaliseSpecialPage( Title $title ) {
361                 if ( $title->getNamespace() == NS_SPECIAL ) {
362                         list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
363                         if ( !$name ) return $title;
364                         $ret = SpecialPage::getTitleFor( $name, $subpage );
365                         $ret->mFragment = $title->getFragment();
366                         return $ret;
367                 } else {
368                         return $title;
369                 }
370         }
371
372         /**
373          * Returns the filename part of an url.
374          * Used as alternative text for external images.
375          */
376         function fnamePart( $url ) {
377                 $basename = strrchr( $url, '/' );
378                 if ( false === $basename ) {
379                         $basename = $url;
380                 } else {
381                         $basename = substr( $basename, 1 );
382                 }
383                 return $basename;
384         }
385
386         /**
387          * Return the code for images which were added via external links,
388          * via Parser::maybeMakeExternalImage().
389          */
390         function makeExternalImage( $url, $alt = '' ) {
391                 if ( $alt == '' ) {
392                         $alt = $this->fnamePart( $url );
393                 }
394                 $img = '';
395                 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
396                 if(!$success) {
397                         wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true);
398                         return $img;
399                 }
400                 return Html::element( 'img',
401                         array(
402                                 'src' => $url,
403                                 'alt' => $alt ) );
404         }
405
406         /**
407          * Given parameters derived from [[Image:Foo|options...]], generate the
408          * HTML that that syntax inserts in the page.
409          *
410          * @param Title $title Title object
411          * @param File $file File object, or false if it doesn't exist
412          *
413          * @param array $frameParams Associative array of parameters external to the media handler.
414          *     Boolean parameters are indicated by presence or absence, the value is arbitrary and
415          *     will often be false.
416          *          thumbnail       If present, downscale and frame
417          *          manualthumb     Image name to use as a thumbnail, instead of automatic scaling
418          *          framed          Shows image in original size in a frame
419          *          frameless       Downscale but don't frame
420          *          upright         If present, tweak default sizes for portrait orientation
421          *          upright_factor  Fudge factor for "upright" tweak (default 0.75)
422          *          border          If present, show a border around the image
423          *          align           Horizontal alignment (left, right, center, none)
424          *          valign          Vertical alignment (baseline, sub, super, top, text-top, middle,
425          *                          bottom, text-bottom)
426          *          alt             Alternate text for image (i.e. alt attribute). Plain text.
427          *          caption         HTML for image caption.
428          *          link-url        URL to link to
429          *          link-title      Title object to link to
430          *          no-link         Boolean, suppress description link
431          *
432          * @param array $handlerParams Associative array of media handler parameters, to be passed
433          *       to transform(). Typical keys are "width" and "page".
434          * @param string $time, timestamp of the file, set as false for current
435          * @param string $query, query params for desc url
436          * @return string HTML for an image, with links, wrappers, etc.
437          */
438         function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
439                 $res = null;
440                 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
441                 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
442                         return $res;
443                 }
444
445                 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
446                 if ( $file && !$file->allowInlineDisplay() ) {
447                         wfDebug( __METHOD__.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
448                         return $this->link( $title );
449                 }
450
451                 // Shortcuts
452                 $fp =& $frameParams;
453                 $hp =& $handlerParams;
454
455                 // Clean up parameters
456                 $page = isset( $hp['page'] ) ? $hp['page'] : false;
457                 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
458                 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
459                 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
460
461                 $prefix = $postfix = '';
462
463                 if ( 'center' == $fp['align'] ) {
464                         $prefix  = '<div class="center">';
465                         $postfix = '</div>';
466                         $fp['align']   = 'none';
467                 }
468                 if ( $file && !isset( $hp['width'] ) ) {
469                         $hp['width'] = $file->getWidth( $page );
470
471                         if( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
472                                 $wopt = $wgUser->getOption( 'thumbsize' );
473
474                                 if( !isset( $wgThumbLimits[$wopt] ) ) {
475                                          $wopt = User::getDefaultOption( 'thumbsize' );
476                                 }
477
478                                 // Reduce width for upright images when parameter 'upright' is used
479                                 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
480                                         $fp['upright'] = $wgThumbUpright;
481                                 }
482                                 // Use width which is smaller: real image width or user preference width
483                                 // 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
484                                 $prefWidth = isset( $fp['upright'] ) ?
485                                         round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
486                                         $wgThumbLimits[$wopt];
487                                 if ( $hp['width'] <= 0 || $prefWidth < $hp['width'] ) {
488                                         $hp['width'] = $prefWidth;
489                                 }
490                         }
491                 }
492
493                 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
494                         # Create a thumbnail. Alignment depends on language
495                         # writing direction, # right aligned for left-to-right-
496                         # languages ("Western languages"), left-aligned
497                         # for right-to-left-languages ("Semitic languages")
498                         #
499                         # If  thumbnail width has not been provided, it is set
500                         # to the default user option as specified in Language*.php
501                         if ( $fp['align'] == '' ) {
502                                 $fp['align'] = $wgContLang->alignEnd();
503                         }
504                         return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
505                 }
506
507                 if ( $file && isset( $fp['frameless'] ) ) {
508                         $srcWidth = $file->getWidth( $page );
509                         # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
510                         # This is the same behaviour as the "thumb" option does it already.
511                         if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
512                                 $hp['width'] = $srcWidth;
513                         }
514                 }
515
516                 if ( $file && $hp['width'] ) {
517                         # Create a resized image, without the additional thumbnail features
518                         $thumb = $file->transform( $hp );
519                 } else {
520                         $thumb = false;
521                 }
522
523                 if ( !$thumb ) {
524                         $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time==true );
525                 } else {
526                         $params = array(
527                                 'alt' => $fp['alt'],
528                                 'title' => $fp['title'],
529                                 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
530                                 'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false );
531                         if ( !empty( $fp['link-url'] ) ) {
532                                 $params['custom-url-link'] = $fp['link-url'];
533                         } elseif ( !empty( $fp['link-title'] ) ) {
534                                 $params['custom-title-link'] = $fp['link-title'];
535                         } elseif ( !empty( $fp['no-link'] ) ) {
536                                 // No link
537                         } else {
538                                 $params['desc-link'] = true;
539                                 $params['desc-query'] = $query;
540                         }
541
542                         $s = $thumb->toHtml( $params );
543                 }
544                 if ( $fp['align'] != '' ) {
545                         $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
546                 }
547                 return str_replace("\n", ' ',$prefix.$s.$postfix);
548         }
549
550         /**
551          * Make HTML for a thumbnail including image, border and caption
552          * @param Title $title
553          * @param File $file File object or false if it doesn't exist
554          */
555         function makeThumbLinkObj( Title $title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
556                 $frameParams = array(
557                         'alt' => $alt,
558                         'caption' => $label,
559                         'align' => $align
560                 );
561                 if ( $framed ) $frameParams['framed'] = true;
562                 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
563                 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
564         }
565
566         function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
567                 global $wgStylePath, $wgContLang;
568                 $exists = $file && $file->exists();
569
570                 # Shortcuts
571                 $fp =& $frameParams;
572                 $hp =& $handlerParams;
573
574                 $page = isset( $hp['page'] ) ? $hp['page'] : false;
575                 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
576                 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
577                 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
578                 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
579
580                 if ( empty( $hp['width'] ) ) {
581                         // Reduce width for upright images when parameter 'upright' is used
582                         $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
583                 }
584                 $thumb = false;
585
586                 if ( !$exists ) {
587                         $outerWidth = $hp['width'] + 2;
588                 } else {
589                         if ( isset( $fp['manualthumb'] ) ) {
590                                 # Use manually specified thumbnail
591                                 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
592                                 if( $manual_title ) {
593                                         $manual_img = wfFindFile( $manual_title );
594                                         if ( $manual_img ) {
595                                                 $thumb = $manual_img->getUnscaledThumb();
596                                         } else {
597                                                 $exists = false;
598                                         }
599                                 }
600                         } elseif ( isset( $fp['framed'] ) ) {
601                                 // Use image dimensions, don't scale
602                                 $thumb = $file->getUnscaledThumb( $page );
603                         } else {
604                                 # Do not present an image bigger than the source, for bitmap-style images
605                                 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
606                                 $srcWidth = $file->getWidth( $page );
607                                 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
608                                         $hp['width'] = $srcWidth;
609                                 }
610                                 $thumb = $file->transform( $hp );
611                         }
612
613                         if ( $thumb ) {
614                                 $outerWidth = $thumb->getWidth() + 2;
615                         } else {
616                                 $outerWidth = $hp['width'] + 2;
617                         }
618                 }
619
620                 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
621                 # So we don't need to pass it here in $query. However, the URL for the
622                 # zoom icon still needs it, so we make a unique query for it. See bug 14771
623                 $url = $title->getLocalURL( $query );
624                 if( $page ) {
625                         $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
626                 }
627
628                 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
629
630                 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
631                 if( !$exists ) {
632                         $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time==true );
633                         $zoomicon = '';
634                 } elseif ( !$thumb ) {
635                         $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
636                         $zoomicon = '';
637                 } else {
638                         $s .= $thumb->toHtml( array(
639                                 'alt' => $fp['alt'],
640                                 'title' => $fp['title'],
641                                 'img-class' => 'thumbimage',
642                                 'desc-link' => true,
643                                 'desc-query' => $query ) );
644                         if ( isset( $fp['framed'] ) ) {
645                                 $zoomicon="";
646                         } else {
647                                 $zoomicon =  '<div class="magnify">'.
648                                         '<a href="'.$url.'" class="internal" title="'.$more.'">'.
649                                         '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
650                                         'width="15" height="11" alt="" /></a></div>';
651                         }
652                 }
653                 $s .= '  <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
654                 return str_replace("\n", ' ', $s);
655         }
656
657         /**
658          * Make a "broken" link to an image
659          *
660          * @param Title $title Image title
661          * @param string $text Link label
662          * @param string $query Query string
663          * @param string $trail Link trail
664          * @param string $prefix Link prefix
665          * @param bool $time, a file of a certain timestamp was requested
666          * @return string
667          */
668         public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
669                 global $wgEnableUploads, $wgUploadNavigationUrl;
670                 if( $title instanceof Title ) {
671                         wfProfileIn( __METHOD__ );
672                         $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
673                         if( ( $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
674                                 if( $text == '' )
675                                         $text = htmlspecialchars( $title->getPrefixedText() );
676
677                                 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
678                                 if( $redir ) {
679                                         wfProfileOut( __METHOD__ );
680                                         return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
681                                 }
682                                 
683                                 $href = $this->getUploadUrl( $title, $query );
684
685
686                                 list( $inside, $trail ) = self::splitTrail( $trail );
687
688                                 wfProfileOut( __METHOD__ );
689                                 return Html::element( 'a', array(
690                                         'href' => $href,
691                                         'class' => 'new',
692                                         'title' => $title->getPrefixedText()
693                                 ), $prefix . $text . $inside ) . $trail;
694                         } else {
695                                 wfProfileOut( __METHOD__ );
696                                 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
697                         }
698                 } else {
699                         return "<!-- ERROR -->{$prefix}{$text}{$trail}";
700                 }
701         }
702         
703         /**
704          * Get the URL to upload a certain file
705          * 
706          * @param $destFile Title Title of the file to upload
707          * @param $query string Urlencoded query string to prepend
708          * @return string Urlencoded URL
709          */
710         protected function getUploadUrl( $destFile, $query = '' ) {
711                 global $wgUploadNavigationUrl;
712                 $q = 'wpDestFile=' . $destFile->getPartialUrl();
713                 if( $query != '' )
714                         $q .= '&' . $query;
715
716                 if( $wgUploadNavigationUrl ) {
717                         return wfAppendQuery( $wgUploadNavigationUrl, $q );
718                 } else {
719                         $upload = SpecialPage::getTitleFor( 'Upload' );
720                         return $upload->getLocalUrl( $q );
721                 }       
722         }
723
724         /**
725          * Create a direct link to a given uploaded file.
726          *
727          * @param $title Title object.
728          * @param $text String: pre-sanitized HTML
729          * @param $time string: time image was created
730          * @return string HTML
731          *
732          * @public
733          * @todo Handle invalid or missing images better.
734          */
735         function makeMediaLinkObj( $title, $text = '', $time = false ) {
736                 if( is_null( $title ) ) {
737                         ### HOTFIX. Instead of breaking, return empty string.
738                         return $text;
739                 } else {
740                         $img  = wfFindFile( $title, array( 'time' => $time ) );
741                         if( $img ) {
742                                 $url  = $img->getURL();
743                                 $class = 'internal';
744                         } else {
745                                 $url = $this->getUploadUrl( $title );
746                                 $class = 'new';
747                         }
748                         $alt = htmlspecialchars( $title->getText() );
749                         if( $text == '' ) {
750                                 $text = $alt;
751                         }
752                         $u = htmlspecialchars( $url );
753                         return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
754                 }
755         }
756
757         /**
758          *  Make a link to a special page given its name and, optionally,
759          * a message key from the link text.
760          * Usage example: $skin->specialLink( 'recentchanges' )
761          */
762         function specialLink( $name, $key = '' ) {
763                 global $wgContLang;
764
765                 if ( $key == '' ) { $key = strtolower( $name ); }
766                 $pn = $wgContLang->ucfirst( $name );
767                 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
768                   wfMsg( $key ) );
769         }
770
771         /**
772          * Make an external link
773          * @param String $url URL to link to
774          * @param String $text text of link
775          * @param boolean $escape Do we escape the link text?
776          * @param String $linktype Type of external link. Gets added to the classes
777          * @param array $attribs Array of extra attributes to <a>
778          *
779          * @todo FIXME: This is a really crappy implementation. $linktype and
780          * 'external' are mashed into the class attrib for the link (which is made
781          * into a string). Then, if we've got additional params in $attribs, we
782          * add to it. People using this might want to change the classes (or other
783          * default link attributes), but passing $attribsText is just messy. Would
784          * make a lot more sense to make put the classes into $attribs, let the
785          * hook play with them, *then* expand it all at once.
786          */
787         function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
788                 if ( isset( $attribs[ 'class' ] ) ) $class = $attribs[ 'class' ]; # yet another hack :(
789                 else $class =  'external ' . $linktype;
790
791                 $attribsText = $this->getExternalLinkAttributes( $class );
792                 $url = htmlspecialchars( $url );
793                 if( $escape ) {
794                         $text = htmlspecialchars( $text );
795                 }
796                 $link = '';
797                 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
798                 if(!$success) {
799                         wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
800                         return $link;
801                 }
802                 if ( $attribs ) {
803                         $attribsText .= Html::expandAttributes( $attribs );
804                 }
805                 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
806         }
807
808         /**
809          * Make user link (or user contributions for unregistered users)
810          * @param $userId   Integer: user id in database.
811          * @param $userText String: user name in database
812          * @return string HTML fragment
813          * @private
814          */
815         function userLink( $userId, $userText ) {
816                 if( $userId == 0 ) {
817                         $page = SpecialPage::getTitleFor( 'Contributions', $userText );
818                 } else {
819                         $page = Title::makeTitle( NS_USER, $userText );
820                 }
821                 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
822         }
823
824         /**
825          * Generate standard user tool links (talk, contributions, block link, etc.)
826          *
827          * @param int $userId User identifier
828          * @param string $userText User name or IP address
829          * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
830          * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
831          * @param int $edits, user edit count (optional, for performance)
832          * @return string
833          */
834         public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
835                 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
836                 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
837                 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
838
839                 $items = array();
840                 if( $talkable ) {
841                         $items[] = $this->userTalkLink( $userId, $userText );
842                 }
843                 if( $userId ) {
844                         // check if the user has an edit
845                         $attribs = array();
846                         if( $redContribsWhenNoEdits ) {
847                                 $count = !is_null($edits) ? $edits : User::edits( $userId );
848                                 if( $count == 0 ) {
849                                         $attribs['class'] = 'new';
850                                 }
851                         }
852                         $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
853
854                         $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
855                 }
856                 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
857                         $items[] = $this->blockLink( $userId, $userText );
858                 }
859
860                 if( $items ) {
861                         return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
862                 } else {
863                         return '';
864                 }
865         }
866
867         /**
868          * Alias for userToolLinks( $userId, $userText, true );
869          * @param int $userId User identifier
870          * @param string $userText User name or IP address
871          * @param int $edits, user edit count (optional, for performance)
872          */
873         public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
874                 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
875         }
876
877
878         /**
879          * @param $userId Integer: user id in database.
880          * @param $userText String: user name in database.
881          * @return string HTML fragment with user talk link
882          * @private
883          */
884         function userTalkLink( $userId, $userText ) {
885                 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
886                 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
887                 return $userTalkLink;
888         }
889
890         /**
891          * @param $userId Integer: userid
892          * @param $userText String: user name in database.
893          * @return string HTML fragment with block link
894          * @private
895          */
896         function blockLink( $userId, $userText ) {
897                 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
898                 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
899                 return $blockLink;
900         }
901
902         /**
903          * Generate a user link if the current user is allowed to view it
904          * @param $rev Revision object.
905          * @param $isPublic, bool, show only if all users can see it
906          * @return string HTML
907          */
908         function revUserLink( $rev, $isPublic = false ) {
909                 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
910                         $link = wfMsgHtml( 'rev-deleted-user' );
911                 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
912                         $link = $this->userLink( $rev->getUser( Revision::FOR_THIS_USER ),
913                                 $rev->getUserText( Revision::FOR_THIS_USER ) );
914                 } else {
915                         $link = wfMsgHtml( 'rev-deleted-user' );
916                 }
917                 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
918                         return '<span class="history-deleted">' . $link . '</span>';
919                 }
920                 return $link;
921         }
922
923         /**
924          * Generate a user tool link cluster if the current user is allowed to view it
925          * @param $rev Revision object.
926          * @param $isPublic, bool, show only if all users can see it
927          * @return string HTML
928          */
929         function revUserTools( $rev, $isPublic = false ) {
930                 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
931                         $link = wfMsgHtml( 'rev-deleted-user' );
932                 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
933                         $userId = $rev->getUser( Revision::FOR_THIS_USER );
934                         $userText = $rev->getUserText( Revision::FOR_THIS_USER );
935                         $link = $this->userLink( $userId, $userText ) .
936                                 ' ' . $this->userToolLinks( $userId, $userText );
937                 } else {
938                         $link = wfMsgHtml( 'rev-deleted-user' );
939                 }
940                 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
941                         return ' <span class="history-deleted">' . $link . '</span>';
942                 }
943                 return $link;
944         }
945
946         /**
947          * This function is called by all recent changes variants, by the page history,
948          * and by the user contributions list. It is responsible for formatting edit
949          * comments. It escapes any HTML in the comment, but adds some CSS to format
950          * auto-generated comments (from section editing) and formats [[wikilinks]].
951          *
952          * @author Erik Moeller <moeller@scireview.de>
953          *
954          * Note: there's not always a title to pass to this function.
955          * Since you can't set a default parameter for a reference, I've turned it
956          * temporarily to a value pass. Should be adjusted further. --brion
957          *
958          * @param string $comment
959          * @param mixed $title Title object (to generate link to the section in autocomment) or null
960          * @param bool $local Whether section links should refer to local page
961          */
962         function formatComment($comment, $title = null, $local = false) {
963                 wfProfileIn( __METHOD__ );
964
965                 # Sanitize text a bit:
966                 $comment = str_replace( "\n", " ", $comment );
967                 # Allow HTML entities (for bug 13815)
968                 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
969
970                 # Render autocomments and make links:
971                 $comment = $this->formatAutocomments( $comment, $title, $local );
972                 $comment = $this->formatLinksInComment( $comment, $title, $local );
973
974                 wfProfileOut( __METHOD__ );
975                 return $comment;
976         }
977
978         /**
979          * The pattern for autogen comments is / * foo * /, which makes for
980          * some nasty regex.
981          * We look for all comments, match any text before and after the comment,
982          * add a separator where needed and format the comment itself with CSS
983          * Called by Linker::formatComment.
984          *
985          * @param string $comment Comment text
986          * @param object $title An optional title object used to links to sections
987          * @return string $comment formatted comment
988          *
989          * @todo Document the $local parameter.
990          */
991         private function formatAutocomments( $comment, $title = null, $local = false ) {
992                 // Bah!
993                 $this->autocommentTitle = $title;
994                 $this->autocommentLocal = $local;
995                 $comment = preg_replace_callback(
996                         '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
997                         array( $this, 'formatAutocommentsCallback' ),
998                         $comment );
999                 unset( $this->autocommentTitle );
1000                 unset( $this->autocommentLocal );
1001                 return $comment;
1002         }
1003
1004         private function formatAutocommentsCallback( $match ) {
1005                 $title = $this->autocommentTitle;
1006                 $local = $this->autocommentLocal;
1007
1008                 $pre = $match[1];
1009                 $auto = $match[2];
1010                 $post = $match[3];
1011                 $link = '';
1012                 if ( $title ) {
1013                         $section = $auto;
1014
1015                         # Generate a valid anchor name from the section title.
1016                         # Hackish, but should generally work - we strip wiki
1017                         # syntax, including the magic [[: that is used to
1018                         # "link rather than show" in case of images and
1019                         # interlanguage links.
1020                         $section = str_replace( '[[:', '', $section );
1021                         $section = str_replace( '[[', '', $section );
1022                         $section = str_replace( ']]', '', $section );
1023                         if ( $local ) {
1024                                 $sectionTitle = Title::newFromText( '#' . $section );
1025                         } else {
1026                                 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1027                                         $title->getDBkey(), $section );
1028                         }
1029                         if ( $sectionTitle ) {
1030                                 $link = $this->link( $sectionTitle,
1031                                         htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1032                                         'noclasses' );
1033                         } else {
1034                                 $link = '';
1035                         }
1036                 }
1037                 $auto = "$link$auto";
1038                 if( $pre ) {
1039                         # written summary $presep autocomment (summary /* section */)
1040                         $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1041                 }
1042                 if( $post ) {
1043                         # autocomment $postsep written summary (/* section */ summary)
1044                         $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1045                 }
1046                 $auto = '<span class="autocomment">' . $auto . '</span>';
1047                 $comment = $pre . $auto . $post;
1048                 return $comment;
1049         }
1050
1051         /**
1052          * Formats wiki links and media links in text; all other wiki formatting
1053          * is ignored
1054          *
1055          * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1056          * @param string $comment Text to format links in
1057          * @return string
1058          */
1059         public function formatLinksInComment( $comment, $title = null, $local = false ) {
1060                 $this->commentContextTitle = $title;
1061                 $this->commentLocal = $local;
1062                 $html = preg_replace_callback(
1063                         '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1064                         array( $this, 'formatLinksInCommentCallback' ),
1065                         $comment );
1066                 unset( $this->commentContextTitle );
1067                 unset( $this->commentLocal );
1068                 return $html;
1069         }
1070
1071         protected function formatLinksInCommentCallback( $match ) {
1072                 global $wgContLang;
1073
1074                 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1075                 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1076
1077                 $comment = $match[0];
1078
1079                 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1080                 if( strpos( $match[1], '%' ) !== false ) {
1081                         $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1082                 }
1083
1084                 # Handle link renaming [[foo|text]] will show link as "text"
1085                 if( $match[3] != "" ) {
1086                         $text = $match[3];
1087                 } else {
1088                         $text = $match[1];
1089                 }
1090                 $submatch = array();
1091                 $thelink = null;
1092                 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1093                         # Media link; trail not supported.
1094                         $linkRegexp = '/\[\[(.*?)\]\]/';
1095                         $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1096                         $thelink = $this->makeMediaLinkObj( $title, $text );
1097                 } else {
1098                         # Other kind of link
1099                         if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1100                                 $trail = $submatch[1];
1101                         } else {
1102                                 $trail = "";
1103                         }
1104                         $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1105                         if (isset($match[1][0]) && $match[1][0] == ':')
1106                                 $match[1] = substr($match[1], 1);
1107                         list( $inside, $trail ) = Linker::splitTrail( $trail );
1108
1109                         $linkText = $text;
1110                         $linkTarget = Linker::normalizeSubpageLink( $this->commentContextTitle,
1111                                 $match[1], $linkText );
1112
1113                         $target = Title::newFromText( $linkTarget );
1114                         if( $target ) {
1115                                 if( $target->getText() == '' && !$this->commentLocal && $this->commentContextTitle ) {
1116                                         $newTarget = clone( $this->commentContextTitle );
1117                                         $newTarget->setFragment( '#' . $target->getFragment() );
1118                                         $target = $newTarget;
1119                                 }
1120                                 $thelink = $this->link(
1121                                         $target,
1122                                         $linkText . $inside
1123                                 ) . $trail;
1124                         }
1125                 }
1126                 if( $thelink ) {
1127                         // If the link is still valid, go ahead and replace it in!
1128                         $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1129                 }
1130
1131                 return $comment;
1132         }
1133
1134         static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1135                 # Valid link forms:
1136                 # Foobar -- normal
1137                 # :Foobar -- override special treatment of prefix (images, language links)
1138                 # /Foobar -- convert to CurrentPage/Foobar
1139                 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1140                 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1141                 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1142
1143                 wfProfileIn( __METHOD__ );
1144                 $ret = $target; # default return value is no change
1145
1146                 # Some namespaces don't allow subpages,
1147                 # so only perform processing if subpages are allowed
1148                 if( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1149                         $hash = strpos( $target, '#' );
1150                         if( $hash !== false ) {
1151                                 $suffix = substr( $target, $hash );
1152                                 $target = substr( $target, 0, $hash );
1153                         } else {
1154                                 $suffix = '';
1155                         }
1156                         # bug 7425
1157                         $target = trim( $target );
1158                         # Look at the first character
1159                         if( $target != '' && $target{0} === '/' ) {
1160                                 # / at end means we don't want the slash to be shown
1161                                 $m = array();
1162                                 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1163                                 if( $trailingSlashes ) {
1164                                         $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1165                                 } else {
1166                                         $noslash = substr( $target, 1 );
1167                                 }
1168
1169                                 $ret = $contextTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1170                                 if( $text === '' ) {
1171                                         $text = $target . $suffix;
1172                                 } # this might be changed for ugliness reasons
1173                         } else {
1174                                 # check for .. subpage backlinks
1175                                 $dotdotcount = 0;
1176                                 $nodotdot = $target;
1177                                 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1178                                         ++$dotdotcount;
1179                                         $nodotdot = substr( $nodotdot, 3 );
1180                                 }
1181                                 if($dotdotcount > 0) {
1182                                         $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1183                                         if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1184                                                 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1185                                                 # / at the end means don't show full path
1186                                                 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1187                                                         $nodotdot = substr( $nodotdot, 0, -1 );
1188                                                         if( $text === '' ) {
1189                                                                 $text = $nodotdot . $suffix;
1190                                                         }
1191                                                 }
1192                                                 $nodotdot = trim( $nodotdot );
1193                                                 if( $nodotdot != '' ) {
1194                                                         $ret .= '/' . $nodotdot;
1195                                                 }
1196                                                 $ret .= $suffix;
1197                                         }
1198                                 }
1199                         }
1200                 }
1201
1202                 wfProfileOut( __METHOD__ );
1203                 return $ret;
1204         }
1205
1206         /**
1207          * Wrap a comment in standard punctuation and formatting if
1208          * it's non-empty, otherwise return empty string.
1209          *
1210          * @param string $comment
1211          * @param mixed $title Title object (to generate link to section in autocomment) or null
1212          * @param bool $local Whether section links should refer to local page
1213          *
1214          * @return string
1215          */
1216         function commentBlock( $comment, $title = null, $local = false ) {
1217                 // '*' used to be the comment inserted by the software way back
1218                 // in antiquity in case none was provided, here for backwards
1219                 // compatability, acc. to brion -ævar
1220                 if( $comment == '' || $comment == '*' ) {
1221                         return '';
1222                 } else {
1223                         $formatted = $this->formatComment( $comment, $title, $local );
1224                         return " <span class=\"comment\">($formatted)</span>";
1225                 }
1226         }
1227
1228         /**
1229          * Wrap and format the given revision's comment block, if the current
1230          * user is allowed to view it.
1231          *
1232          * @param Revision $rev
1233          * @param bool $local Whether section links should refer to local page
1234          * @param $isPublic, show only if all users can see it
1235          * @return string HTML
1236          */
1237         function revComment( Revision $rev, $local = false, $isPublic = false ) {
1238                 if( $rev->getRawComment() == "" ) return "";
1239                 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1240                         $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1241                 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1242                         $block = $this->commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1243                                 $rev->getTitle(), $local );
1244                 } else {
1245                         $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1246                 }
1247                 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1248                         return " <span class=\"history-deleted\">$block</span>";
1249                 }
1250                 return $block;
1251         }
1252
1253         public function formatRevisionSize( $size ) {
1254                 if ( $size == 0 ) {
1255                         $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1256                 } else {
1257                         global $wgLang;
1258                         $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1259                         $stxt = "($stxt)";
1260                 }
1261                 $stxt = htmlspecialchars( $stxt );
1262                 return "<span class=\"history-size\">$stxt</span>";
1263         }
1264
1265         /**
1266          * Add another level to the Table of Contents
1267          */
1268         function tocIndent() {
1269                 return "\n<ul>";
1270         }
1271
1272         /**
1273          * Finish one or more sublevels on the Table of Contents
1274          */
1275         function tocUnindent($level) {
1276                 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1277         }
1278
1279         /**
1280          * parameter level defines if we are on an indentation level
1281          */
1282         function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1283                 $classes = "toclevel-$level";
1284                 if ( $sectionIndex !== false )
1285                         $classes .= " tocsection-$sectionIndex";
1286                 return "\n<li class=\"$classes\"><a href=\"#" .
1287                         $anchor . '"><span class="tocnumber">' .
1288                         $tocnumber . '</span> <span class="toctext">' .
1289                         $tocline . '</span></a>';
1290         }
1291
1292         /**
1293          * End a Table Of Contents line.
1294          * tocUnindent() will be used instead if we're ending a line below
1295          * the new level.
1296          */
1297         function tocLineEnd() {
1298                 return "</li>\n";
1299         }
1300
1301         /**
1302          * Wraps the TOC in a table and provides the hide/collapse javascript.
1303          * @param string $toc html of the Table Of Contents
1304          * @return string Full html of the TOC
1305          */
1306         function tocList($toc) {
1307                 $title = wfMsgHtml('toc') ;
1308                 return
1309                    '<table id="toc" class="toc"><tr><td>'
1310                  . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1311                  . $toc
1312                  # no trailing newline, script should not be wrapped in a
1313                  # paragraph
1314                  . "</ul>\n</td></tr></table>"
1315                  . Html::inlineScript(
1316                         'if (window.showTocToggle) {'
1317                         . ' var tocShowText = "' . Xml::escapeJsString( wfMsg('showtoc') ) . '";'
1318                         . ' var tocHideText = "' . Xml::escapeJsString( wfMsg('hidetoc') ) . '";'
1319                         . ' showTocToggle();'
1320                         . ' } ' )
1321                 . "\n";
1322         }
1323
1324         /**
1325          * Generate a table of contents from a section tree
1326          * Currently unused.
1327          * @param $tree Return value of ParserOutput::getSections()
1328          * @return string HTML
1329          */
1330         public function generateTOC( $tree ) {
1331                 $toc = '';
1332                 $lastLevel = 0;
1333                 foreach ( $tree as $section ) {
1334                         if ( $section['toclevel'] > $lastLevel )
1335                                 $toc .= $this->tocIndent();
1336                         else if ( $section['toclevel'] < $lastLevel )
1337                                 $toc .= $this->tocUnindent(
1338                                         $lastLevel - $section['toclevel'] );
1339                         else
1340                                 $toc .= $this->tocLineEnd();
1341
1342                         $toc .= $this->tocLine( $section['anchor'],
1343                                 $section['line'], $section['number'],
1344                                 $section['toclevel'], $section['index'] );
1345                         $lastLevel = $section['toclevel'];
1346                 }
1347                 $toc .= $this->tocLineEnd();
1348                 return $this->tocList( $toc );
1349         }
1350
1351         /**
1352          * Create a section edit link.  This supersedes editSectionLink() and
1353          * editSectionLinkForOther().
1354          *
1355          * @param $nt      Title  The title being linked to (may not be the same as
1356          *   $wgTitle, if the section is included from a template)
1357          * @param $section string The designation of the section being pointed to,
1358          *   to be included in the link, like "&section=$section"
1359          * @param $tooltip string The tooltip to use for the link: will be escaped
1360          *   and wrapped in the 'editsectionhint' message
1361          * @return         string HTML to use for edit link
1362          */
1363         public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1364                 // HTML generated here should probably have userlangattributes
1365                 // added to it for LTR text on RTL pages
1366                 $attribs = array();
1367                 if( !is_null( $tooltip ) ) {
1368                         $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1369                 }
1370                 $link = $this->link( $nt, wfMsg('editsection'),
1371                         $attribs,
1372                         array( 'action' => 'edit', 'section' => $section ),
1373                         array( 'noclasses', 'known' )
1374                 );
1375
1376                 # Run the old hook.  This takes up half of the function . . . hopefully
1377                 # we can rid of it someday.
1378                 $attribs = '';
1379                 if( $tooltip ) {
1380                         $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1381                         $attribs = " title=\"$attribs\"";
1382                 }
1383                 $result = null;
1384                 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1385                 if( !is_null( $result ) ) {
1386                         # For reverse compatibility, add the brackets *after* the hook is
1387                         # run, and even add them to hook-provided text.  (This is the main
1388                         # reason that the EditSectionLink hook is deprecated in favor of
1389                         # DoEditSectionLink: it can't change the brackets or the span.)
1390                         $result = wfMsgHtml( 'editsection-brackets', $result );
1391                         return "<span class=\"editsection\">$result</span>";
1392                 }
1393
1394                 # Add the brackets and the span, and *then* run the nice new hook, with
1395                 # clean and non-redundant arguments.
1396                 $result = wfMsgHtml( 'editsection-brackets', $link );
1397                 $result = "<span class=\"editsection\">$result</span>";
1398
1399                 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1400                 return $result;
1401         }
1402
1403         /**
1404          * Create a headline for content
1405          *
1406          * @param int    $level   The level of the headline (1-6)
1407          * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1408          *                        This *must* be at least '>' for no attribs
1409          * @param string $anchor  The anchor to give the headline (the bit after the #)
1410          * @param string $text    The text of the header
1411          * @param string $link    HTML to add for the section edit link
1412          * @param mixed  $legacyAnchor A second, optional anchor to give for
1413          *   backward compatibility (false to omit)
1414          *
1415          * @return string HTML headline
1416          */
1417         public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1418                 $ret = "<h$level$attribs"
1419                         . $link
1420                         . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1421                         . "</h$level>";
1422                 if ( $legacyAnchor !== false ) {
1423                         $ret = "<a id=\"$legacyAnchor\"></a>$ret";
1424                 }
1425                 return $ret;
1426         }
1427
1428         /**
1429          * Split a link trail, return the "inside" portion and the remainder of the trail
1430          * as a two-element array
1431          *
1432          * @static
1433          */
1434         static function splitTrail( $trail ) {
1435                 static $regex = false;
1436                 if ( $regex === false ) {
1437                         global $wgContLang;
1438                         $regex = $wgContLang->linkTrail();
1439                 }
1440                 $inside = '';
1441                 if ( $trail != '' ) {
1442                         $m = array();
1443                         if ( preg_match( $regex, $trail, $m ) ) {
1444                                 $inside = $m[1];
1445                                 $trail = $m[2];
1446                         }
1447                 }
1448                 return array( $inside, $trail );
1449         }
1450
1451         /**
1452          * Generate a rollback link for a given revision.  Currently it's the
1453          * caller's responsibility to ensure that the revision is the top one. If
1454          * it's not, of course, the user will get an error message.
1455          *
1456          * If the calling page is called with the parameter &bot=1, all rollback
1457          * links also get that parameter. It causes the edit itself and the rollback
1458          * to be marked as "bot" edits. Bot edits are hidden by default from recent
1459          * changes, so this allows sysops to combat a busy vandal without bothering
1460          * other users.
1461          *
1462          * @param Revision $rev
1463          */
1464         function generateRollback( $rev ) {
1465                 return '<span class="mw-rollback-link">['
1466                         . $this->buildRollbackLink( $rev )
1467                         . ']</span>';
1468         }
1469
1470         /**
1471          * Build a raw rollback link, useful for collections of "tool" links
1472          *
1473          * @param Revision $rev
1474          * @return string
1475          */
1476         public function buildRollbackLink( $rev ) {
1477                 global $wgRequest, $wgUser;
1478                 $title = $rev->getTitle();
1479                 $query = array(
1480                         'action' => 'rollback',
1481                         'from' => $rev->getUserText()
1482                 );
1483                 if( $wgRequest->getBool( 'bot' ) ) {
1484                         $query['bot'] = '1';
1485                         $query['hidediff'] = '1'; // bug 15999
1486                 }
1487                 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1488                         $rev->getUserText() ) );
1489                 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1490                         array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1491                         $query, array( 'known', 'noclasses' ) );
1492         }
1493
1494         /**
1495          * Returns HTML for the "templates used on this page" list.
1496          *
1497          * @param array $templates Array of templates from Article::getUsedTemplate
1498          * or similar
1499          * @param bool $preview Whether this is for a preview
1500          * @param bool $section Whether this is for a section edit
1501          * @return string HTML output
1502          */
1503         public function formatTemplates( $templates, $preview = false, $section = false ) {
1504                 wfProfileIn( __METHOD__ );
1505
1506                 $outText = '';
1507                 if ( count( $templates ) > 0 ) {
1508                         # Do a batch existence check
1509                         $batch = new LinkBatch;
1510                         foreach( $templates as $title ) {
1511                                 $batch->addObj( $title );
1512                         }
1513                         $batch->execute();
1514
1515                         # Construct the HTML
1516                         $outText = '<div class="mw-templatesUsedExplanation">';
1517                         if ( $preview ) {
1518                                 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1519                         } elseif ( $section ) {
1520                                 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1521                         } else {
1522                                 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1523                         }
1524                         $outText .= "</div><ul>\n";
1525
1526                         usort( $templates, array( 'Title', 'compare' ) );
1527                         foreach ( $templates as $titleObj ) {
1528                                 $r = $titleObj->getRestrictions( 'edit' );
1529                                 if ( in_array( 'sysop', $r ) ) {
1530                                         $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1531                                 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1532                                         $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1533                                 } else {
1534                                         $protected = '';
1535                                 }
1536                                 if( $titleObj->quickUserCan( 'edit' ) ) {
1537                                         $editLink = $this->link(
1538                                                 $titleObj,
1539                                                 wfMsg( 'editlink' ),
1540                                                 array(),
1541                                                 array( 'action' => 'edit' )
1542                                         );
1543                                 } else {
1544                                         $editLink = $this->link(
1545                                                 $titleObj,
1546                                                 wfMsg( 'viewsourcelink' ),
1547                                                 array(),
1548                                                 array( 'action' => 'edit' )
1549                                         );
1550                                 }
1551                                 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1552                         }
1553                         $outText .= '</ul>';
1554                 }
1555                 wfProfileOut( __METHOD__  );
1556                 return $outText;
1557         }
1558
1559         /**
1560          * Returns HTML for the "hidden categories on this page" list.
1561          *
1562          * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1563          * or similar
1564          * @return string HTML output
1565          */
1566         public function formatHiddenCategories( $hiddencats ) {
1567                 global $wgLang;
1568                 wfProfileIn( __METHOD__ );
1569
1570                 $outText = '';
1571                 if ( count( $hiddencats ) > 0 ) {
1572                         # Construct the HTML
1573                         $outText = '<div class="mw-hiddenCategoriesExplanation">';
1574                         $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1575                         $outText .= "</div><ul>\n";
1576
1577                         foreach ( $hiddencats as $titleObj ) {
1578                                 $outText .= '<li>' . $this->link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1579                         }
1580                         $outText .= '</ul>';
1581                 }
1582                 wfProfileOut( __METHOD__  );
1583                 return $outText;
1584         }
1585
1586         /**
1587          * Format a size in bytes for output, using an appropriate
1588          * unit (B, KB, MB or GB) according to the magnitude in question
1589          *
1590          * @param $size Size to format
1591          * @return string
1592          */
1593         public function formatSize( $size ) {
1594                 global $wgLang;
1595                 return htmlspecialchars( $wgLang->formatSize( $size ) );
1596         }
1597
1598         /**
1599          * Given the id of an interface element, constructs the appropriate title
1600          * attribute from the system messages.  (Note, this is usually the id but
1601          * isn't always, because sometimes the accesskey needs to go on a different
1602          * element than the id, for reverse-compatibility, etc.)
1603          *
1604          * @param string $name    Id of the element, minus prefixes.
1605          * @param mixed  $options null or the string 'withaccess' to add an access-
1606          *   key hint
1607          * @return string Contents of the title attribute (which you must HTML-
1608          *   escape), or false for no title attribute
1609          */
1610         public function titleAttrib( $name, $options = null ) {
1611                 wfProfileIn( __METHOD__ );
1612
1613                 $tooltip = wfMsg( "tooltip-$name" );
1614                 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1615                 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1616
1617                 # Message equal to '-' means suppress it.
1618                 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) || $tooltip == '-' ) {
1619                         $tooltip = false;
1620                 }
1621
1622                 if ( $options == 'withaccess' ) {
1623                         $accesskey = $this->accesskey( $name );
1624                         if( $accesskey !== false ) {
1625                                 if ( $tooltip === false || $tooltip === '' ) {
1626                                         $tooltip = "[$accesskey]";
1627                                 } else {
1628                                         $tooltip .= " [$accesskey]";
1629                                 }
1630                         }
1631                 }
1632
1633                 wfProfileOut( __METHOD__ );
1634                 return $tooltip;
1635         }
1636
1637         /**
1638          * Given the id of an interface element, constructs the appropriate
1639          * accesskey attribute from the system messages.  (Note, this is usually
1640          * the id but isn't always, because sometimes the accesskey needs to go on
1641          * a different element than the id, for reverse-compatibility, etc.)
1642          *
1643          * @param string $name    Id of the element, minus prefixes.
1644          * @return string Contents of the accesskey attribute (which you must HTML-
1645          *   escape), or false for no accesskey attribute
1646          */
1647         public function accesskey( $name ) {
1648                 wfProfileIn( __METHOD__ );
1649
1650                 $accesskey = wfMsg( "accesskey-$name" );
1651
1652                 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1653                 # attribute, but this is broken for accesskey: that might be a useful
1654                 # value.
1655                 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1656                         wfProfileOut( __METHOD__ );
1657                         return $accesskey;
1658                 }
1659
1660                 wfProfileOut( __METHOD__ );
1661                 return false;
1662         }
1663
1664         /**
1665          * Creates a (show/hide) link for deleting revisions/log entries
1666          *
1667          * @param array $query  Query parameters to be passed to link()
1668          * @param bool $restricted  Set to true to use a <strong> instead of a <span>
1669          * @param bool $delete Set to true to use (show/hide) rather than (show)
1670          *
1671          * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1672          * span to allow for customization of appearance with CSS
1673          */
1674         public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1675                 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1676                 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1677                 $tag = $restricted ? 'strong' : 'span';
1678                 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1679                 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1680         }
1681
1682         /**
1683          * Creates a dead (show/hide) link for deleting revisions/log entries
1684          *
1685          * @param bool $delete Set to true to use (show/hide) rather than (show)
1686          *
1687          * @return string HTML text wrapped in a span to allow for customization
1688          * of appearance with CSS
1689          */
1690         public function revDeleteLinkDisabled( $delete = true ) {
1691                 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1692                 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1693         }
1694
1695         /* Deprecated methods */
1696
1697         /**
1698          * @deprecated
1699          */
1700         function postParseLinkColour( $s = null ) {
1701                 wfDeprecated( __METHOD__ );
1702                 return null;
1703         }
1704
1705
1706         /**
1707          * @deprecated Use link()
1708          *
1709          * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1710          * it if you already have a title object handy. See makeLinkObj for further documentation.
1711          *
1712          * @param $title String: the text of the title
1713          * @param $text  String: link text
1714          * @param $query String: optional query part
1715          * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1716          *                      be included in the link text. Other characters will be appended after
1717          *                      the end of the link.
1718          */
1719         function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1720                 wfProfileIn( __METHOD__ );
1721                 $nt = Title::newFromText( $title );
1722                 if ( $nt instanceof Title ) {
1723                         $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1724                 } else {
1725                         wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
1726                         $result = $text == "" ? $title : $text;
1727                 }
1728
1729                 wfProfileOut( __METHOD__ );
1730                 return $result;
1731         }
1732
1733         /**
1734          * @deprecated Use link()
1735          *
1736          * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1737          * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1738          *
1739          * @param $title String: the text of the title
1740          * @param $text  String: link text
1741          * @param $query String: optional query part
1742          * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1743          *                      be included in the link text. Other characters will be appended after
1744          *                      the end of the link.
1745          */
1746         function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
1747                 $nt = Title::newFromText( $title );
1748                 if ( $nt instanceof Title ) {
1749                         return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1750                 } else {
1751                         wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
1752                         return $text == '' ? $title : $text;
1753                 }
1754         }
1755
1756         /**
1757          * @deprecated Use link()
1758          *
1759          * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1760          * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1761          *
1762          * @param string $title The text of the title
1763          * @param string $text Link text
1764          * @param string $query Optional query part
1765          * @param string $trail Optional trail. Alphabetic characters at the start of this string will
1766          *                      be included in the link text. Other characters will be appended after
1767          *                      the end of the link.
1768          */
1769         function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1770                 $nt = Title::newFromText( $title );
1771                 if ( $nt instanceof Title ) {
1772                         return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1773                 } else {
1774                         wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
1775                         return $text == '' ? $title : $text;
1776                 }
1777         }
1778
1779         /**
1780          * @deprecated Use link()
1781          *
1782          * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1783          * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1784          *
1785          * @param $title String: the text of the title
1786          * @param $text  String: link text
1787          * @param $query String: optional query part
1788          * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1789          *                      be included in the link text. Other characters will be appended after
1790          *                      the end of the link.
1791          */
1792         function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1793                 wfDeprecated( __METHOD__ );
1794                 $nt = Title::newFromText( $title );
1795                 if ( $nt instanceof Title ) {
1796                         return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1797                 } else {
1798                         wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
1799                         return $text == '' ? $title : $text;
1800                 }
1801         }
1802
1803         /**
1804          * @deprecated Use link()
1805          *
1806          * Make a link for a title which may or may not be in the database. If you need to
1807          * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1808          * call to this will result in a DB query.
1809          *
1810          * @param $nt     Title: the title object to make the link from, e.g. from
1811          *                      Title::newFromText.
1812          * @param $text  String: link text
1813          * @param $query String: optional query part
1814          * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1815          *                      be included in the link text. Other characters will be appended after
1816          *                      the end of the link.
1817          * @param $prefix String: optional prefix. As trail, only before instead of after.
1818          */
1819         function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
1820                 wfProfileIn( __METHOD__ );
1821
1822                 $query = wfCgiToArray( $query );
1823                 list( $inside, $trail ) = Linker::splitTrail( $trail );
1824                 if( $text === '' ) {
1825                         $text = $this->linkText( $nt );
1826                 }
1827
1828                 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1829
1830                 wfProfileOut( __METHOD__ );
1831                 return $ret;
1832         }
1833
1834         /**
1835          * @deprecated Use link()
1836          *
1837          * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1838          * it doesn't have to do a database query. It's also valid for interwiki titles and special
1839          * pages.
1840          *
1841          * @param $nt Title object of target page
1842          * @param $text   String: text to replace the title
1843          * @param $query  String: link target
1844          * @param $trail  String: text after link
1845          * @param $prefix String: text before link text
1846          * @param $aprops String: extra attributes to the a-element
1847          * @param $style  String: style to apply - if empty, use getInternalLinkAttributesObj instead
1848          * @return the a-element
1849          */
1850         function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1851                 wfProfileIn( __METHOD__ );
1852
1853                 if ( $text == '' ) {
1854                         $text = $this->linkText( $title );
1855                 }
1856                 $attribs = Sanitizer::mergeAttributes(
1857                         Sanitizer::decodeTagAttributes( $aprops ),
1858                         Sanitizer::decodeTagAttributes( $style )
1859                 );
1860                 $query = wfCgiToArray( $query );
1861                 list( $inside, $trail ) = Linker::splitTrail( $trail );
1862
1863                 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1864                         array( 'known', 'noclasses' ) ) . $trail;
1865
1866                 wfProfileOut( __METHOD__ );
1867                 return $ret;
1868         }
1869
1870         /**
1871          * @deprecated Use link()
1872          *
1873          * Make a red link to the edit page of a given title.
1874          *
1875          * @param $nt Title object of the target page
1876          * @param $text  String: Link text
1877          * @param $query String: Optional query part
1878          * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1879          *                      be included in the link text. Other characters will be appended after
1880          *                      the end of the link.
1881          */
1882         function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1883                 wfProfileIn( __METHOD__ );
1884
1885                 list( $inside, $trail ) = Linker::splitTrail( $trail );
1886                 if( $text === '' ) {
1887                         $text = $this->linkText( $title );
1888                 }
1889                 $nt = $this->normaliseSpecialPage( $title );
1890
1891                 $ret = $this->link( $title, "$prefix$text$inside", array(),
1892                         wfCgiToArray( $query ), 'broken' ) . $trail;
1893
1894                 wfProfileOut( __METHOD__ );
1895                 return $ret;
1896         }
1897
1898         /**
1899          * @deprecated Use link()
1900          *
1901          * Make a brown link to a short article.
1902          *
1903          * @param $nt Title object of the target page
1904          * @param $text  String: link text
1905          * @param $query String: optional query part
1906          * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1907          *                      be included in the link text. Other characters will be appended after
1908          *                      the end of the link.
1909          */
1910         function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1911                 wfDeprecated( __METHOD__ );
1912                 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1913         }
1914
1915         /**
1916          * @deprecated Use link()
1917          *
1918          * Make a coloured link.
1919          *
1920          * @param $nt Title object of the target page
1921          * @param $colour Integer: colour of the link
1922          * @param $text   String:  link text
1923          * @param $query  String:  optional query part
1924          * @param $trail  String:  optional trail. Alphabetic characters at the start of this string will
1925          *                      be included in the link text. Other characters will be appended after
1926          *                      the end of the link.
1927          */
1928         function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1929                 if($colour != ''){
1930                         $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1931                 } else $style = '';
1932                 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1933         }
1934
1935         /** Obsolete alias */
1936         function makeImage( $url, $alt = '' ) {
1937                 wfDeprecated( __METHOD__ );
1938                 return $this->makeExternalImage( $url, $alt );
1939         }
1940
1941         /**
1942          * Creates the HTML source for images
1943          * @deprecated use makeImageLink2
1944          *
1945          * @param object $title
1946          * @param string $label label text
1947          * @param string $alt alt text
1948          * @param string $align horizontal alignment: none, left, center, right)
1949          * @param array $handlerParams Parameters to be passed to the media handler
1950          * @param boolean $framed shows image in original size in a frame
1951          * @param boolean $thumb shows image as thumbnail in a frame
1952          * @param string $manualthumb image name for the manual thumbnail
1953          * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1954          * @param string $time, timestamp of the file, set as false for current
1955          * @return string
1956          */
1957         function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
1958           $thumb = false, $manualthumb = '', $valign = '', $time = false )
1959         {
1960                 $frameParams = array( 'alt' => $alt, 'caption' => $label );
1961                 if ( $align ) {
1962                         $frameParams['align'] = $align;
1963                 }
1964                 if ( $framed ) {
1965                         $frameParams['framed'] = true;
1966                 }
1967                 if ( $thumb ) {
1968                         $frameParams['thumbnail'] = true;
1969                 }
1970                 if ( $manualthumb ) {
1971                         $frameParams['manualthumb'] = $manualthumb;
1972                 }
1973                 if ( $valign ) {
1974                         $frameParams['valign'] = $valign;
1975                 }
1976                 $file = wfFindFile( $title, array( 'time' => $time ) );
1977                 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
1978         }
1979
1980         /** @deprecated use Linker::makeMediaLinkObj() */
1981         function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
1982                 $nt = Title::makeTitleSafe( NS_FILE, $name );
1983                 return $this->makeMediaLinkObj( $nt, $text, $time );
1984         }
1985
1986         /**
1987          * Used to generate section edit links that point to "other" pages
1988          * (sections that are really part of included pages).
1989          *
1990          * @deprecated use Linker::doEditSectionLink()
1991          * @param $title Title string.
1992          * @param $section Integer: section number.
1993          */
1994         public function editSectionLinkForOther( $title, $section ) {
1995                 wfDeprecated( __METHOD__ );
1996                 $title = Title::newFromText( $title );
1997                 return $this->doEditSectionLink( $title, $section );
1998         }
1999
2000         /**
2001          * @deprecated use Linker::doEditSectionLink()
2002          * @param $nt Title object.
2003          * @param $section Integer: section number.
2004          * @param $hint Link String: title, or default if omitted or empty
2005          */
2006         public function editSectionLink( Title $nt, $section, $hint = '' ) {
2007                 wfDeprecated( __METHOD__ );
2008                 if( $hint === '' ) {
2009                         # No way to pass an actual empty $hint here!  The new interface al-
2010                         # lows this, so we have to do this for compatibility.
2011                         $hint = null;
2012                 }
2013                 return $this->doEditSectionLink( $nt, $section, $hint );
2014         }
2015
2016         /**
2017          * Returns the attributes for the tooltip and access key
2018          */
2019         public function tooltipAndAccesskeyAttribs( $name ) {
2020                 global $wgEnableTooltipsAndAccesskeys;
2021                 if ( !$wgEnableTooltipsAndAccesskeys )
2022                         return array();
2023                 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2024                 # no attribute" instead of "output '' as value for attribute", this
2025                 # would be three lines.
2026                 $attribs = array(
2027                         'title' => $this->titleAttrib( $name, 'withaccess' ),
2028                         'accesskey' => $this->accesskey( $name )
2029                 );
2030                 if ( $attribs['title'] === false ) {
2031                         unset( $attribs['title'] );
2032                 }
2033                 if ( $attribs['accesskey'] === false ) {
2034                         unset( $attribs['accesskey'] );
2035                 }
2036                 return $attribs;
2037         }
2038         /**
2039          * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
2040          */
2041         public function tooltipAndAccesskey( $name ) {
2042                 return Xml::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2043         }
2044
2045
2046         /** @deprecated Returns raw bits of HTML, use titleAttrib() */
2047         public function tooltip( $name, $options = null ) {
2048                 global $wgEnableTooltipsAndAccesskeys;
2049                 if ( !$wgEnableTooltipsAndAccesskeys )
2050                         return '';
2051                 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2052                 # no attribute" instead of "output '' as value for attribute", this
2053                 # would be two lines.
2054                 $tooltip = $this->titleAttrib( $name, $options );
2055                 if ( $tooltip === false ) {
2056                         return '';
2057                 }
2058                 return Xml::expandAttributes( array(
2059                         'title' => $this->titleAttrib( $name, $options )
2060                 ) );
2061         }
2062 }