]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/ImagePage.php
MediaWiki 1.16.5-scripts
[autoinstalls/mediawiki.git] / includes / ImagePage.php
1 <?php
2
3 if( !defined( 'MEDIAWIKI' ) )
4         die( 1 );
5
6 /**
7  * Special handling for image description pages
8  *
9  * @ingroup Media
10  */
11 class ImagePage extends Article {
12
13         /* private */ var $img;  // Image object
14         /* private */ var $displayImg;
15         /* private */ var $repo;
16         /* private */ var $fileLoaded;
17         var $mExtraDescription = false;
18         var $dupes;
19
20         function __construct( $title ) {
21                 parent::__construct( $title );
22                 $this->dupes = null;
23                 $this->repo = null;
24         }
25         
26         public function setFile( $file ) {
27                 $this->displayImg = $file;
28                 $this->img = $file;
29                 $this->fileLoaded = true;
30         }
31
32         protected function loadFile() {
33                 if( $this->fileLoaded ) {
34                         return true;
35                 }
36                 $this->fileLoaded = true;
37
38                 $this->displayImg = $this->img = false;
39                 wfRunHooks( 'ImagePageFindFile', array( $this, &$this->img, &$this->displayImg ) );
40                 if( !$this->img ) {
41                         $this->img = wfFindFile( $this->mTitle );
42                         if( !$this->img ) {
43                                 $this->img = wfLocalFile( $this->mTitle );
44                         }
45                 }
46                 if( !$this->displayImg ) {
47                         $this->displayImg = $this->img;
48                 }
49                 $this->repo = $this->img->getRepo();
50         }
51
52         /**
53          * Handler for action=render
54          * Include body text only; none of the image extras
55          */
56         public function render() {
57                 global $wgOut;
58                 $wgOut->setArticleBodyOnly( true );
59                 parent::view();
60         }
61
62         public function view() {
63                 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
64                 $this->loadFile();
65
66                 if( $this->mTitle->getNamespace() == NS_FILE && $this->img->getRedirected() ) {
67                         if( $this->mTitle->getDBkey() == $this->img->getName() ) {
68                                 // mTitle is the same as the redirect target so ask Article
69                                 // to perform the redirect for us.
70                                 return Article::view();
71                         } else {
72                                 // mTitle is not the same as the redirect target so it is 
73                                 // probably the redirect page itself. Fake the redirect symbol
74                                 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
75                                 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->img->getName() ),
76                                         /* $appendSubtitle */ true, /* $forceKnown */ true ) );
77                                 $this->viewUpdates();
78                                 return;
79                         }
80                 }
81
82                 $diff = $wgRequest->getVal( 'diff' );
83                 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
84
85                 if( $this->mTitle->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) )
86                         return Article::view();
87                         
88                 $this->showRedirectedFromHeader();
89
90                 if( $wgShowEXIF && $this->displayImg->exists() ) {
91                         // FIXME: bad interface, see note on MediaHandler::formatMetadata().
92                         $formattedMetadata = $this->displayImg->formatMetadata();
93                         $showmeta = $formattedMetadata !== false;
94                 } else {
95                         $showmeta = false;
96                 }
97
98                 if( !$diff && $this->displayImg->exists() )
99                         $wgOut->addHTML( $this->showTOC($showmeta) );
100
101                 if( !$diff )
102                         $this->openShowImage();
103
104                 # No need to display noarticletext, we use our own message, output in openShowImage()
105                 if( $this->getID() ) {
106                         Article::view();
107                 } else {
108                         # Just need to set the right headers
109                         $wgOut->setArticleFlag( true );
110                         $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
111                         $this->viewUpdates();
112                 }
113
114                 # Show shared description, if needed
115                 if( $this->mExtraDescription ) {
116                         $fol = wfMsgNoTrans( 'shareddescriptionfollows' );
117                         if( $fol != '-' && !wfEmptyMsg( 'shareddescriptionfollows', $fol ) ) {
118                                 $wgOut->addWikiText( $fol );
119                         }
120                         $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
121                 }
122
123                 $this->closeShowImage();
124                 $this->imageHistory();
125                 // TODO: Cleanup the following
126                 
127                 $wgOut->addHTML( Xml::element( 'h2',
128                         array( 'id' => 'filelinks' ),
129                         wfMsg( 'imagelinks' ) ) . "\n" );
130                 $this->imageDupes();
131                 # TODO! FIXME! For some freaky reason, we can't redirect to foreign images.
132                 # Yet we return metadata about the target. Definitely an issue in the FileRepo
133                 $this->imageRedirects();
134                 $this->imageLinks();
135                 
136                 # Allow extensions to add something after the image links
137                 $html = '';
138                 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
139                 if ( $html)
140                         $wgOut->addHTML( $html );
141
142                 if( $showmeta ) {
143                         global $wgStylePath, $wgStyleVersion;
144                         $expand = htmlspecialchars( Xml::escapeJsString( wfMsg( 'metadata-expand' ) ) );
145                         $collapse = htmlspecialchars( Xml::escapeJsString( wfMsg( 'metadata-collapse' ) ) );
146                         $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
147                         $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
148                         $wgOut->addScriptFile( 'metadata.js' );
149                         $wgOut->addHTML(
150                                 "<script type=\"text/javascript\">attachMetadataToggle('mw_metadata', '$expand', '$collapse');</script>\n" );
151                 }
152         }
153         
154         public function getRedirectTarget() {
155                 $this->loadFile();
156                 if( $this->img->isLocal() ) {
157                         return parent::getRedirectTarget();
158                 }
159                 // Foreign image page
160                 $from = $this->img->getRedirected();
161                 $to = $this->img->getName();
162                 if( $from == $to ) {
163                         return null; 
164                 }
165                 return $this->mRedirectTarget = Title::makeTitle( NS_FILE, $to );
166         }
167         public function followRedirect() {
168                 $this->loadFile();
169                 if( $this->img->isLocal() ) {
170                         return parent::followRedirect();
171                 }
172                 $from = $this->img->getRedirected();
173                 $to = $this->img->getName();
174                 if( $from == $to ) {
175                         return false; 
176                 }
177                 return Title::makeTitle( NS_FILE, $to );        
178         }
179         public function isRedirect( $text = false ) {
180                 $this->loadFile();
181                 if( $this->img->isLocal() )
182                         return parent::isRedirect( $text );
183                         
184                 return (bool)$this->img->getRedirected();
185         }
186         
187         public function isLocal() {
188                 $this->loadFile();
189                 return $this->img->isLocal();
190         }
191         
192         public function getFile() {
193                 $this->loadFile();
194                 return $this->img;
195         }
196         
197         public function getDisplayedFile() {
198                 $this->loadFile();
199                 return $this->displayImg;
200         }
201         
202         public function getDuplicates() {
203                 $this->loadFile();
204                 if( !is_null($this->dupes) ) {
205                         return $this->dupes;
206                 }
207                 if( !( $hash = $this->img->getSha1() ) ) {
208                         return $this->dupes = array();
209                 }
210                 $dupes = RepoGroup::singleton()->findBySha1( $hash );
211                 // Remove duplicates with self and non matching file sizes
212                 $self = $this->img->getRepoName().':'.$this->img->getName();
213                 $size = $this->img->getSize();
214                 foreach ( $dupes as $index => $file ) {
215                         $key = $file->getRepoName().':'.$file->getName();
216                         if( $key == $self )
217                                 unset( $dupes[$index] );
218                         if( $file->getSize() != $size )
219                                 unset( $dupes[$index] );
220                 }
221                 return $this->dupes = $dupes;
222                 
223         }
224         
225
226         /**
227          * Create the TOC
228          *
229          * @param bool $metadata Whether or not to show the metadata link
230          * @return string
231          */
232         protected function showTOC( $metadata ) {
233                 $r = array(
234                                 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
235                                 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
236                                 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>', 
237                 );
238                 if ( $metadata ) {
239                         $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
240                 }
241         
242                 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
243                 
244                 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
245         }
246
247         /**
248          * Make a table with metadata to be shown in the output page.
249          *
250          * FIXME: bad interface, see note on MediaHandler::formatMetadata().
251          *
252          * @param array $exif The array containing the EXIF data
253          * @return string
254          */
255         protected function makeMetadataTable( $metadata ) {
256                 $r = "<div class=\"mw-imagepage-section-metadata\">";
257                 $r .= wfMsgNoTrans( 'metadata-help' );
258                 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
259                 foreach ( $metadata as $type => $stuff ) {
260                         foreach ( $stuff as $v ) {
261                                 # FIXME, why is this using escapeId for a class?!
262                                 $class = Sanitizer::escapeId( $v['id'] );
263                                 if( $type == 'collapsed' ) {
264                                         $class .= ' collapsable';
265                                 }
266                                 $r .= "<tr class=\"$class\">\n";
267                                 $r .= "<th>{$v['name']}</th>\n";
268                                 $r .= "<td>{$v['value']}</td>\n</tr>";
269                         }
270                 }
271                 $r .= "</table>\n</div>\n";
272                 return $r;
273         }
274
275         /**
276          * Overloading Article's getContent method.
277          *
278          * Omit noarticletext if sharedupload; text will be fetched from the
279          * shared upload server if possible.
280          */
281         public function getContent() {
282                 $this->loadFile();
283                 if( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
284                         return '';
285                 }
286                 return Article::getContent();
287         }
288
289         protected function openShowImage() {
290                 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
291                         $wgLang, $wgContLang, $wgEnableUploads;
292
293                 $this->loadFile();
294
295                 $full_url  = $this->displayImg->getURL();
296                 $linkAttribs = false;
297                 $sizeSel = intval( $wgUser->getOption( 'imagesize') );
298                 if( !isset( $wgImageLimits[$sizeSel] ) ) {
299                         $sizeSel = User::getDefaultOption( 'imagesize' );
300
301                         // The user offset might still be incorrect, specially if
302                         // $wgImageLimits got changed (see bug #8858).
303                         if( !isset( $wgImageLimits[$sizeSel] ) ) {
304                                 // Default to the first offset in $wgImageLimits
305                                 $sizeSel = 0;
306                         }
307                 }
308                 $max = $wgImageLimits[$sizeSel];
309                 $maxWidth = $max[0];
310                 $maxHeight = $max[1];
311                 $sk = $wgUser->getSkin();
312                 $dirmark = $wgContLang->getDirMark();
313
314                 if( $this->displayImg->exists() ) {
315                         # image
316                         $page = $wgRequest->getIntOrNull( 'page' );
317                         if( is_null( $page ) ) {
318                                 $params = array();
319                                 $page = 1;
320                         } else {
321                                 $params = array( 'page' => $page );
322                         }
323                         $width_orig = $this->displayImg->getWidth();
324                         $width = $width_orig;
325                         $height_orig = $this->displayImg->getHeight();
326                         $height = $height_orig;
327                         $mime = $this->displayImg->getMimeType();
328                         $showLink = false;
329                         $linkAttribs = array( 'href' => $full_url );
330                         $longDesc = $this->displayImg->getLongDesc();
331
332                         wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
333
334                         if( $this->displayImg->allowInlineDisplay() ) {
335                                 # image
336
337                                 # "Download high res version" link below the image
338                                 #$msgsize = wfMsgHtml('file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->displayImg->getSize() ), $mime );
339                                 # We'll show a thumbnail of this image
340                                 if( $width > $maxWidth || $height > $maxHeight ) {
341                                         # Calculate the thumbnail size.
342                                         # First case, the limiting factor is the width, not the height.
343                                         if( $width / $height >= $maxWidth / $maxHeight ) {
344                                                 $height = round( $height * $maxWidth / $width);
345                                                 $width = $maxWidth;
346                                                 # Note that $height <= $maxHeight now.
347                                         } else {
348                                                 $newwidth = floor( $width * $maxHeight / $height);
349                                                 $height = round( $height * $newwidth / $width );
350                                                 $width = $newwidth;
351                                                 # Note that $height <= $maxHeight now, but might not be identical
352                                                 # because of rounding.
353                                         }
354                                         $msgbig  = wfMsgHtml( 'show-big-image' );
355                                         $msgsmall = wfMsgExt( 'show-big-image-thumb', 'parseinline',
356                                                 $wgLang->formatNum( $width ),
357                                                 $wgLang->formatNum( $height )
358                                         );
359                                 } else {
360                                         # Image is small enough to show full size on image page
361                                         $msgbig = htmlspecialchars( $this->displayImg->getName() );
362                                         $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
363                                 }
364
365                                 $params['width'] = $width;
366                                 $thumbnail = $this->displayImg->transform( $params );
367
368                                 $anchorclose = "<br />";
369                                 if( $this->displayImg->mustRender() ) {
370                                         $showLink = true;
371                                 } else {
372                                         $anchorclose .=
373                                                 $msgsmall .
374                                                 '<br />' . Xml::tags( 'a', $linkAttribs,  $msgbig ) . "$dirmark " . $longDesc;
375                                 }
376
377                                 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
378                                 if( $isMulti ) {
379                                         $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
380                                 }
381
382                                 if( $thumbnail ) {
383                                         $options = array(
384                                                 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
385                                                 'file-link' => true,
386                                         );
387                                         $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
388                                                 $thumbnail->toHtml( $options ) .
389                                                 $anchorclose . "</div>\n" );
390                                 }
391
392                                 if( $isMulti ) {
393                                         $count = $this->displayImg->pageCount();
394
395                                         if( $page > 1 ) {
396                                                 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
397                                                 $link = $sk->link(
398                                                         $this->mTitle,
399                                                         $label,
400                                                         array(),
401                                                         array( 'page' => $page - 1 ),
402                                                         array( 'known', 'noclasses' )
403                                                 );
404                                                 $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
405                                                         array( 'page' => $page - 1 ) );
406                                         } else {
407                                                 $thumb1 = '';
408                                         }
409
410                                         if( $page < $count ) {
411                                                 $label = wfMsg( 'imgmultipagenext' );
412                                                 $link = $sk->link(
413                                                         $this->mTitle,
414                                                         $label,
415                                                         array(),
416                                                         array( 'page' => $page + 1 ),
417                                                         array( 'known', 'noclasses' )
418                                                 );
419                                                 $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
420                                                         array( 'page' => $page + 1 ) );
421                                         } else {
422                                                 $thumb2 = '';
423                                         }
424
425                                         global $wgScript;
426
427                                         $formParams = array(
428                                                 'name' => 'pageselector',
429                                                 'action' => $wgScript,
430                                                 'onchange' => 'document.pageselector.submit();',
431                                         );
432
433                                         $option = array();
434                                         for ( $i=1; $i <= $count; $i++ ) {
435                                                 $options[] = Xml::option( $wgLang->formatNum($i), $i, $i == $page );
436                                         }
437                                         $select = Xml::tags( 'select',
438                                                 array( 'id' => 'pageselector', 'name' => 'page' ),
439                                                 implode( "\n", $options ) );
440
441                                         $wgOut->addHTML(
442                                                 '</td><td><div class="multipageimagenavbox">' .
443                                                 Xml::openElement( 'form', $formParams ) .
444                                                 Xml::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
445                                                 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
446                                                 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
447                                                 Xml::closeElement( 'form' ) .
448                                                 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
449                                         );
450                                 }
451                         } else {
452                                 #if direct link is allowed but it's not a renderable image, show an icon.
453                                 if( $this->displayImg->isSafeFile() ) {
454                                         $icon= $this->displayImg->iconThumb();
455
456                                         $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
457                                         $icon->toHtml( array( 'file-link' => true ) ) .
458                                         "</div>\n" );
459                                 }
460
461                                 $showLink = true;
462                         }
463
464
465                         if($showLink) {
466                                 $filename = wfEscapeWikiText( $this->displayImg->getName() );
467                                 $medialink = "[[Media:$filename|$filename]]";
468
469                                 if( !$this->displayImg->isSafeFile() ) {
470                                         $warning = wfMsgNoTrans( 'mediawarning' );
471                                         $wgOut->addWikiText( <<<EOT
472 <div class="fullMedia">
473 <span class="dangerousLink">{$medialink}</span>$dirmark
474 <span class="fileInfo">$longDesc</span>
475 </div>
476 <div class="mediaWarning">$warning</div>
477 EOT
478                                                 );
479                                 } else {
480                                         $wgOut->addWikiText( <<<EOT
481 <div class="fullMedia">
482 {$medialink}{$dirmark}
483 <span class="fileInfo">$longDesc</span>
484 </div>
485 EOT
486                                         );
487                                 }
488                         }
489
490                         if( !$this->displayImg->isLocal() ) {
491                                 $this->printSharedImageText();
492                         }
493                 } else {
494                         # Image does not exist
495                         if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
496                                 // Only show an upload link if the user can upload
497                                 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
498                                 $nofile = array(
499                                         'filepage-nofile-link',
500                                         $uploadTitle->getFullUrl( array( 'wpDestFile' => $this->img->getName() ) )
501                                 );
502                         }
503                         else
504                         {
505                                 $nofile = 'filepage-nofile';
506                         }
507                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
508                         $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
509                 }
510         }
511
512         /**
513          * Show a notice that the file is from a shared repository
514          */
515         protected function printSharedImageText() {
516                 global $wgOut;
517
518                 $this->loadFile();
519
520                 $descUrl = $this->img->getDescriptionUrl();
521                 $descText = $this->img->getDescriptionText();
522
523                 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
524                 $repo = $this->img->getRepo()->getDisplayName();
525
526                 $msg = '';
527                 if( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-'  ) {
528                         $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
529                 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
530                         $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
531                 } else {
532                         $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
533                 }
534
535                 if( $descText ) {
536                         $this->mExtraDescription = $descText;
537                 }
538         }
539
540         public function getUploadUrl() {
541                 $this->loadFile();
542                 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
543                 return $uploadTitle->getFullUrl( array(
544                         'wpDestFile' => $this->img->getName(),
545                         'wpForReUpload' => 1
546                  ) );
547         }
548
549         /**
550          * Print out the various links at the bottom of the image page, e.g. reupload,
551          * external editing (and instructions link) etc.
552          */
553         protected function uploadLinksBox() {
554                 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
555
556                 if( !$wgEnableUploads ) { return; }
557
558                 $this->loadFile();
559                 if( !$this->img->isLocal() )
560                         return;
561
562                 $sk = $wgUser->getSkin();
563
564                 $wgOut->addHTML( "<br /><ul>\n" );
565
566                 # "Upload a new version of this file" link
567                 if( UploadBase::userCanReUpload($wgUser,$this->img->name) ) {
568                         $ulink = $sk->makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
569                         $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
570                 }
571
572                 # External editing link
573                 if ( $wgUseExternalEditor ) {
574                         $elink = $sk->link(
575                                 $this->mTitle,
576                                 wfMsgHtml( 'edit-externally' ),
577                                 array(),
578                                 array(
579                                         'action' => 'edit',
580                                         'externaledit' => 'true',
581                                         'mode' => 'file'
582                                 ),
583                                 array( 'known', 'noclasses' )
584                         );
585                         $wgOut->addHTML( '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' . wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) . "</small></li>\n" );
586                 }
587
588                 $wgOut->addHTML( "</ul>\n" );
589         }
590
591         protected function closeShowImage() {} # For overloading
592
593         /**
594          * If the page we've just displayed is in the "Image" namespace,
595          * we follow it with an upload history of the image and its usage.
596          */
597         protected function imageHistory() {
598                 global $wgOut;
599
600                 $this->loadFile();
601                 $pager = new ImageHistoryPseudoPager( $this );
602                 $wgOut->addHTML( $pager->getBody() );
603                 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
604
605                 $this->img->resetHistory(); // free db resources
606
607                 # Exist check because we don't want to show this on pages where an image
608                 # doesn't exist along with the noimage message, that would suck. -ævar
609                 if( $this->img->exists() ) {
610                         $this->uploadLinksBox();
611                 }
612         }
613
614         protected function imageLinks() {
615                 global $wgUser, $wgOut, $wgLang;
616
617                 $limit = 100;
618
619                 $dbr = wfGetDB( DB_SLAVE );
620
621                 $res = $dbr->select(
622                         array( 'imagelinks', 'page' ),
623                         array( 'page_namespace', 'page_title' ),
624                         array( 'il_to' => $this->mTitle->getDBkey(), 'il_from = page_id' ),
625                         __METHOD__,
626                         array( 'LIMIT' => $limit + 1)   
627                 );
628                 $count = $dbr->numRows( $res );
629                 if( $count == 0 ) {
630                         $wgOut->addHTML( "<div id='mw-imagepage-nolinkstoimage'>\n" );
631                         $wgOut->addWikiMsg( 'nolinkstoimage' );
632                         $wgOut->addHTML( "</div>\n" );
633                         return;
634                 }
635                 
636                 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
637                 if( $count <= $limit - 1 ) {
638                         $wgOut->addWikiMsg( 'linkstoimage', $count );
639                 } else {
640                         // More links than the limit. Add a link to [[Special:Whatlinkshere]]
641                         $wgOut->addWikiMsg( 'linkstoimage-more',
642                                 $wgLang->formatNum( $limit ),
643                                 $this->mTitle->getPrefixedDBkey()
644                         );
645                 }
646
647                 $wgOut->addHTML( "<ul class='mw-imagepage-linkstoimage'>\n" );
648                 $sk = $wgUser->getSkin();
649                 $count = 0;
650                 while ( $s = $res->fetchObject() ) {
651                         $count++;
652                         if( $count <= $limit ) {
653                                 // We have not yet reached the extra one that tells us there is more to fetch
654                                 $link = $sk->link(
655                                         Title::makeTitle( $s->page_namespace, $s->page_title ),
656                                         null,
657                                         array(),
658                                         array(),
659                                         array( 'known', 'noclasses' )
660                                 );
661                                 $wgOut->addHTML( "<li>{$link}</li>\n" );
662                         }
663                 }
664                 $wgOut->addHTML( "</ul>\n" );
665                 $res->free();
666
667                 // Add a links to [[Special:Whatlinkshere]]
668                 if( $count > $limit )
669                         $wgOut->addWikiMsg( 'morelinkstoimage', $this->mTitle->getPrefixedDBkey() );
670                 $wgOut->addHTML( "</div>\n" );
671         }
672         
673         protected function imageRedirects() {
674                 global $wgUser, $wgOut, $wgLang;
675
676                 $redirects = $this->getTitle()->getRedirectsHere( NS_FILE );
677                 if( count( $redirects ) == 0 ) return;
678
679                 $wgOut->addHTML( "<div id='mw-imagepage-section-redirectstofile'>\n" );
680                 $wgOut->addWikiMsg( 'redirectstofile',
681                         $wgLang->formatNum( count( $redirects ) )
682                 );
683                 $wgOut->addHTML( "<ul class='mw-imagepage-redirectstofile'>\n" );
684
685                 $sk = $wgUser->getSkin();
686                 foreach ( $redirects as $title ) {
687                         $link = $sk->link(
688                                 $title,
689                                 null,
690                                 array(),
691                                 array( 'redirect' => 'no' ),
692                                 array( 'known', 'noclasses' )
693                         );
694                         $wgOut->addHTML( "<li>{$link}</li>\n" );
695                 }
696                 $wgOut->addHTML( "</ul></div>\n" );
697
698         }
699
700         protected function imageDupes() {
701                 global $wgOut, $wgUser, $wgLang;
702
703                 $this->loadFile();
704
705                 $dupes = $this->getDuplicates();
706                 if( count( $dupes ) == 0 ) return;
707
708                 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
709                 $wgOut->addWikiMsg( 'duplicatesoffile',
710                         $wgLang->formatNum( count( $dupes ) ), $this->mTitle->getDBkey()
711                 );
712                 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
713
714                 $sk = $wgUser->getSkin();
715                 foreach ( $dupes as $file ) {
716                         $fromSrc = '';
717                         if( $file->isLocal() ) {
718                                 $link = $sk->link(
719                                         $file->getTitle(),
720                                         null,
721                                         array(),
722                                         array(),
723                                         array( 'known', 'noclasses' )
724                                 );
725                         } else {
726                                 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
727                                         $file->getTitle()->getPrefixedText() );
728                                 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
729                         }
730                         $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
731                 }
732                 $wgOut->addHTML( "</ul></div>\n" );
733         }
734
735         /**
736          * Delete the file, or an earlier version of it
737          */
738         public function delete() {
739                 global $wgUploadMaintenance;
740                 if( $wgUploadMaintenance && $this->mTitle && $this->mTitle->getNamespace() == NS_FILE ) {
741                         global $wgOut;
742                         $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n", array( 'filedelete-maintenance' ) );
743                         return;
744                 }
745
746                 $this->loadFile();
747                 if( !$this->img->exists() || !$this->img->isLocal() || $this->img->getRedirected() ) {
748                         // Standard article deletion
749                         Article::delete();
750                         return;
751                 }
752                 $deleter = new FileDeleteForm( $this->img );
753                 $deleter->execute();
754         }
755
756         /**
757          * Revert the file to an earlier version
758          */
759         public function revert() {
760                 $this->loadFile();
761                 $reverter = new FileRevertForm( $this->img );
762                 $reverter->execute();
763         }
764
765         /**
766          * Override handling of action=purge
767          */
768         public function doPurge() {
769                 $this->loadFile();
770                 if( $this->img->exists() ) {
771                         wfDebug( "ImagePage::doPurge purging " . $this->img->getName() . "\n" );
772                         $update = new HTMLCacheUpdate( $this->mTitle, 'imagelinks' );
773                         $update->doUpdate();
774                         $this->img->upgradeRow();
775                         $this->img->purgeCache();
776                 } else {
777                         wfDebug( "ImagePage::doPurge no image for " . $this->img->getName() . "; limiting purge to cache only\n" );
778                         // even if the file supposedly doesn't exist, force any cached information
779                         // to be updated (in case the cached information is wrong)
780                         $this->img->purgeCache();
781                 }
782                 parent::doPurge();
783         }
784
785         /**
786          * Display an error with a wikitext description
787          */
788         function showError( $description ) {
789                 global $wgOut;
790                 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
791                 $wgOut->setRobotPolicy( "noindex,nofollow" );
792                 $wgOut->setArticleRelated( false );
793                 $wgOut->enableClientCache( false );
794                 $wgOut->addWikiText( $description );
795         }
796
797 }
798
799 /**
800  * Builds the image revision log shown on image pages
801  *
802  * @ingroup Media
803  */
804 class ImageHistoryList {
805
806         protected $imagePage, $img, $skin, $title, $repo, $showThumb;
807         protected $preventClickjacking = false;
808
809         public function __construct( $imagePage ) {
810                 global $wgUser, $wgShowArchiveThumbnails;
811                 $this->skin = $wgUser->getSkin();
812                 $this->current = $imagePage->getFile();
813                 $this->img = $imagePage->getDisplayedFile();
814                 $this->title = $imagePage->getTitle();
815                 $this->imagePage = $imagePage;
816                 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
817         }
818
819         public function getImagePage() {
820                 return $this->imagePage;
821         }
822
823         public function getSkin() {
824                 return $this->skin;
825         }
826
827         public function getFile() {
828                 return $this->img;
829         }
830
831         public function beginImageHistoryList( $navLinks = '' ) {
832                 global $wgOut, $wgUser;
833                 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
834                         . "<div id=\"mw-imagepage-section-filehistory\">\n"
835                         . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
836                         . $navLinks . "\n"
837                         . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
838                         . '<tr><td></td>'
839                         . ( $this->current->isLocal() && ($wgUser->isAllowed('delete') || $wgUser->isAllowed('deletedhistory') ) ? '<td></td>' : '' )
840                         . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
841                         . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
842                         . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
843                         . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
844                         . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
845                         . "</tr>\n";
846         }
847
848         public function endImageHistoryList( $navLinks = '' ) {
849                 return "</table>\n$navLinks\n</div>\n";
850         }
851
852         public function imageHistoryLine( $iscur, $file ) {
853                 global $wgUser, $wgLang, $wgContLang, $wgTitle;
854
855                 $timestamp = wfTimestamp(TS_MW, $file->getTimestamp());
856                 $img = $iscur ? $file->getName() : $file->getArchiveName();
857                 $user = $file->getUser('id');
858                 $usertext = $file->getUser('text');
859                 $description = $file->getDescription();
860
861                 $local = $this->current->isLocal();
862                 $row = $css = $selected = '';
863
864                 // Deletion link
865                 if( $local && ($wgUser->isAllowed('delete') || $wgUser->isAllowed('deletedhistory') ) ) {
866                         $row .= '<td>';
867                         # Link to remove from history
868                         if( $wgUser->isAllowed( 'delete' ) ) {
869                                 $q = array( 'action' => 'delete' );
870                                 if( !$iscur )
871                                         $q['oldimage'] = $img;
872                                 $row .= $this->skin->link(
873                                         $this->title,
874                                         wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
875                                         array(), $q, array( 'known' )
876                                 );
877                         }
878                         # Link to hide content. Don't show useless link to people who cannot hide revisions.
879                         $canHide = $wgUser->isAllowed( 'deleterevision' );
880                         if( $canHide || ($wgUser->isAllowed('deletedhistory') && $file->getVisibility()) ) {
881                                 if( $wgUser->isAllowed('delete') ) {
882                                         $row .= '<br />';
883                                 }
884                                 // If file is top revision or locked from this user, don't link
885                                 if( $iscur || !$file->userCan(File::DELETED_RESTRICTED) ) {
886                                         $del = $this->skin->revDeleteLinkDisabled( $canHide );
887                                 } else {
888                                         list( $ts, $name ) = explode( '!', $img, 2 );
889                                         $query = array(
890                                                 'type'   => 'oldimage',
891                                                 'target' => $wgTitle->getPrefixedText(), 
892                                                 'ids'    => $ts,
893                                         );
894                                         $del = $this->skin->revDeleteLink( $query,
895                                                 $file->isDeleted(File::DELETED_RESTRICTED), $canHide );
896                                 }
897                                 $row .= $del;
898                         }
899                         $row .= '</td>';
900                 }
901
902                 // Reversion link/current indicator
903                 $row .= '<td>';
904                 if( $iscur ) {
905                         $row .= wfMsgHtml( 'filehist-current' );
906                 } elseif( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
907                         if( $file->isDeleted(File::DELETED_FILE) ) {
908                                 $row .= wfMsgHtml('filehist-revert');
909                         } else {
910                                 $row .= $this->skin->link(
911                                         $this->title,
912                                         wfMsgHtml( 'filehist-revert' ),
913                                         array(),
914                                         array(
915                                                 'action' => 'revert',
916                                                 'oldimage' => $img,
917                                                 'wpEditToken' => $wgUser->editToken( $img )
918                                         ),
919                                         array( 'known', 'noclasses' )
920                                 );
921                         }
922                 }
923                 $row .= '</td>';
924
925                 // Date/time and image link
926                 if( $file->getTimestamp() === $this->img->getTimestamp() ) {
927                         $selected = "class='filehistory-selected'";
928                 }
929                 $row .= "<td $selected style='white-space: nowrap;'>";
930                 if( !$file->userCan(File::DELETED_FILE) ) {
931                         # Don't link to unviewable files
932                         $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
933                 } elseif( $file->isDeleted(File::DELETED_FILE) ) {
934                         $this->preventClickjacking();
935                         $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
936                         # Make a link to review the image
937                         $url = $this->skin->link(
938                                 $revdel,
939                                 $wgLang->timeAndDate( $timestamp, true ),
940                                 array(),
941                                 array(
942                                         'target' => $wgTitle->getPrefixedText(),
943                                         'file' => $img,
944                                         'token' => $wgUser->editToken( $img )
945                                 ),
946                                 array( 'known', 'noclasses' )
947                         );
948                         $row .= '<span class="history-deleted">'.$url.'</span>';
949                 } else {
950                         $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
951                         $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
952                 }
953                 $row .= "</td>";
954
955                 // Thumbnail
956                 if ( $this->showThumb ) {
957                         $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
958                 }
959
960                 // Image dimensions + size
961                 $row .= '<td>';
962                 $row .= htmlspecialchars( $file->getDimensionsString() );
963                 $row .= " <span style='white-space: nowrap;'>(" . $this->skin->formatSize( $file->getSize() ) . ')</span>';
964                 $row .= '</td>';
965
966                 // Uploading user
967                 $row .= '<td>';
968                 if( $local ) {
969                         // Hide deleted usernames
970                         if( $file->isDeleted(File::DELETED_USER) ) {
971                                 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
972                         } else {
973                                 $row .= $this->skin->userLink( $user, $usertext ) . " <span style='white-space: nowrap;'>" . 
974                                         $this->skin->userToolLinks( $user, $usertext ) . "</span>";
975                         }
976                 } else {
977                         $row .= htmlspecialchars( $usertext );
978                 }
979                 $row .= '</td><td>';
980
981                 // Don't show deleted descriptions
982                 if( $file->isDeleted(File::DELETED_COMMENT) ) {
983                         $row .= '<span class="history-deleted">' . wfMsgHtml('rev-deleted-comment') . '</span>';
984                 } else {
985                         $row .= $this->skin->commentBlock( $description, $this->title );
986                 }
987                 $row .= '</td>';
988
989                 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
990                 $classAttr = $rowClass ? " class='$rowClass'" : "";
991
992                 return "<tr{$classAttr}>{$row}</tr>\n";
993         }
994
995         protected function getThumbForLine( $file ) {
996                 global $wgLang;
997
998                 if( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
999                         $params = array(
1000                                 'width' => '120',
1001                                 'height' => '120',
1002                         );
1003                         $timestamp = wfTimestamp(TS_MW, $file->getTimestamp());
1004
1005                         $thumbnail = $file->transform( $params );
1006                         $options = array(
1007                                 'alt' => wfMsg( 'filehist-thumbtext',
1008                                         $wgLang->timeAndDate( $timestamp, true ),
1009                                         $wgLang->date( $timestamp, true ),
1010                                         $wgLang->time( $timestamp, true ) ),
1011                                 'file-link' => true,
1012                         );
1013                         
1014                         if ( !$thumbnail ) return wfMsgHtml( 'filehist-nothumb' );
1015
1016                         return $thumbnail->toHtml( $options );
1017                 } else {
1018                         return wfMsgHtml( 'filehist-nothumb' );
1019                 }
1020         }
1021
1022         protected function preventClickjacking( $enable = true ) {
1023                 $this->preventClickjacking = $enable;
1024         }
1025
1026         public function getPreventClickjacking() {
1027                 return $this->preventClickjacking;
1028         }
1029 }
1030
1031 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1032         protected $preventClickjacking = false;
1033
1034         function __construct( $imagePage ) {
1035                 parent::__construct();
1036                 $this->mImagePage = $imagePage;
1037                 $this->mTitle = clone( $imagePage->getTitle() );
1038                 $this->mTitle->setFragment( '#filehistory' );
1039                 $this->mImg = null;
1040                 $this->mHist = array();
1041                 $this->mRange = array( 0, 0 ); // display range
1042         }
1043         
1044         function getTitle() {
1045                 return $this->mTitle;
1046         }
1047
1048         function getQueryInfo() {
1049                 return false;
1050         }
1051
1052         function getIndexField() {
1053                 return '';
1054         }
1055
1056         function formatRow( $row ) {
1057                 return '';
1058         }
1059         
1060         function getBody() {
1061                 $s = '';
1062                 $this->doQuery();
1063                 if( count($this->mHist) ) {
1064                         $list = new ImageHistoryList( $this->mImagePage );
1065                         # Generate prev/next links
1066                         $navLink = $this->getNavigationBar();
1067                         $s = $list->beginImageHistoryList($navLink);
1068                         // Skip rows there just for paging links
1069                         for( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1070                                 $file = $this->mHist[$i];
1071                                 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1072                         }
1073                         $s .= $list->endImageHistoryList($navLink);
1074
1075                         if ( $list->getPreventClickjacking() ) {
1076                                 $this->preventClickjacking();
1077                         }
1078                 }
1079                 return $s;
1080         }
1081
1082         function doQuery() {
1083                 if( $this->mQueryDone ) return;
1084                 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1085                 if( !$this->mImg->exists() ) {
1086                         return;
1087                 }
1088                 $queryLimit = $this->mLimit + 1; // limit plus extra row
1089                 if( $this->mIsBackwards ) {
1090                         // Fetch the file history
1091                         $this->mHist = $this->mImg->getHistory($queryLimit,null,$this->mOffset,false);
1092                         // The current rev may not meet the offset/limit
1093                         $numRows = count($this->mHist);
1094                         if( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1095                                 $this->mHist = array_merge( array($this->mImg), $this->mHist );
1096                         }
1097                 } else {
1098                         // The current rev may not meet the offset
1099                         if( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1100                                 $this->mHist[] = $this->mImg;
1101                         }
1102                         // Old image versions (fetch extra row for nav links)
1103                         $oiLimit = count($this->mHist) ? $this->mLimit : $this->mLimit+1;
1104                         // Fetch the file history
1105                         $this->mHist = array_merge( $this->mHist,
1106                                 $this->mImg->getHistory($oiLimit,$this->mOffset,null,false) );
1107                 }
1108                 $numRows = count($this->mHist); // Total number of query results
1109                 if( $numRows ) {
1110                         # Index value of top item in the list
1111                         $firstIndex = $this->mIsBackwards ?
1112                                 $this->mHist[$numRows-1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1113                         # Discard the extra result row if there is one
1114                         if( $numRows > $this->mLimit && $numRows > 1 ) {
1115                                 if( $this->mIsBackwards ) {
1116                                         # Index value of item past the index
1117                                         $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1118                                         # Index value of bottom item in the list
1119                                         $lastIndex = $this->mHist[1]->getTimestamp();
1120                                         # Display range
1121                                         $this->mRange = array( 1, $numRows-1 );
1122                                 } else {
1123                                         # Index value of item past the index
1124                                         $this->mPastTheEndIndex = $this->mHist[$numRows-1]->getTimestamp();
1125                                         # Index value of bottom item in the list
1126                                         $lastIndex = $this->mHist[$numRows-2]->getTimestamp();
1127                                         # Display range
1128                                         $this->mRange = array( 0, $numRows-2 );
1129                                 }
1130                         } else {
1131                                 # Setting indexes to an empty string means that they will be
1132                                 # omitted if they would otherwise appear in URLs. It just so
1133                                 # happens that this  is the right thing to do in the standard
1134                                 # UI, in all the relevant cases.
1135                                 $this->mPastTheEndIndex = '';
1136                                 # Index value of bottom item in the list
1137                                 $lastIndex = $this->mIsBackwards ?
1138                                         $this->mHist[0]->getTimestamp() : $this->mHist[$numRows-1]->getTimestamp();
1139                                 # Display range
1140                                 $this->mRange = array( 0, $numRows-1 );
1141                         }
1142                 } else {
1143                         $firstIndex = '';
1144                         $lastIndex = '';
1145                         $this->mPastTheEndIndex = '';
1146                 }
1147                 if( $this->mIsBackwards ) {
1148                         $this->mIsFirst = ( $numRows < $queryLimit );
1149                         $this->mIsLast = ( $this->mOffset == '' );
1150                         $this->mLastShown = $firstIndex;
1151                         $this->mFirstShown = $lastIndex;
1152                 } else {
1153                         $this->mIsFirst = ( $this->mOffset == '' );
1154                         $this->mIsLast = ( $numRows < $queryLimit );
1155                         $this->mLastShown = $lastIndex;
1156                         $this->mFirstShown = $firstIndex;
1157                 }
1158                 $this->mQueryDone = true;
1159         }
1160         
1161         protected function preventClickjacking( $enable = true ) {
1162                 $this->preventClickjacking = $enable;
1163         }
1164
1165         public function getPreventClickjacking() {
1166                 return $this->preventClickjacking;
1167         }
1168
1169 }