Lessons learnt from installing MediaWiki with safe_mode, especially support for uploa...
[mediawiki.git] / includes / ImagePage.php
blobee93cfbd918042347cf79f94b40d1b4d8fc6e36d
1 <?php
2 /**
3 * @package MediaWiki
4 */
6 /**
8 */
9 if( !defined( 'MEDIAWIKI' ) )
10 die();
12 require_once( 'Image.php' );
14 /**
15 * Special handling for image description pages
16 * @package MediaWiki
18 class ImagePage extends Article {
20 /* private */ var $img; // Image object this page is shown for
22 function view() {
23 global $wgUseExternalEditor, $wgOut;
25 $this->img = new Image( $this->mTitle );
27 if( $this->mTitle->getNamespace() == NS_IMAGE ) {
28 $this->openShowImage();
30 # No need to display noarticletext, we use our own message, output in openShowImage()
31 if ( $this->getID() ) {
32 Article::view();
33 } else {
34 # Just need to set the right headers
35 $wgOut->setArticleFlag( true );
36 $wgOut->setRobotpolicy( 'index,follow' );
37 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
38 $wgOut->addMetaTags();
39 $this->viewUpdates();
42 if ( $this->img->exists() ) {
43 $this->uploadNewVersionLink();
44 if ( $wgUseExternalEditor && $this->img->exists() ) {
45 $this->externalEditorLink();
48 $this->closeShowImage();
49 $this->imageHistory();
50 $this->imageLinks();
51 } else {
52 Article::view();
56 function openShowImage()
58 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
59 $wgUseImageResize, $wgRepositoryBaseUrl,
60 $wgUseExternalEditor, $wgServer;
61 $full_url = $this->img->getViewURL();
62 $anchoropen = '';
63 $anchorclose = '';
65 if( $wgUser->getOption( 'imagesize' ) == '' ) {
66 $sizeSel = User::getDefaultOption( 'imagesize' );
67 } else {
68 $sizeSel = IntVal( $wgUser->getOption( 'imagesize' ) );
70 if( !isset( $wgImageLimits[$sizeSel] ) ) {
71 $sizeSel = User::getDefaultOption( 'imagesize' );
73 $max = $wgImageLimits[$sizeSel];
74 $maxWidth = $max[0];
75 $maxHeight = $max[1];
76 $sk = $wgUser->getSkin();
78 if ( $this->img->exists() ) {
79 if ( $this->img->getType() != '' ) {
80 # image
81 $width = $this->img->getWidth();
82 $height = $this->img->getHeight();
83 $msg = wfMsg('showbigimage', $width, $height, intval( $this->img->getSize()/1024 ) );
84 if ( $width > $maxWidth ) {
85 $height = floor( $height * $maxWidth / $width );
86 $width = $maxWidth;
88 if ( $height > $maxHeight ) {
89 $width = floor( $width * $maxHeight / $height );
90 $height = $maxHeight;
92 if ( $width != $this->img->getWidth() || $height != $this->img->getHeight() ) {
93 if( $wgUseImageResize ) {
94 $thumbnail = $this->img->getThumbnail( $width );
95 $url = $thumbnail->getUrl();
96 } else {
97 # No resize ability? Show the full image, but scale
98 # it down in the browser so it fits on the page.
99 $url = $full_url;
101 $anchoropen = "<a href=\"{$full_url}\">";
102 $anchorclose = "</a><br />\n$anchoropen{$msg}</a>";
103 } else {
104 $url = $full_url;
106 $s = '<div class="fullImageLink">' . $anchoropen .
107 "<img border=\"0\" src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"" .
108 htmlspecialchars( $wgRequest->getVal( 'image' ) ).'" />' . $anchorclose . '</div>';
109 } else {
110 $s = "<div class=\"fullMedia\">" . $sk->makeMediaLink( $this->img->getName(),'' ) . '</div>';
112 $wgOut->addHTML( $s );
113 if($this->img->fromSharedDirectory) {
114 $sharedtext="<div class=\"sharedUploadNotice\">" . wfMsg("sharedupload");
115 if($wgRepositoryBaseUrl) {
116 $sharedtext .= " ". wfMsg("shareduploadwiki",$wgRepositoryBaseUrl . urlencode($this->mTitle->getDBkey()));
118 $sharedtext.="</div>";
119 $wgOut->addWikiText($sharedtext);
122 } else {
123 # Image does not exist
124 $wgOut->addWikiText( wfMsg( 'noimage', $this->getUploadUrl() ) );
128 function getUploadUrl() {
129 global $wgServer;
130 $uploadTitle = Title::makeTitle( NS_SPECIAL, 'Upload' );
131 return $wgServer . $uploadTitle->getLocalUrl( 'wpDestFile=' . urlencode( $this->img->getName() ) );
135 function uploadNewVersionLink() {
136 global $wgOut;
137 $wgOut->addWikiText( wfMsg( 'uploadnewversion', $this->getUploadUrl() ) );
140 function externalEditorLink()
142 global $wgUser,$wgOut;
143 $sk = $wgUser->getSkin();
144 $wgOut->addHTML( '<div class="editExternally">' );
145 $wgOut->addHTML( $sk->makeKnownLinkObj( $this->mTitle,
146 wfMsg( 'edit-externally' ),
147 "action=edit&externaledit=true&mode=file" ) );
148 $wgOut->addWikiText( '<div class="editExternallyHelp">' .
149 wfMsg('edit-externally-help') . '</div>' );
150 $wgOut->addHTML( '</div><br clear="all" />' );
153 function closeShowImage()
155 # For overloading
160 * If the page we've just displayed is in the "Image" namespace,
161 * we follow it with an upload history of the image and its usage.
163 function imageHistory()
165 global $wgUser, $wgOut;
167 $sk = $wgUser->getSkin();
169 $line = $this->img->nextHistoryLine();
171 if ( $line ) {
172 $list =& new ImageHistoryList( $sk );
173 $s = $list->beginImageHistoryList() .
174 $list->imageHistoryLine( true, $line->img_timestamp,
175 $this->mTitle->getDBkey(), $line->img_user,
176 $line->img_user_text, $line->img_size, $line->img_description );
178 while ( $line = $this->img->nextHistoryLine() ) {
179 $s .= $list->imageHistoryLine( false, $line->img_timestamp,
180 $line->oi_archive_name, $line->img_user,
181 $line->img_user_text, $line->img_size, $line->img_description );
183 $s .= $list->endImageHistoryList();
184 } else { $s=''; }
185 $wgOut->addHTML( $s );
188 function imageLinks()
190 global $wgUser, $wgOut;
192 $wgOut->addHTML( '<h2>' . wfMsg( 'imagelinks' ) . "</h2>\n" );
194 $dbr =& wfGetDB( DB_SLAVE );
195 $page = $dbr->tableName( 'page' );
196 $imagelinks = $dbr->tableName( 'imagelinks' );
198 $sql = "SELECT page_namespace,page_title FROM $imagelinks,$page WHERE il_to=" .
199 $dbr->addQuotes( $this->mTitle->getDBkey() ) . " AND il_from=page_id"
200 . " LIMIT 500"; # quickie emergency brake
201 $res = $dbr->query( $sql, "ImagePage::imageLinks" );
203 if ( 0 == $dbr->numRows( $res ) ) {
204 $wgOut->addHtml( '<p>' . wfMsg( "nolinkstoimage" ) . "</p>\n" );
205 return;
207 $wgOut->addHTML( '<p>' . wfMsg( 'linkstoimage' ) . "</p>\n<ul>" );
209 $sk = $wgUser->getSkin();
210 while ( $s = $dbr->fetchObject( $res ) ) {
211 $name = Title::MakeTitle( $s->page_namespace, $s->page_title );
212 $link = $sk->makeKnownLinkObj( $name, "" );
213 $wgOut->addHTML( "<li>{$link}</li>\n" );
215 $wgOut->addHTML( "</ul>\n" );
218 function delete()
220 global $wgUser, $wgOut, $wgRequest;
222 $confirm = $wgRequest->getBool( 'wpConfirmB' );
223 $image = $wgRequest->getVal( 'image' );
224 $oldimage = $wgRequest->getVal( 'oldimage' );
226 # Only sysops can delete images. Previously ordinary users could delete
227 # old revisions, but this is no longer the case.
228 if ( !$wgUser->isAllowed('delete') ) {
229 $wgOut->sysopRequired();
230 return;
232 if ( wfReadOnly() ) {
233 $wgOut->readOnlyPage();
234 return;
237 # Better double-check that it hasn't been deleted yet!
238 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
239 if ( ( !is_null( $image ) )
240 && ( '' == trim( $image ) ) ) {
241 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
242 return;
245 $this->img = new Image( $this->mTitle );
247 # Deleting old images doesn't require confirmation
248 if ( !is_null( $oldimage ) || $confirm ) {
249 if( $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
250 $this->doDelete();
251 } else {
252 $wgOut->fatalError( wfMsg( 'sessionfailure' ) );
254 return;
257 if ( !is_null( $image ) ) {
258 $q = '&image=' . urlencode( $image );
259 } else if ( !is_null( $oldimage ) ) {
260 $q = '&oldimage=' . urlencode( $oldimage );
261 } else {
262 $q = '';
264 return $this->confirmDelete( $q, $wgRequest->getText( 'wpReason' ) );
267 function doDelete()
269 global $wgOut, $wgUser, $wgContLang, $wgRequest;
270 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
271 $fname = 'ImagePage::doDelete';
273 $reason = $wgRequest->getVal( 'wpReason' );
274 $oldimage = $wgRequest->getVal( 'oldimage' );
276 $dbw =& wfGetDB( DB_MASTER );
278 if ( !is_null( $oldimage ) ) {
279 if ( strlen( $oldimage ) < 16 ) {
280 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
281 return;
283 if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
284 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
285 return;
288 # Invalidate description page cache
289 $this->mTitle->invalidateCache();
291 # Squid purging
292 if ( $wgUseSquid ) {
293 $urlArr = Array(
294 $wgInternalServer.wfImageArchiveUrl( $oldimage ),
295 $wgInternalServer.$this->mTitle->getFullURL()
297 wfPurgeSquidServers($urlArr);
299 $this->doDeleteOldImage( $oldimage );
300 $dbw->delete( 'oldimage', array( 'oi_archive_name' => $oldimage ) );
301 $deleted = $oldimage;
302 } else {
303 $image = $this->mTitle->getDBkey();
304 $dest = wfImageDir( $image );
305 $archive = wfImageDir( $image );
307 # Delete the image file if it exists; due to sync problems
308 # or manual trimming sometimes the file will be missing.
309 $targetFile = "{$dest}/{$image}";
310 if( file_exists( $targetFile ) && ! @unlink( $targetFile ) ) {
311 # If the deletion operation actually failed, bug out:
312 $wgOut->fileDeleteError( $targetFile );
313 return;
315 $dbw->delete( 'image', array( 'img_name' => $image ) );
316 $res = $dbw->select( 'oldimage', array( 'oi_archive_name' ), array( 'oi_name' => $image ) );
318 # Purge archive URLs from the squid
319 $urlArr = Array();
320 while ( $s = $dbw->fetchObject( $res ) ) {
321 $this->doDeleteOldImage( $s->oi_archive_name );
322 $urlArr[] = $wgInternalServer.wfImageArchiveUrl( $s->oi_archive_name );
325 # And also the HTML of all pages using this image
326 $linksTo = $this->img->getLinksTo();
327 if ( $wgUseSquid ) {
328 $u = SquidUpdate::newFromTitles( $linksTo, $urlArr );
329 array_push( $wgPostCommitUpdateList, $u );
332 $dbw->delete( 'oldimage', array( 'oi_name' => $image ) );
334 # Image itself is now gone, and database is cleaned.
335 # Now we remove the image description page.
337 $article = new Article( $this->mTitle );
338 $article->doDeleteArticle( $reason ); # ignore errors
340 # Invalidate parser cache and client cache for pages using this image
341 # This is left until relatively late to reduce lock time
342 Title::touchArray( $linksTo );
344 /* Delete thumbnails and refresh image metadata cache */
345 $this->img->purgeCache();
348 $deleted = $image;
351 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
352 $wgOut->setRobotpolicy( 'noindex,nofollow' );
354 $sk = $wgUser->getSkin();
355 $loglink = $sk->makeKnownLinkObj(
356 Title::makeTitle( NS_SPECIAL, 'Log/delete' ),
357 wfMsg( 'deletionlog' ) );
359 $text = wfMsg( 'deletedtext', $deleted, $loglink );
361 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
362 $wgOut->returnToMain( false, $this->mTitle->getPrefixedText() );
365 function doDeleteOldImage( $oldimage )
367 global $wgOut;
369 $name = substr( $oldimage, 15 );
370 $archive = wfImageArchiveDir( $name );
372 # Delete the image if it exists. Sometimes the file will be missing
373 # due to manual intervention or weird sync problems; treat that
374 # condition gracefully and continue to delete the database entry.
375 # Also some records may end up with an empty oi_archive_name field
376 # if the original file was missing when a new upload was made;
377 # don't try to delete the directory then!
379 $targetFile = "{$archive}/{$oldimage}";
380 if( $oldimage != '' && file_exists( $targetFile ) && !@unlink( $targetFile ) ) {
381 # If we actually have a file and can't delete it, throw an error.
382 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
383 } else {
384 # Log the deletion
385 $log = new LogPage( 'delete' );
386 $log->addEntry( 'delete', $this->mTitle, wfMsg('deletedrevision',$oldimage) );
390 function revert()
392 global $wgOut, $wgRequest, $wgUser;
393 global $wgUseSquid, $wgInternalServer, $wgDeferredUpdateList;
395 $oldimage = $wgRequest->getText( 'oldimage' );
396 if ( strlen( $oldimage ) < 16 ) {
397 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
398 return;
400 if ( strstr( $oldimage, "/" ) || strstr( $oldimage, "\\" ) ) {
401 $wgOut->unexpectedValueError( 'oldimage', htmlspecialchars($oldimage) );
402 return;
405 if ( wfReadOnly() ) {
406 $wgOut->readOnlyPage();
407 return;
409 if( $wgUser->isAnon() ) {
410 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
411 return;
413 if ( ! $this->mTitle->userCanEdit() ) {
414 $wgOut->sysopRequired();
415 return;
417 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $oldimage ) ) {
418 $wgOut->errorpage( 'internalerror', 'sessionfailure' );
419 return;
421 $name = substr( $oldimage, 15 );
423 $dest = wfImageDir( $name );
424 $archive = wfImageArchiveDir( $name );
425 $curfile = "{$dest}/{$name}";
427 if ( ! is_file( $curfile ) ) {
428 $wgOut->fileNotFoundError( htmlspecialchars( $curfile ) );
429 return;
431 $oldver = wfTimestampNow() . "!{$name}";
433 $dbr =& wfGetDB( DB_SLAVE );
434 $size = $dbr->selectField( 'oldimage', 'oi_size', array( 'oi_archive_name' => $oldimage ) );
436 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
437 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
438 return;
440 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
441 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
444 # Record upload and update metadata cache
445 $img = Image::newFromName( $name );
446 $img->recordUpload( $oldver, wfMsg( "reverted" ) );
448 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
449 $wgOut->setRobotpolicy( 'noindex,nofollow' );
450 $wgOut->addHTML( wfMsg( 'imagereverted' ) );
452 $descTitle = $img->getTitle();
453 $wgOut->returnToMain( false, $descTitle->getPrefixedText() );
458 * @todo document
459 * @package MediaWiki
461 class ImageHistoryList {
462 function ImageHistoryList( &$skin ) {
463 $this->skin =& $skin;
466 function beginImageHistoryList() {
467 $s = "\n<h2>" . wfMsg( 'imghistory' ) . "</h2>\n" .
468 "<p>" . wfMsg( 'imghistlegend' ) . "</p>\n".'<ul class="special">';
469 return $s;
472 function endImageHistoryList() {
473 $s = "</ul>\n";
474 return $s;
477 function imageHistoryLine( $iscur, $timestamp, $img, $user, $usertext, $size, $description ) {
478 global $wgUser, $wgLang, $wgContLang, $wgTitle;
480 $datetime = $wgLang->timeanddate( $timestamp, true );
481 $del = wfMsg( 'deleteimg' );
482 $delall = wfMsg( 'deleteimgcompletely' );
483 $cur = wfMsg( 'cur' );
485 if ( $iscur ) {
486 $url = Image::imageUrl( $img );
487 $rlink = $cur;
488 if ( $wgUser->isAllowed('delete') ) {
489 $link = $wgTitle->escapeLocalURL( 'image=' . $wgTitle->getPartialURL() .
490 '&action=delete' );
491 $style = $this->skin->getInternalLinkAttributes( $link, $delall );
493 $dlink = '<a href="'.$link.'"'.$style.'>'.$delall.'</a>';
494 } else {
495 $dlink = $del;
497 } else {
498 $url = htmlspecialchars( wfImageArchiveUrl( $img ) );
499 if( $wgUser->getID() != 0 && $wgTitle->userCanEdit() ) {
500 $token = urlencode( $wgUser->editToken( $img ) );
501 $rlink = $this->skin->makeKnownLinkObj( $wgTitle,
502 wfMsg( 'revertimg' ), 'action=revert&oldimage=' .
503 urlencode( $img ) . "&wpEditToken=$token" );
504 $dlink = $this->skin->makeKnownLinkObj( $wgTitle,
505 $del, 'action=delete&oldimage=' . urlencode( $img ) .
506 "&wpEditToken=$token" );
507 } else {
508 # Having live active links for non-logged in users
509 # means that bots and spiders crawling our site can
510 # inadvertently change content. Baaaad idea.
511 $rlink = wfMsg( 'revertimg' );
512 $dlink = $del;
515 if ( 0 == $user ) {
516 $userlink = $usertext;
517 } else {
518 $userlink = $this->skin->makeLinkObj(
519 Title::makeTitle( NS_USER, $usertext ),
520 $usertext );
522 $nbytes = wfMsg( 'nbytes', $size );
523 $style = $this->skin->getInternalLinkAttributes( $url, $datetime );
525 $s = "<li> ({$dlink}) ({$rlink}) <a href=\"{$url}\"{$style}>{$datetime}</a>"
526 . " . . {$userlink} ({$nbytes})";
528 $s .= $this->skin->commentBlock( $description, $wgTitle );
529 $s .= "</li>\n";
530 return $s;