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