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