Fix regression in even sizing of diff columns; forgot to restore a couple bits I...
[mediawiki.git] / includes / Image.php
blobb456c1d7a43fc7ac97915aa8d9c9d1399f884920
1 <?php
2 /**
3 */
5 /**
6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
14 /**
15 * Bump this number when serialized cache records may be incompatible.
17 define( 'MW_IMAGE_VERSION', 2 );
19 /**
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
25 * @addtogroup Media
27 class Image
29 const DELETED_FILE = 1;
30 const DELETED_COMMENT = 2;
31 const DELETED_USER = 4;
32 const DELETED_RESTRICTED = 8;
33 const RENDER_NOW = 1;
35 /**#@+
36 * @private
38 var $name, # name of the image (constructor)
39 $imagePath, # Path of the image (loadFromXxx)
40 $url, # Image URL (accessor)
41 $title, # Title object for this image (constructor)
42 $fileExists, # does the image file exist on disk? (loadFromXxx)
43 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
44 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
45 $historyRes, # result of the query for the image's history (nextHistoryLine)
46 $width, # \
47 $height, # |
48 $bits, # --- returned by getimagesize (loadFromXxx)
49 $attr, # /
50 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
51 $mime, # MIME type, determined by MimeMagic::guessMimeType
52 $extension, # The file extension (constructor)
53 $size, # Size in bytes (loadFromXxx)
54 $metadata, # Metadata
55 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
56 $page, # Page to render when creating thumbnails
57 $lastError; # Error string associated with a thumbnail display error
60 /**#@-*/
62 /**
63 * Create an Image object from an image name
65 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
66 * @public
68 public static function newFromName( $name ) {
69 $title = Title::makeTitleSafe( NS_IMAGE, $name );
70 if ( is_object( $title ) ) {
71 return new Image( $title );
72 } else {
73 return NULL;
77 /**
78 * Obsolete factory function, use constructor
79 * @deprecated
81 function newFromTitle( $title ) {
82 return new Image( $title );
85 function Image( $title ) {
86 if( !is_object( $title ) ) {
87 throw new MWException( 'Image constructor given bogus title.' );
89 $this->title =& $title;
90 $this->name = $title->getDBkey();
91 $this->metadata = '';
93 $n = strrpos( $this->name, '.' );
94 $this->extension = Image::normalizeExtension( $n ?
95 substr( $this->name, $n + 1 ) : '' );
96 $this->historyLine = 0;
98 $this->dataLoaded = false;
102 * Normalize a file extension to the common form, and ensure it's clean.
103 * Extensions with non-alphanumeric characters will be discarded.
105 * @param $ext string (without the .)
106 * @return string
108 static function normalizeExtension( $ext ) {
109 $lower = strtolower( $ext );
110 $squish = array(
111 'htm' => 'html',
112 'jpeg' => 'jpg',
113 'mpeg' => 'mpg',
114 'tiff' => 'tif' );
115 if( isset( $squish[$lower] ) ) {
116 return $squish[$lower];
117 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
118 return $lower;
119 } else {
120 return '';
125 * Get the memcached keys
126 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
128 function getCacheKeys( ) {
129 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
131 $hashedName = md5($this->name);
132 $keys = array( wfMemcKey( 'Image', $hashedName ) );
133 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
134 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
136 return $keys;
140 * Try to load image metadata from memcached. Returns true on success.
142 function loadFromCache() {
143 global $wgUseSharedUploads, $wgMemc;
144 wfProfileIn( __METHOD__ );
145 $this->dataLoaded = false;
146 $keys = $this->getCacheKeys();
147 $cachedValues = $wgMemc->get( $keys[0] );
149 // Check if the key existed and belongs to this version of MediaWiki
150 if (!empty($cachedValues) && is_array($cachedValues)
151 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
152 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
154 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
155 # if this is shared file, we need to check if image
156 # in shared repository has not changed
157 if ( isset( $keys[1] ) ) {
158 $commonsCachedValues = $wgMemc->get( $keys[1] );
159 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
160 && isset($commonsCachedValues['version'])
161 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
162 && isset($commonsCachedValues['mime'])) {
163 wfDebug( "Pulling image metadata from shared repository cache\n" );
164 $this->name = $commonsCachedValues['name'];
165 $this->imagePath = $commonsCachedValues['imagePath'];
166 $this->fileExists = $commonsCachedValues['fileExists'];
167 $this->width = $commonsCachedValues['width'];
168 $this->height = $commonsCachedValues['height'];
169 $this->bits = $commonsCachedValues['bits'];
170 $this->type = $commonsCachedValues['type'];
171 $this->mime = $commonsCachedValues['mime'];
172 $this->metadata = $commonsCachedValues['metadata'];
173 $this->size = $commonsCachedValues['size'];
174 $this->fromSharedDirectory = true;
175 $this->dataLoaded = true;
176 $this->imagePath = $this->getFullPath(true);
179 } else {
180 wfDebug( "Pulling image metadata from local cache\n" );
181 $this->name = $cachedValues['name'];
182 $this->imagePath = $cachedValues['imagePath'];
183 $this->fileExists = $cachedValues['fileExists'];
184 $this->width = $cachedValues['width'];
185 $this->height = $cachedValues['height'];
186 $this->bits = $cachedValues['bits'];
187 $this->type = $cachedValues['type'];
188 $this->mime = $cachedValues['mime'];
189 $this->metadata = $cachedValues['metadata'];
190 $this->size = $cachedValues['size'];
191 $this->fromSharedDirectory = false;
192 $this->dataLoaded = true;
193 $this->imagePath = $this->getFullPath();
196 if ( $this->dataLoaded ) {
197 wfIncrStats( 'image_cache_hit' );
198 } else {
199 wfIncrStats( 'image_cache_miss' );
202 wfProfileOut( __METHOD__ );
203 return $this->dataLoaded;
207 * Save the image metadata to memcached
209 function saveToCache() {
210 global $wgMemc, $wgUseSharedUploads;
211 $this->load();
212 $keys = $this->getCacheKeys();
213 // We can't cache negative metadata for non-existent files,
214 // because if the file later appears in commons, the local
215 // keys won't be purged.
216 if ( $this->fileExists || !$wgUseSharedUploads ) {
217 $cachedValues = array(
218 'version' => MW_IMAGE_VERSION,
219 'name' => $this->name,
220 'imagePath' => $this->imagePath,
221 'fileExists' => $this->fileExists,
222 'fromShared' => $this->fromSharedDirectory,
223 'width' => $this->width,
224 'height' => $this->height,
225 'bits' => $this->bits,
226 'type' => $this->type,
227 'mime' => $this->mime,
228 'metadata' => $this->metadata,
229 'size' => $this->size );
231 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
232 } else {
233 // However we should clear them, so they aren't leftover
234 // if we've deleted the file.
235 $wgMemc->delete( $keys[0] );
240 * Load metadata from the file itself
242 function loadFromFile() {
243 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
244 wfProfileIn( __METHOD__ );
245 $this->imagePath = $this->getFullPath();
246 $this->fileExists = file_exists( $this->imagePath );
247 $this->fromSharedDirectory = false;
248 $gis = array();
250 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
252 # If the file is not found, and a shared upload directory is used, look for it there.
253 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
254 # In case we're on a wgCapitalLinks=false wiki, we
255 # capitalize the first letter of the filename before
256 # looking it up in the shared repository.
257 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
258 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
259 if ( $this->fileExists ) {
260 $this->name = $sharedImage->name;
261 $this->imagePath = $this->getFullPath(true);
262 $this->fromSharedDirectory = true;
267 if ( $this->fileExists ) {
268 $magic=& MimeMagic::singleton();
270 $this->mime = $magic->guessMimeType($this->imagePath,true);
271 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
272 $handler = MediaHandler::getHandler( $this->mime );
274 # Get size in bytes
275 $this->size = filesize( $this->imagePath );
277 # Height, width and metadata
278 if ( $handler ) {
279 $gis = $handler->getImageSize( $this, $this->imagePath );
280 $this->metadata = $handler->getMetadata( $this, $this->imagePath );
281 } else {
282 $gis = false;
283 $this->metadata = '';
286 wfDebug(__METHOD__.': '.$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
288 else {
289 $this->mime = NULL;
290 $this->type = MEDIATYPE_UNKNOWN;
291 $this->metadata = '';
292 wfDebug(__METHOD__.': '.$this->imagePath." NOT FOUND!\n");
295 if( $gis ) {
296 $this->width = $gis[0];
297 $this->height = $gis[1];
298 } else {
299 $this->width = 0;
300 $this->height = 0;
303 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
305 #NOTE: we have to set this flag early to avoid load() to be called
306 # be some of the functions below. This may lead to recursion or other bad things!
307 # as ther's only one thread of execution, this should be safe anyway.
308 $this->dataLoaded = true;
310 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
311 else $this->bits = 0;
313 wfProfileOut( __METHOD__ );
317 * Load image metadata from the DB
319 function loadFromDB() {
320 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
321 wfProfileIn( __METHOD__ );
323 $dbr = wfGetDB( DB_SLAVE );
325 $row = $dbr->selectRow( 'image',
326 array( 'img_size', 'img_width', 'img_height', 'img_bits',
327 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
328 array( 'img_name' => $this->name ), __METHOD__ );
329 if ( $row ) {
330 $this->fromSharedDirectory = false;
331 $this->fileExists = true;
332 $this->loadFromRow( $row );
333 $this->imagePath = $this->getFullPath();
334 // Check for rows from a previous schema, quietly upgrade them
335 $this->maybeUpgradeRow();
336 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
337 # In case we're on a wgCapitalLinks=false wiki, we
338 # capitalize the first letter of the filename before
339 # looking it up in the shared repository.
340 $name = $wgContLang->ucfirst($this->name);
341 $dbc = Image::getCommonsDB();
343 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
344 array(
345 'img_size', 'img_width', 'img_height', 'img_bits',
346 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
347 array( 'img_name' => $name ), __METHOD__ );
348 if ( $row ) {
349 $this->fromSharedDirectory = true;
350 $this->fileExists = true;
351 $this->imagePath = $this->getFullPath(true);
352 $this->name = $name;
353 $this->loadFromRow( $row );
355 // Check for rows from a previous schema, quietly upgrade them
356 $this->maybeUpgradeRow();
360 if ( !$row ) {
361 $this->size = 0;
362 $this->width = 0;
363 $this->height = 0;
364 $this->bits = 0;
365 $this->type = 0;
366 $this->fileExists = false;
367 $this->fromSharedDirectory = false;
368 $this->metadata = '';
369 $this->mime = false;
372 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
373 $this->dataLoaded = true;
374 wfProfileOut( __METHOD__ );
378 * Load image metadata from a DB result row
380 function loadFromRow( &$row ) {
381 $this->size = $row->img_size;
382 $this->width = $row->img_width;
383 $this->height = $row->img_height;
384 $this->bits = $row->img_bits;
385 $this->type = $row->img_media_type;
387 $major= $row->img_major_mime;
388 $minor= $row->img_minor_mime;
390 if (!$major) $this->mime = "unknown/unknown";
391 else {
392 if (!$minor) $minor= "unknown";
393 $this->mime = $major.'/'.$minor;
395 $this->metadata = $row->img_metadata;
397 $this->dataLoaded = true;
401 * Load image metadata from cache or DB, unless already loaded
403 function load() {
404 global $wgSharedUploadDBname, $wgUseSharedUploads;
405 if ( !$this->dataLoaded ) {
406 if ( !$this->loadFromCache() ) {
407 $this->loadFromDB();
408 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
409 $this->loadFromFile();
410 } elseif ( $this->fileExists || !$wgUseSharedUploads ) {
411 // We can do negative caching for local images, because the cache
412 // will be purged on upload. But we can't do it when shared images
413 // are enabled, since updates to that won't purge foreign caches.
414 $this->saveToCache();
417 $this->dataLoaded = true;
422 * Upgrade a row if it needs it
424 function maybeUpgradeRow() {
425 if ( is_null($this->type) || $this->mime == 'image/svg' ) {
426 $this->upgradeRow();
427 } else {
428 $handler = $this->getHandler();
429 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
430 $this->upgradeRow();
436 * Fix assorted version-related problems with the image row by reloading it from the file
438 function upgradeRow() {
439 global $wgDBname, $wgSharedUploadDBname;
440 wfProfileIn( __METHOD__ );
442 $this->loadFromFile();
444 if ( $this->fromSharedDirectory ) {
445 if ( !$wgSharedUploadDBname ) {
446 wfProfileOut( __METHOD__ );
447 return;
450 // Write to the other DB using selectDB, not database selectors
451 // This avoids breaking replication in MySQL
452 $dbw = Image::getCommonsDB();
453 } else {
454 $dbw = wfGetDB( DB_MASTER );
457 list( $major, $minor ) = self::splitMime( $this->mime );
459 wfDebug(__METHOD__.': upgrading '.$this->name." to the current schema\n");
461 $dbw->update( 'image',
462 array(
463 'img_width' => $this->width,
464 'img_height' => $this->height,
465 'img_bits' => $this->bits,
466 'img_media_type' => $this->type,
467 'img_major_mime' => $major,
468 'img_minor_mime' => $minor,
469 'img_metadata' => $this->metadata,
470 ), array( 'img_name' => $this->name ), __METHOD__
472 if ( $this->fromSharedDirectory ) {
473 $dbw->selectDB( $wgDBname );
475 wfProfileOut( __METHOD__ );
479 * Split an internet media type into its two components; if not
480 * a two-part name, set the minor type to 'unknown'.
482 * @param $mime "text/html" etc
483 * @return array ("text", "html") etc
485 static function splitMime( $mime ) {
486 if( strpos( $mime, '/' ) !== false ) {
487 return explode( '/', $mime, 2 );
488 } else {
489 return array( $mime, 'unknown' );
494 * Return the name of this image
495 * @public
497 function getName() {
498 return $this->name;
502 * Return the associated title object
503 * @public
505 function getTitle() {
506 return $this->title;
510 * Return the URL of the image file
511 * @public
513 function getURL() {
514 if ( !$this->url ) {
515 $this->load();
516 if($this->fileExists) {
517 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
518 } else {
519 $this->url = '';
522 return $this->url;
525 function getViewURL() {
526 if( $this->mustRender()) {
527 if( $this->canRender() ) {
528 return $this->createThumb( $this->getWidth() );
530 else {
531 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
532 return $this->getURL(); #hm... return NULL?
534 } else {
535 return $this->getURL();
540 * Return the image path of the image in the
541 * local file system as an absolute path
542 * @public
544 function getImagePath() {
545 $this->load();
546 return $this->imagePath;
550 * Return the width of the image
552 * Returns false on error
553 * @public
555 function getWidth( $page = 1 ) {
556 $this->load();
557 if ( $this->isMultipage() ) {
558 $dim = $this->getHandler()->getPageDimensions( $this, $page );
559 if ( $dim ) {
560 return $dim['width'];
561 } else {
562 return false;
564 } else {
565 return $this->width;
570 * Return the height of the image
572 * Returns false on error
573 * @public
575 function getHeight( $page = 1 ) {
576 $this->load();
577 if ( $this->isMultipage() ) {
578 $dim = $this->getHandler()->getPageDimensions( $this, $page );
579 if ( $dim ) {
580 return $dim['height'];
581 } else {
582 return false;
584 } else {
585 return $this->height;
590 * Get handler-specific metadata
592 function getMetadata() {
593 $this->load();
594 return $this->metadata;
598 * Return the size of the image file, in bytes
599 * @public
601 function getSize() {
602 $this->load();
603 return $this->size;
607 * Returns the mime type of the file.
609 function getMimeType() {
610 $this->load();
611 return $this->mime;
615 * Return the type of the media in the file.
616 * Use the value returned by this function with the MEDIATYPE_xxx constants.
618 function getMediaType() {
619 $this->load();
620 return $this->type;
624 * Checks if the file can be presented to the browser as a bitmap.
626 * Currently, this checks if the file is an image format
627 * that can be converted to a format
628 * supported by all browsers (namely GIF, PNG and JPEG),
629 * or if it is an SVG image and SVG conversion is enabled.
631 * @todo remember the result of this check.
633 function canRender() {
634 $handler = $this->getHandler();
635 return $handler && $handler->canRender();
639 * Return true if the file is of a type that can't be directly
640 * rendered by typical browsers and needs to be re-rasterized.
642 * This returns true for everything but the bitmap types
643 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
644 * also return true for any non-image formats.
646 * @return bool
648 function mustRender() {
649 $handler = $this->getHandler();
650 return $handler && $handler->mustRender();
654 * Determines if this media file may be shown inline on a page.
656 * This is currently synonymous to canRender(), but this could be
657 * extended to also allow inline display of other media,
658 * like flash animations or videos. If you do so, please keep in mind that
659 * that could be a security risk.
661 function allowInlineDisplay() {
662 return $this->canRender();
666 * Determines if this media file is in a format that is unlikely to
667 * contain viruses or malicious content. It uses the global
668 * $wgTrustedMediaFormats list to determine if the file is safe.
670 * This is used to show a warning on the description page of non-safe files.
671 * It may also be used to disallow direct [[media:...]] links to such files.
673 * Note that this function will always return true if allowInlineDisplay()
674 * or isTrustedFile() is true for this file.
676 function isSafeFile() {
677 if ($this->allowInlineDisplay()) return true;
678 if ($this->isTrustedFile()) return true;
680 global $wgTrustedMediaFormats;
682 $type= $this->getMediaType();
683 $mime= $this->getMimeType();
684 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
686 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
687 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
689 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
690 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
692 return false;
695 /** Returns true if the file is flagged as trusted. Files flagged that way
696 * can be linked to directly, even if that is not allowed for this type of
697 * file normally.
699 * This is a dummy function right now and always returns false. It could be
700 * implemented to extract a flag from the database. The trusted flag could be
701 * set on upload, if the user has sufficient privileges, to bypass script-
702 * and html-filters. It may even be coupled with cryptographics signatures
703 * or such.
705 function isTrustedFile() {
706 #this could be implemented to check a flag in the databas,
707 #look for signatures, etc
708 return false;
712 * Return the escapeLocalURL of this image
713 * @public
715 function getEscapeLocalURL( $query=false) {
716 return $this->getTitle()->escapeLocalURL( $query );
720 * Return the escapeFullURL of this image
721 * @public
723 function getEscapeFullURL() {
724 $this->getTitle();
725 return $this->title->escapeFullURL();
729 * Return the URL of an image, provided its name.
731 * @param string $name Name of the image, without the leading "Image:"
732 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
733 * @return string URL of $name image
734 * @public
736 static function imageUrl( $name, $fromSharedDirectory = false ) {
737 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
738 if($fromSharedDirectory) {
739 $base = '';
740 $path = $wgSharedUploadPath;
741 } else {
742 $base = $wgUploadBaseUrl;
743 $path = $wgUploadPath;
745 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
746 return wfUrlencode( $url );
750 * Returns true if the image file exists on disk.
751 * @return boolean Whether image file exist on disk.
752 * @public
754 function exists() {
755 $this->load();
756 return $this->fileExists;
760 * @todo document
761 * @private
763 function thumbUrlFromName( $thumbName, $subdir = 'thumb' ) {
764 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
765 if($this->fromSharedDirectory) {
766 $base = '';
767 $path = $wgSharedUploadPath;
768 } else {
769 $base = $wgUploadBaseUrl;
770 $path = $wgUploadPath;
772 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
773 $hashdir = wfGetHashPath($this->name, $this->fromSharedDirectory) .
774 wfUrlencode( $this->name );
775 } else {
776 $hashdir = '';
778 $url = "{$base}{$path}/{$subdir}{$hashdir}/" . wfUrlencode( $thumbName );
779 return $url;
783 * @deprecated Use $image->transform()->getUrl() or thumbUrlFromName()
785 function thumbUrl( $width, $subdir = 'thumb' ) {
786 $name = $this->thumbName( array( 'width' => $width ) );
787 if ( strval( $name ) !== '' ) {
788 return array( false, $this->thumbUrlFromName( $name, $subdir ) );
789 } else {
790 return array( false, false );
794 function getTransformScript() {
795 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
796 if ( $this->fromSharedDirectory ) {
797 $script = $wgSharedThumbnailScriptPath;
798 } else {
799 $script = $wgThumbnailScriptPath;
801 if ( $script ) {
802 return "$script?f=" . urlencode( $this->name );
803 } else {
804 return false;
809 * Get a ThumbnailImage which is the same size as the source
811 function getUnscaledThumb( $page = false ) {
812 if ( $page ) {
813 $params = array(
814 'page' => $page,
815 'width' => $this->getWidth( $page )
817 } else {
818 $params = array( 'width' => $this->getWidth() );
820 return $this->transform( $params );
824 * Return the file name of a thumbnail with the specified parameters
826 * @param array $params Handler-specific parameters
827 * @private
829 function thumbName( $params ) {
830 $handler = $this->getHandler();
831 if ( !$handler ) {
832 return null;
834 list( $thumbExt, /* $thumbMime */ ) = self::getThumbType( $this->extension, $this->mime );
835 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name;
836 if ( $thumbExt != $this->extension ) {
837 $thumbName .= ".$thumbExt";
839 return $thumbName;
843 * Create a thumbnail of the image having the specified width/height.
844 * The thumbnail will not be created if the width is larger than the
845 * image's width. Let the browser do the scaling in this case.
846 * The thumbnail is stored on disk and is only computed if the thumbnail
847 * file does not exist OR if it is older than the image.
848 * Returns the URL.
850 * Keeps aspect ratio of original image. If both width and height are
851 * specified, the generated image will be no bigger than width x height,
852 * and will also have correct aspect ratio.
854 * @param integer $width maximum width of the generated thumbnail
855 * @param integer $height maximum height of the image (optional)
856 * @public
858 function createThumb( $width, $height = -1 ) {
859 $params = array( 'width' => $width );
860 if ( $height != -1 ) {
861 $params['height'] = $height;
863 $thumb = $this->transform( $params );
864 if( is_null( $thumb ) || $thumb->isError() ) return '';
865 return $thumb->getUrl();
869 * As createThumb, but returns a ThumbnailImage object. This can
870 * provide access to the actual file, the real size of the thumb,
871 * and can produce a convenient <img> tag for you.
873 * For non-image formats, this may return a filetype-specific icon.
875 * @param integer $width maximum width of the generated thumbnail
876 * @param integer $height maximum height of the image (optional)
877 * @param boolean $render True to render the thumbnail if it doesn't exist,
878 * false to just return the URL
880 * @return ThumbnailImage or null on failure
881 * @public
883 * @deprecated use transform()
885 function getThumbnail( $width, $height=-1, $render = true ) {
886 $params = array( 'width' => $width );
887 if ( $height != -1 ) {
888 $params['height'] = $height;
890 $flags = $render ? self::RENDER_NOW : 0;
891 return $this->transform( $params, $flags );
895 * Transform a media file
897 * @param array $params An associative array of handler-specific parameters. Typical
898 * keys are width, height and page.
899 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
900 * @return MediaTransformOutput
902 function transform( $params, $flags = 0 ) {
903 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
905 wfProfileIn( __METHOD__ );
906 do {
907 $handler = $this->getHandler();
908 if ( !$handler || !$handler->canRender() ) {
909 // not a bitmap or renderable image, don't try.
910 $thumb = $this->iconThumb();
911 break;
914 $script = $this->getTransformScript();
915 if ( $script && !($flags & self::RENDER_NOW) ) {
916 // Use a script to transform on client request
917 $thumb = $handler->getScriptedTransform( $this, $script, $params );
918 break;
921 $normalisedParams = $params;
922 $handler->normaliseParams( $this, $normalisedParams );
923 list( $thumbExt, $thumbMime ) = self::getThumbType( $this->extension, $this->mime );
924 $thumbName = $this->thumbName( $normalisedParams );
925 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ) . "/$thumbName";
926 $thumbUrl = $this->thumbUrlFromName( $thumbName );
929 if ( !$wgGenerateThumbnailOnParse && !($flags & self::RENDER_NOW ) ) {
930 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
931 break;
934 wfDebug( "Doing stat for $thumbPath\n" );
935 $this->migrateThumbFile( $thumbName );
936 if ( file_exists( $thumbPath ) ) {
937 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
938 break;
941 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
943 // Ignore errors if requested
944 if ( !$thumb ) {
945 $thumb = null;
946 } elseif ( $thumb->isError() ) {
947 $this->lastError = $thumb->toText();
948 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
949 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
953 if ( $wgUseSquid ) {
954 wfPurgeSquidServers( array( $thumbUrl ) );
956 } while (false);
958 wfProfileOut( __METHOD__ );
959 return $thumb;
963 * Fix thumbnail files from 1.4 or before, with extreme prejudice
965 function migrateThumbFile( $thumbName ) {
966 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
967 $thumbPath = "$thumbDir/$thumbName";
968 if ( is_dir( $thumbPath ) ) {
969 // Directory where file should be
970 // This happened occasionally due to broken migration code in 1.5
971 // Rename to broken-*
972 global $wgUploadDirectory;
973 for ( $i = 0; $i < 100 ; $i++ ) {
974 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
975 if ( !file_exists( $broken ) ) {
976 rename( $thumbPath, $broken );
977 break;
980 // Doesn't exist anymore
981 clearstatcache();
983 if ( is_file( $thumbDir ) ) {
984 // File where directory should be
985 unlink( $thumbDir );
986 // Doesn't exist anymore
987 clearstatcache();
992 * Get a MediaHandler instance for this image
994 function getHandler() {
995 return MediaHandler::getHandler( $this->getMimeType() );
999 * Get a ThumbnailImage representing a file type icon
1000 * @return ThumbnailImage
1002 function iconThumb() {
1003 global $wgStylePath, $wgStyleDirectory;
1005 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
1006 foreach( $try as $icon ) {
1007 $path = '/common/images/icons/' . $icon;
1008 $filepath = $wgStyleDirectory . $path;
1009 if( file_exists( $filepath ) ) {
1010 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1013 return null;
1017 * Get last thumbnailing error.
1018 * Largely obsolete.
1020 function getLastError() {
1021 return $this->lastError;
1025 * Get all thumbnail names previously generated for this image
1027 function getThumbnails( $shared = false ) {
1028 if ( Image::isHashed( $shared ) ) {
1029 $this->load();
1030 $files = array();
1031 $dir = wfImageThumbDir( $this->name, $shared );
1033 if ( is_dir( $dir ) ) {
1034 $handle = opendir( $dir );
1036 if ( $handle ) {
1037 while ( false !== ( $file = readdir($handle) ) ) {
1038 if ( $file{0} != '.' ) {
1039 $files[] = $file;
1042 closedir( $handle );
1045 } else {
1046 $files = array();
1049 return $files;
1053 * Refresh metadata in memcached, but don't touch thumbnails or squid
1055 function purgeMetadataCache() {
1056 clearstatcache();
1057 $this->loadFromFile();
1058 $this->saveToCache();
1062 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1064 function purgeCache( $archiveFiles = array(), $shared = false ) {
1065 global $wgUseSquid;
1067 // Refresh metadata cache
1068 $this->purgeMetadataCache();
1070 // Delete thumbnails
1071 $files = $this->getThumbnails( $shared );
1072 $dir = wfImageThumbDir( $this->name, $shared );
1073 $urls = array();
1074 foreach ( $files as $file ) {
1075 # Check that the base image name is part of the thumb name
1076 # This is a basic sanity check to avoid erasing unrelated directories
1077 if ( strpos( $file, $this->name ) !== false ) {
1078 $url = $this->thumbUrlFromName( $file );
1079 $urls[] = $url;
1080 @unlink( "$dir/$file" );
1084 // Purge the squid
1085 if ( $wgUseSquid ) {
1086 $urls[] = $this->getURL();
1087 foreach ( $archiveFiles as $file ) {
1088 $urls[] = wfImageArchiveUrl( $file );
1090 wfPurgeSquidServers( $urls );
1095 * Purge the image description page, but don't go after
1096 * pages using the image. Use when modifying file history
1097 * but not the current data.
1099 function purgeDescription() {
1100 $page = Title::makeTitle( NS_IMAGE, $this->name );
1101 $page->invalidateCache();
1102 $page->purgeSquid();
1106 * Purge metadata and all affected pages when the image is created,
1107 * deleted, or majorly updated. A set of additional URLs may be
1108 * passed to purge, such as specific image files which have changed.
1109 * @param $urlArray array
1111 function purgeEverything( $urlArr=array() ) {
1112 // Delete thumbnails and refresh image metadata cache
1113 $this->purgeCache();
1114 $this->purgeDescription();
1116 // Purge cache of all pages using this image
1117 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1118 $update->doUpdate();
1122 * Return the image history of this image, line by line.
1123 * starts with current version, then old versions.
1124 * uses $this->historyLine to check which line to return:
1125 * 0 return line for current version
1126 * 1 query for old versions, return first one
1127 * 2, ... return next old version from above query
1129 * @public
1131 function nextHistoryLine() {
1132 $dbr = wfGetDB( DB_SLAVE );
1134 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1135 $this->historyRes = $dbr->select( 'image',
1136 array(
1137 'img_size',
1138 'img_description',
1139 'img_user','img_user_text',
1140 'img_timestamp',
1141 'img_width',
1142 'img_height',
1143 "'' AS oi_archive_name"
1145 array( 'img_name' => $this->title->getDBkey() ),
1146 __METHOD__
1148 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1149 return FALSE;
1151 } else if ( $this->historyLine == 1 ) {
1152 $this->historyRes = $dbr->select( 'oldimage',
1153 array(
1154 'oi_size AS img_size',
1155 'oi_description AS img_description',
1156 'oi_user AS img_user',
1157 'oi_user_text AS img_user_text',
1158 'oi_timestamp AS img_timestamp',
1159 'oi_width as img_width',
1160 'oi_height as img_height',
1161 'oi_archive_name'
1163 array( 'oi_name' => $this->title->getDBkey() ),
1164 __METHOD__,
1165 array( 'ORDER BY' => 'oi_timestamp DESC' )
1168 $this->historyLine ++;
1170 return $dbr->fetchObject( $this->historyRes );
1174 * Reset the history pointer to the first element of the history
1175 * @public
1177 function resetHistory() {
1178 $this->historyLine = 0;
1182 * Return the full filesystem path to the file. Note that this does
1183 * not mean that a file actually exists under that location.
1185 * This path depends on whether directory hashing is active or not,
1186 * i.e. whether the images are all found in the same directory,
1187 * or in hashed paths like /images/3/3c.
1189 * @public
1190 * @param boolean $fromSharedDirectory Return the path to the file
1191 * in a shared repository (see $wgUseSharedRepository and related
1192 * options in DefaultSettings.php) instead of a local one.
1195 function getFullPath( $fromSharedRepository = false ) {
1196 global $wgUploadDirectory, $wgSharedUploadDirectory;
1198 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1199 $wgUploadDirectory;
1201 // $wgSharedUploadDirectory may be false, if thumb.php is used
1202 if ( $dir ) {
1203 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1204 } else {
1205 $fullpath = false;
1208 return $fullpath;
1212 * @return bool
1214 public static function isHashed( $shared ) {
1215 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1216 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1220 * Record an image upload in the upload log and the image table
1222 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1223 global $wgUser, $wgUseCopyrightUpload;
1225 $dbw = wfGetDB( DB_MASTER );
1227 // Delete thumbnails and refresh the metadata cache
1228 $this->purgeCache();
1230 // Fail now if the image isn't there
1231 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1232 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1233 return false;
1236 if ( $wgUseCopyrightUpload ) {
1237 if ( $license != '' ) {
1238 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1240 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1241 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1242 "$licensetxt" .
1243 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1244 } else {
1245 if ( $license != '' ) {
1246 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1247 $textdesc = $filedesc .
1248 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1249 } else {
1250 $textdesc = $desc;
1254 $now = $dbw->timestamp();
1256 #split mime type
1257 if (strpos($this->mime,'/')!==false) {
1258 list($major,$minor)= explode('/',$this->mime,2);
1260 else {
1261 $major= $this->mime;
1262 $minor= "unknown";
1265 # Test to see if the row exists using INSERT IGNORE
1266 # This avoids race conditions by locking the row until the commit, and also
1267 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1268 $dbw->insert( 'image',
1269 array(
1270 'img_name' => $this->name,
1271 'img_size'=> $this->size,
1272 'img_width' => intval( $this->width ),
1273 'img_height' => intval( $this->height ),
1274 'img_bits' => $this->bits,
1275 'img_media_type' => $this->type,
1276 'img_major_mime' => $major,
1277 'img_minor_mime' => $minor,
1278 'img_timestamp' => $now,
1279 'img_description' => $desc,
1280 'img_user' => $wgUser->getID(),
1281 'img_user_text' => $wgUser->getName(),
1282 'img_metadata' => $this->metadata,
1284 __METHOD__,
1285 'IGNORE'
1288 if( $dbw->affectedRows() == 0 ) {
1289 # Collision, this is an update of an image
1290 # Insert previous contents into oldimage
1291 $dbw->insertSelect( 'oldimage', 'image',
1292 array(
1293 'oi_name' => 'img_name',
1294 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1295 'oi_size' => 'img_size',
1296 'oi_width' => 'img_width',
1297 'oi_height' => 'img_height',
1298 'oi_bits' => 'img_bits',
1299 'oi_timestamp' => 'img_timestamp',
1300 'oi_description' => 'img_description',
1301 'oi_user' => 'img_user',
1302 'oi_user_text' => 'img_user_text',
1303 ), array( 'img_name' => $this->name ), __METHOD__
1306 # Update the current image row
1307 $dbw->update( 'image',
1308 array( /* SET */
1309 'img_size' => $this->size,
1310 'img_width' => intval( $this->width ),
1311 'img_height' => intval( $this->height ),
1312 'img_bits' => $this->bits,
1313 'img_media_type' => $this->type,
1314 'img_major_mime' => $major,
1315 'img_minor_mime' => $minor,
1316 'img_timestamp' => $now,
1317 'img_description' => $desc,
1318 'img_user' => $wgUser->getID(),
1319 'img_user_text' => $wgUser->getName(),
1320 'img_metadata' => $this->metadata,
1321 ), array( /* WHERE */
1322 'img_name' => $this->name
1323 ), __METHOD__
1325 } else {
1326 # This is a new image
1327 # Update the image count
1328 $site_stats = $dbw->tableName( 'site_stats' );
1329 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1332 $descTitle = $this->getTitle();
1333 $article = new Article( $descTitle );
1334 $minor = false;
1335 $watch = $watch || $wgUser->isWatched( $descTitle );
1336 $suppressRC = true; // There's already a log entry, so don't double the RC load
1338 if( $descTitle->exists() ) {
1339 // TODO: insert a null revision into the page history for this update.
1340 if( $watch ) {
1341 $wgUser->addWatch( $descTitle );
1344 # Invalidate the cache for the description page
1345 $descTitle->invalidateCache();
1346 $descTitle->purgeSquid();
1347 } else {
1348 // New image; create the description page.
1349 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1352 # Hooks, hooks, the magic of hooks...
1353 wfRunHooks( 'FileUpload', array( $this ) );
1355 # Add the log entry
1356 $log = new LogPage( 'upload' );
1357 $log->addEntry( 'upload', $descTitle, $desc );
1359 # Commit the transaction now, in case something goes wrong later
1360 # The most important thing is that images don't get lost, especially archives
1361 $dbw->immediateCommit();
1363 # Invalidate cache for all pages using this image
1364 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1365 $update->doUpdate();
1367 return true;
1371 * Get an array of Title objects which are articles which use this image
1372 * Also adds their IDs to the link cache
1374 * This is mostly copied from Title::getLinksTo()
1376 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1378 function getLinksTo( $options = '' ) {
1379 wfProfileIn( __METHOD__ );
1381 if ( $options ) {
1382 $db = wfGetDB( DB_MASTER );
1383 } else {
1384 $db = wfGetDB( DB_SLAVE );
1386 $linkCache =& LinkCache::singleton();
1388 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1389 $encName = $db->addQuotes( $this->name );
1390 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1391 $res = $db->query( $sql, __METHOD__ );
1393 $retVal = array();
1394 if ( $db->numRows( $res ) ) {
1395 while ( $row = $db->fetchObject( $res ) ) {
1396 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1397 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1398 $retVal[] = $titleObj;
1402 $db->freeResult( $res );
1403 wfProfileOut( __METHOD__ );
1404 return $retVal;
1407 function getExifData() {
1408 $handler = $this->getHandler();
1409 if ( !$handler || $handler->getMetadataType( $this ) != 'exif' ) {
1410 return array();
1412 if ( !$this->metadata ) {
1413 return array();
1415 $exif = unserialize( $this->metadata );
1416 if ( !$exif ) {
1417 return array();
1419 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
1420 $format = new FormatExif( $exif );
1422 return $format->getFormattedData();
1426 * Returns true if the image does not come from the shared
1427 * image repository.
1429 * @return bool
1431 function isLocal() {
1432 return !$this->fromSharedDirectory;
1436 * Was this image ever deleted from the wiki?
1438 * @return bool
1440 function wasDeleted() {
1441 $title = Title::makeTitle( NS_IMAGE, $this->name );
1442 return ( $title->isDeleted() > 0 );
1446 * Delete all versions of the image.
1448 * Moves the files into an archive directory (or deletes them)
1449 * and removes the database rows.
1451 * Cache purging is done; logging is caller's responsibility.
1453 * @param $reason
1454 * @return true on success, false on some kind of failure
1456 function delete( $reason, $suppress=false ) {
1457 $transaction = new FSTransaction();
1458 $urlArr = array( $this->getURL() );
1460 if( !FileStore::lock() ) {
1461 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1462 return false;
1465 try {
1466 $dbw = wfGetDB( DB_MASTER );
1467 $dbw->begin();
1469 // Delete old versions
1470 $result = $dbw->select( 'oldimage',
1471 array( 'oi_archive_name' ),
1472 array( 'oi_name' => $this->name ) );
1474 while( $row = $dbw->fetchObject( $result ) ) {
1475 $oldName = $row->oi_archive_name;
1477 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1479 // We'll need to purge this URL from caches...
1480 $urlArr[] = wfImageArchiveUrl( $oldName );
1482 $dbw->freeResult( $result );
1484 // And the current version...
1485 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1487 $dbw->immediateCommit();
1488 } catch( MWException $e ) {
1489 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1490 $transaction->rollback();
1491 FileStore::unlock();
1492 throw $e;
1495 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1496 $transaction->commit();
1497 FileStore::unlock();
1500 // Update site_stats
1501 $site_stats = $dbw->tableName( 'site_stats' );
1502 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1504 $this->purgeEverything( $urlArr );
1506 return true;
1511 * Delete an old version of the image.
1513 * Moves the file into an archive directory (or deletes it)
1514 * and removes the database row.
1516 * Cache purging is done; logging is caller's responsibility.
1518 * @param $reason
1519 * @throws MWException or FSException on database or filestore failure
1520 * @return true on success, false on some kind of failure
1522 function deleteOld( $archiveName, $reason, $suppress=false ) {
1523 $transaction = new FSTransaction();
1524 $urlArr = array();
1526 if( !FileStore::lock() ) {
1527 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1528 return false;
1531 $transaction = new FSTransaction();
1532 try {
1533 $dbw = wfGetDB( DB_MASTER );
1534 $dbw->begin();
1535 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1536 $dbw->immediateCommit();
1537 } catch( MWException $e ) {
1538 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1539 $transaction->rollback();
1540 FileStore::unlock();
1541 throw $e;
1544 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1545 $transaction->commit();
1546 FileStore::unlock();
1548 $this->purgeDescription();
1550 // Squid purging
1551 global $wgUseSquid;
1552 if ( $wgUseSquid ) {
1553 $urlArr = array(
1554 wfImageArchiveUrl( $archiveName ),
1556 wfPurgeSquidServers( $urlArr );
1558 return true;
1562 * Delete the current version of a file.
1563 * May throw a database error.
1564 * @return true on success, false on failure
1566 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1567 return $this->prepareDeleteVersion(
1568 $this->getFullPath(),
1569 $reason,
1570 'image',
1571 array(
1572 'fa_name' => 'img_name',
1573 'fa_archive_name' => 'NULL',
1574 'fa_size' => 'img_size',
1575 'fa_width' => 'img_width',
1576 'fa_height' => 'img_height',
1577 'fa_metadata' => 'img_metadata',
1578 'fa_bits' => 'img_bits',
1579 'fa_media_type' => 'img_media_type',
1580 'fa_major_mime' => 'img_major_mime',
1581 'fa_minor_mime' => 'img_minor_mime',
1582 'fa_description' => 'img_description',
1583 'fa_user' => 'img_user',
1584 'fa_user_text' => 'img_user_text',
1585 'fa_timestamp' => 'img_timestamp' ),
1586 array( 'img_name' => $this->name ),
1587 $suppress,
1588 __METHOD__ );
1592 * Delete a given older version of a file.
1593 * May throw a database error.
1594 * @return true on success, false on failure
1596 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1597 $oldpath = wfImageArchiveDir( $this->name ) .
1598 DIRECTORY_SEPARATOR . $archiveName;
1599 return $this->prepareDeleteVersion(
1600 $oldpath,
1601 $reason,
1602 'oldimage',
1603 array(
1604 'fa_name' => 'oi_name',
1605 'fa_archive_name' => 'oi_archive_name',
1606 'fa_size' => 'oi_size',
1607 'fa_width' => 'oi_width',
1608 'fa_height' => 'oi_height',
1609 'fa_metadata' => 'NULL',
1610 'fa_bits' => 'oi_bits',
1611 'fa_media_type' => 'NULL',
1612 'fa_major_mime' => 'NULL',
1613 'fa_minor_mime' => 'NULL',
1614 'fa_description' => 'oi_description',
1615 'fa_user' => 'oi_user',
1616 'fa_user_text' => 'oi_user_text',
1617 'fa_timestamp' => 'oi_timestamp' ),
1618 array(
1619 'oi_name' => $this->name,
1620 'oi_archive_name' => $archiveName ),
1621 $suppress,
1622 __METHOD__ );
1626 * Do the dirty work of backing up an image row and its file
1627 * (if $wgSaveDeletedFiles is on) and removing the originals.
1629 * Must be run while the file store is locked and a database
1630 * transaction is open to avoid race conditions.
1632 * @return FSTransaction
1634 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1635 global $wgUser, $wgSaveDeletedFiles;
1637 // Dupe the file into the file store
1638 if( file_exists( $path ) ) {
1639 if( $wgSaveDeletedFiles ) {
1640 $group = 'deleted';
1642 $store = FileStore::get( $group );
1643 $key = FileStore::calculateKey( $path, $this->extension );
1644 $transaction = $store->insert( $key, $path,
1645 FileStore::DELETE_ORIGINAL );
1646 } else {
1647 $group = null;
1648 $key = null;
1649 $transaction = FileStore::deleteFile( $path );
1651 } else {
1652 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
1653 $group = null;
1654 $key = null;
1655 $transaction = new FSTransaction(); // empty
1658 if( $transaction === false ) {
1659 // Fail to restore?
1660 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
1661 throw new MWException( "Could not archive and delete file $path" );
1662 return false;
1665 // Bitfields to further supress the image content
1666 // Note that currently, live images are stored elsewhere
1667 // and cannot be partially deleted
1668 $bitfield = 0;
1669 if ( $suppress ) {
1670 $bitfield |= self::DELETED_FILE;
1671 $bitfield |= self::DELETED_COMMENT;
1672 $bitfield |= self::DELETED_USER;
1673 $bitfield |= self::DELETED_RESTRICTED;
1676 $dbw = wfGetDB( DB_MASTER );
1677 $storageMap = array(
1678 'fa_storage_group' => $dbw->addQuotes( $group ),
1679 'fa_storage_key' => $dbw->addQuotes( $key ),
1681 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1682 'fa_deleted_timestamp' => $dbw->timestamp(),
1683 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1684 'fa_deleted' => $bitfield);
1685 $allFields = array_merge( $storageMap, $fieldMap );
1687 try {
1688 if( $wgSaveDeletedFiles ) {
1689 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1691 $dbw->delete( $table, $where, $fname );
1692 } catch( DBQueryError $e ) {
1693 // Something went horribly wrong!
1694 // Leave the file as it was...
1695 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
1696 $transaction->rollback();
1697 throw $e;
1700 return $transaction;
1704 * Restore all or specified deleted revisions to the given file.
1705 * Permissions and logging are left to the caller.
1707 * May throw database exceptions on error.
1709 * @param $versions set of record ids of deleted items to restore,
1710 * or empty to restore all revisions.
1711 * @return the number of file revisions restored if successful,
1712 * or false on failure
1714 function restore( $versions=array(), $Unsuppress=false ) {
1715 global $wgUser;
1717 if( !FileStore::lock() ) {
1718 wfDebug( __METHOD__." could not acquire filestore lock\n" );
1719 return false;
1722 $transaction = new FSTransaction();
1723 try {
1724 $dbw = wfGetDB( DB_MASTER );
1725 $dbw->begin();
1727 // Re-confirm whether this image presently exists;
1728 // if no we'll need to create an image record for the
1729 // first item we restore.
1730 $exists = $dbw->selectField( 'image', '1',
1731 array( 'img_name' => $this->name ),
1732 __METHOD__ );
1734 // Fetch all or selected archived revisions for the file,
1735 // sorted from the most recent to the oldest.
1736 $conditions = array( 'fa_name' => $this->name );
1737 if( $versions ) {
1738 $conditions['fa_id'] = $versions;
1741 $result = $dbw->select( 'filearchive', '*',
1742 $conditions,
1743 __METHOD__,
1744 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1746 if( $dbw->numRows( $result ) < count( $versions ) ) {
1747 // There's some kind of conflict or confusion;
1748 // we can't restore everything we were asked to.
1749 wfDebug( __METHOD__.": couldn't find requested items\n" );
1750 $dbw->rollback();
1751 FileStore::unlock();
1752 return false;
1755 if( $dbw->numRows( $result ) == 0 ) {
1756 // Nothing to do.
1757 wfDebug( __METHOD__.": nothing to do\n" );
1758 $dbw->rollback();
1759 FileStore::unlock();
1760 return true;
1763 $revisions = 0;
1764 while( $row = $dbw->fetchObject( $result ) ) {
1765 if ( $Unsuppress ) {
1766 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1767 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
1768 // Skip restoring file revisions that the user cannot restore
1769 continue;
1771 $revisions++;
1772 $store = FileStore::get( $row->fa_storage_group );
1773 if( !$store ) {
1774 wfDebug( __METHOD__.": skipping row with no file.\n" );
1775 continue;
1778 if( $revisions == 1 && !$exists ) {
1779 $destDir = wfImageDir( $row->fa_name );
1780 if ( !is_dir( $destDir ) ) {
1781 wfMkdirParents( $destDir );
1783 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
1785 // We may have to fill in data if this was originally
1786 // an archived file revision.
1787 if( is_null( $row->fa_metadata ) ) {
1788 $tempFile = $store->filePath( $row->fa_storage_key );
1790 $magic = MimeMagic::singleton();
1791 $mime = $magic->guessMimeType( $tempFile, true );
1792 $media_type = $magic->getMediaType( $tempFile, $mime );
1793 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
1794 $handler = MediaHandler::getHandler( $mime );
1795 if ( $handler ) {
1796 $metadata = $handler->getMetadata( $image, $tempFile );
1797 } else {
1798 $metadata = '';
1800 } else {
1801 $metadata = $row->fa_metadata;
1802 $major_mime = $row->fa_major_mime;
1803 $minor_mime = $row->fa_minor_mime;
1804 $media_type = $row->fa_media_type;
1807 $table = 'image';
1808 $fields = array(
1809 'img_name' => $row->fa_name,
1810 'img_size' => $row->fa_size,
1811 'img_width' => $row->fa_width,
1812 'img_height' => $row->fa_height,
1813 'img_metadata' => $metadata,
1814 'img_bits' => $row->fa_bits,
1815 'img_media_type' => $media_type,
1816 'img_major_mime' => $major_mime,
1817 'img_minor_mime' => $minor_mime,
1818 'img_description' => $row->fa_description,
1819 'img_user' => $row->fa_user,
1820 'img_user_text' => $row->fa_user_text,
1821 'img_timestamp' => $row->fa_timestamp );
1822 } else {
1823 $archiveName = $row->fa_archive_name;
1824 if( $archiveName == '' ) {
1825 // This was originally a current version; we
1826 // have to devise a new archive name for it.
1827 // Format is <timestamp of archiving>!<name>
1828 $archiveName =
1829 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
1830 '!' . $row->fa_name;
1832 $destDir = wfImageArchiveDir( $row->fa_name );
1833 if ( !is_dir( $destDir ) ) {
1834 wfMkdirParents( $destDir );
1836 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
1838 $table = 'oldimage';
1839 $fields = array(
1840 'oi_name' => $row->fa_name,
1841 'oi_archive_name' => $archiveName,
1842 'oi_size' => $row->fa_size,
1843 'oi_width' => $row->fa_width,
1844 'oi_height' => $row->fa_height,
1845 'oi_bits' => $row->fa_bits,
1846 'oi_description' => $row->fa_description,
1847 'oi_user' => $row->fa_user,
1848 'oi_user_text' => $row->fa_user_text,
1849 'oi_timestamp' => $row->fa_timestamp );
1852 $dbw->insert( $table, $fields, __METHOD__ );
1853 // @todo this delete is not totally safe, potentially
1854 $dbw->delete( 'filearchive',
1855 array( 'fa_id' => $row->fa_id ),
1856 __METHOD__ );
1858 // Check if any other stored revisions use this file;
1859 // if so, we shouldn't remove the file from the deletion
1860 // archives so they will still work.
1861 $useCount = $dbw->selectField( 'filearchive',
1862 'COUNT(*)',
1863 array(
1864 'fa_storage_group' => $row->fa_storage_group,
1865 'fa_storage_key' => $row->fa_storage_key ),
1866 __METHOD__ );
1867 if( $useCount == 0 ) {
1868 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1869 $flags = FileStore::DELETE_ORIGINAL;
1870 } else {
1871 $flags = 0;
1874 $transaction->add( $store->export( $row->fa_storage_key,
1875 $destPath, $flags ) );
1878 $dbw->immediateCommit();
1879 } catch( MWException $e ) {
1880 wfDebug( __METHOD__." caught error, aborting\n" );
1881 $transaction->rollback();
1882 throw $e;
1885 $transaction->commit();
1886 FileStore::unlock();
1888 if( $revisions > 0 ) {
1889 if( !$exists ) {
1890 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
1892 // Update site_stats
1893 $site_stats = $dbw->tableName( 'site_stats' );
1894 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1896 $this->purgeEverything();
1897 } else {
1898 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
1899 $this->purgeDescription();
1903 return $revisions;
1907 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1908 * document.
1910 * @return Bool
1912 function isMultipage() {
1913 $handler = $this->getHandler();
1914 return $handler && $handler->isMultiPage();
1918 * Returns the number of pages of a multipage document, or NULL for
1919 * documents which aren't multipage documents
1921 function pageCount() {
1922 $handler = $this->getHandler();
1923 if ( $handler && $handler->isMultiPage() ) {
1924 return $handler->pageCount( $this );
1925 } else {
1926 return null;
1930 static function getCommonsDB() {
1931 static $dbc;
1932 global $wgLoadBalancer, $wgSharedUploadDBname;
1933 if ( !isset( $dbc ) ) {
1934 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1935 $dbinfo = $wgLoadBalancer->mServers[$i];
1936 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1937 $dbinfo['password'], $wgSharedUploadDBname );
1939 return $dbc;
1943 * Calculate the height of a thumbnail using the source and destination width
1945 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1946 // Exact integer multiply followed by division
1947 if ( $srcWidth == 0 ) {
1948 return 0;
1949 } else {
1950 return round( $srcHeight * $dstWidth / $srcWidth );
1955 * Get an image size array like that returned by getimagesize(), or false if it
1956 * can't be determined.
1958 * @param string $fileName The filename
1959 * @return array
1961 function getImageSize( $fileName ) {
1962 $handler = $this->getHandler();
1963 return $handler->getImageSize( $this, $fileName );
1967 * Get the thumbnail extension and MIME type for a given source MIME type
1968 * @return array thumbnail extension and MIME type
1970 static function getThumbType( $ext, $mime ) {
1971 $handler = MediaHandler::getHandler( $mime );
1972 if ( $handler ) {
1973 return $handler->getThumbType( $ext, $mime );
1974 } else {
1975 return array( $ext, $mime );
1979 } //class
1983 * @addtogroup Media
1985 class ArchivedFile
1988 * Returns a file object from the filearchive table
1989 * In the future, all current and old image storage
1990 * may use FileStore. There will be a "old" storage
1991 * for current and previous file revisions as well as
1992 * the "deleted" group for archived revisions
1993 * @param $title, the corresponding image page title
1994 * @param $id, the image id, a unique key
1995 * @param $key, optional storage key
1996 * @return ResultWrapper
1998 function ArchivedFile( $title, $id=0, $key='' ) {
1999 if( !is_object( $title ) ) {
2000 throw new MWException( 'Image constructor given bogus title.' );
2002 $conds = ($id) ? "fa_id = $id" : "fa_storage_key = '$key'";
2003 if( $title->getNamespace() == NS_IMAGE ) {
2004 $dbr = wfGetDB( DB_SLAVE );
2005 $res = $dbr->select( 'filearchive',
2006 array(
2007 'fa_id',
2008 'fa_name',
2009 'fa_storage_key',
2010 'fa_storage_group',
2011 'fa_size',
2012 'fa_bits',
2013 'fa_width',
2014 'fa_height',
2015 'fa_metadata',
2016 'fa_media_type',
2017 'fa_major_mime',
2018 'fa_minor_mime',
2019 'fa_description',
2020 'fa_user',
2021 'fa_user_text',
2022 'fa_timestamp',
2023 'fa_deleted' ),
2024 array(
2025 'fa_name' => $title->getDbKey(),
2026 $conds ),
2027 __METHOD__,
2028 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2030 if ( $dbr->numRows( $res ) == 0 ) {
2031 // this revision does not exist?
2032 return;
2034 $ret = $dbr->resultObject( $res );
2035 $row = $ret->fetchObject();
2037 // initialize fields for filestore image object
2038 $this->mId = intval($row->fa_id);
2039 $this->mName = $row->fa_name;
2040 $this->mGroup = $row->fa_storage_group;
2041 $this->mKey = $row->fa_storage_key;
2042 $this->mSize = $row->fa_size;
2043 $this->mBits = $row->fa_bits;
2044 $this->mWidth = $row->fa_width;
2045 $this->mHeight = $row->fa_height;
2046 $this->mMetaData = $row->fa_metadata;
2047 $this->mMime = "$row->fa_major_mime/$row->fa_minor_mime";
2048 $this->mType = $row->fa_media_type;
2049 $this->mDescription = $row->fa_description;
2050 $this->mUser = $row->fa_user;
2051 $this->mUserText = $row->fa_user_text;
2052 $this->mTimestamp = $row->fa_timestamp;
2053 $this->mDeleted = $row->fa_deleted;
2054 } else {
2055 throw new MWException( 'This title does not correspond to an image page.' );
2056 return;
2058 return true;
2062 * int $field one of DELETED_* bitfield constants
2063 * for file or revision rows
2064 * @return bool
2066 function isDeleted( $field ) {
2067 return ($this->mDeleted & $field) == $field;
2071 * Determine if the current user is allowed to view a particular
2072 * field of this FileStore image file, if it's marked as deleted.
2073 * @param int $field
2074 * @return bool
2076 function userCan( $field ) {
2077 if( isset($this->mDeleted) && ($this->mDeleted & $field) == $field ) {
2078 // images
2079 global $wgUser;
2080 $permission = ( $this->mDeleted & Revision::DELETED_RESTRICTED ) == Revision::DELETED_RESTRICTED
2081 ? 'hiderevision'
2082 : 'deleterevision';
2083 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2084 return $wgUser->isAllowed( $permission );
2085 } else {
2086 return true;
2092 * Aliases for backwards compatibility with 1.6
2094 define( 'MW_IMG_DELETED_FILE', Image::DELETED_FILE );
2095 define( 'MW_IMG_DELETED_COMMENT', Image::DELETED_COMMENT );
2096 define( 'MW_IMG_DELETED_USER', Image::DELETED_USER );
2097 define( 'MW_IMG_DELETED_RESTRICTED', Image::DELETED_RESTRICTED );