7 * NOTE FOR WINDOWS USERS:
8 * To enable EXIF functions, add the folloing lines to the
9 * "Windows extensions" section of php.ini:
11 * extension=extensions/php_mbstring.dll
12 * extension=extensions/php_exif.dll
16 * Bump this number when serialized cache records may be incompatible.
18 define( 'MW_IMAGE_VERSION', 1 );
21 * Class to represent an image
23 * Provides methods to retrieve paths (physical, logical, URL),
24 * to generate thumbnails or for uploading.
32 var $name, # name of the image (constructor)
33 $imagePath, # Path of the image (loadFromXxx)
34 $url, # Image URL (accessor)
35 $title, # Title object for this image (constructor)
36 $fileExists, # does the image file exist on disk? (loadFromXxx)
37 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
38 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
39 $historyRes, # result of the query for the image's history (nextHistoryLine)
42 $bits, # --- returned by getimagesize (loadFromXxx)
44 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
45 $mime, # MIME type, determined by MimeMagic::guessMimeType
46 $size, # Size in bytes (loadFromXxx)
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $lastError; # Error string associated with a thumbnail display error
55 * Create an Image object from an image name
57 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
60 function newFromName( $name ) {
61 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
62 if ( is_object( $title ) ) {
63 return new Image( $title );
70 * Obsolete factory function, use constructor
73 function newFromTitle( $title ) {
74 return new Image( $title );
77 function Image( $title ) {
78 if( !is_object( $title ) ) {
79 throw new MWException( 'Image constructor given bogus title.' );
81 $this->title
=& $title;
82 $this->name
= $title->getDBkey();
83 $this->metadata
= serialize ( array() ) ;
85 $n = strrpos( $this->name
, '.' );
86 $this->extension
= Image
::normalizeExtension( $n ?
87 substr( $this->name
, $n +
1 ) : '' );
88 $this->historyLine
= 0;
90 $this->dataLoaded
= false;
95 * Normalize a file extension to the common form, and ensure it's clean.
96 * Extensions with non-alphanumeric characters will be discarded.
98 * @param $ext string (without the .)
101 static function normalizeExtension( $ext ) {
102 $lower = strtolower( $ext );
108 if( isset( $squish[$lower] ) ) {
109 return $squish[$lower];
110 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
118 * Get the memcached keys
119 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
121 function getCacheKeys( ) {
122 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
124 $hashedName = md5($this->name
);
125 $keys = array( "$wgDBname:Image:$hashedName" );
126 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
127 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
133 * Try to load image metadata from memcached. Returns true on success.
135 function loadFromCache() {
136 global $wgUseSharedUploads, $wgMemc;
137 wfProfileIn( __METHOD__
);
138 $this->dataLoaded
= false;
139 $keys = $this->getCacheKeys();
140 $cachedValues = $wgMemc->get( $keys[0] );
142 // Check if the key existed and belongs to this version of MediaWiki
143 if (!empty($cachedValues) && is_array($cachedValues)
144 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
145 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
147 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
148 # if this is shared file, we need to check if image
149 # in shared repository has not changed
150 if ( isset( $keys[1] ) ) {
151 $commonsCachedValues = $wgMemc->get( $keys[1] );
152 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
153 && isset($commonsCachedValues['version'])
154 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
155 && isset($commonsCachedValues['mime'])) {
156 wfDebug( "Pulling image metadata from shared repository cache\n" );
157 $this->name
= $commonsCachedValues['name'];
158 $this->imagePath
= $commonsCachedValues['imagePath'];
159 $this->fileExists
= $commonsCachedValues['fileExists'];
160 $this->width
= $commonsCachedValues['width'];
161 $this->height
= $commonsCachedValues['height'];
162 $this->bits
= $commonsCachedValues['bits'];
163 $this->type
= $commonsCachedValues['type'];
164 $this->mime
= $commonsCachedValues['mime'];
165 $this->metadata
= $commonsCachedValues['metadata'];
166 $this->size
= $commonsCachedValues['size'];
167 $this->fromSharedDirectory
= true;
168 $this->dataLoaded
= true;
169 $this->imagePath
= $this->getFullPath(true);
173 wfDebug( "Pulling image metadata from local cache\n" );
174 $this->name
= $cachedValues['name'];
175 $this->imagePath
= $cachedValues['imagePath'];
176 $this->fileExists
= $cachedValues['fileExists'];
177 $this->width
= $cachedValues['width'];
178 $this->height
= $cachedValues['height'];
179 $this->bits
= $cachedValues['bits'];
180 $this->type
= $cachedValues['type'];
181 $this->mime
= $cachedValues['mime'];
182 $this->metadata
= $cachedValues['metadata'];
183 $this->size
= $cachedValues['size'];
184 $this->fromSharedDirectory
= false;
185 $this->dataLoaded
= true;
186 $this->imagePath
= $this->getFullPath();
189 if ( $this->dataLoaded
) {
190 wfIncrStats( 'image_cache_hit' );
192 wfIncrStats( 'image_cache_miss' );
195 wfProfileOut( __METHOD__
);
196 return $this->dataLoaded
;
200 * Save the image metadata to memcached
202 function saveToCache() {
205 $keys = $this->getCacheKeys();
206 if ( $this->fileExists
) {
207 // We can't cache negative metadata for non-existent files,
208 // because if the file later appears in commons, the local
209 // keys won't be purged.
210 $cachedValues = array(
211 'version' => MW_IMAGE_VERSION
,
212 'name' => $this->name
,
213 'imagePath' => $this->imagePath
,
214 'fileExists' => $this->fileExists
,
215 'fromShared' => $this->fromSharedDirectory
,
216 'width' => $this->width
,
217 'height' => $this->height
,
218 'bits' => $this->bits
,
219 'type' => $this->type
,
220 'mime' => $this->mime
,
221 'metadata' => $this->metadata
,
222 'size' => $this->size
);
224 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
226 // However we should clear them, so they aren't leftover
227 // if we've deleted the file.
228 $wgMemc->delete( $keys[0] );
233 * Load metadata from the file itself
235 function loadFromFile() {
236 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
237 wfProfileIn( __METHOD__
);
238 $this->imagePath
= $this->getFullPath();
239 $this->fileExists
= file_exists( $this->imagePath
);
240 $this->fromSharedDirectory
= false;
243 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
245 # If the file is not found, and a shared upload directory is used, look for it there.
246 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
247 # In case we're on a wgCapitalLinks=false wiki, we
248 # capitalize the first letter of the filename before
249 # looking it up in the shared repository.
250 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
251 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
252 if ( $this->fileExists
) {
253 $this->name
= $sharedImage->name
;
254 $this->imagePath
= $this->getFullPath(true);
255 $this->fromSharedDirectory
= true;
260 if ( $this->fileExists
) {
261 $magic=& wfGetMimeMagic();
263 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
264 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
267 $this->size
= filesize( $this->imagePath
);
269 $magic=& wfGetMimeMagic();
272 wfSuppressWarnings();
273 if( $this->mime
== 'image/svg' ) {
274 $gis = wfGetSVGsize( $this->imagePath
);
275 } elseif( $this->mime
== 'image/vnd.djvu' ) {
276 $deja = new DjVuImage( $this->imagePath
);
277 $gis = $deja->getImageSize();
278 } elseif ( !$magic->isPHPImageType( $this->mime
) ) {
279 # Don't try to get the width and height of sound and video files, that's bad for performance
282 $gis = getimagesize( $this->imagePath
);
286 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
290 $this->type
= MEDIATYPE_UNKNOWN
;
291 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
295 $this->width
= $gis[0];
296 $this->height
= $gis[1];
302 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
304 #NOTE: we have to set this flag early to avoid load() to be called
305 # be some of the functions below. This may lead to recursion or other bad things!
306 # as ther's only one thread of execution, this should be safe anyway.
307 $this->dataLoaded
= true;
310 $this->metadata
= serialize( $this->retrieveExifData( $this->imagePath
) );
312 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
313 else $this->bits
= 0;
315 wfProfileOut( __METHOD__
);
319 * Load image metadata from the DB
321 function loadFromDB() {
322 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
323 wfProfileIn( __METHOD__
);
325 $dbr =& wfGetDB( DB_SLAVE
);
327 $this->checkDBSchema($dbr);
329 $row = $dbr->selectRow( 'image',
330 array( 'img_size', 'img_width', 'img_height', 'img_bits',
331 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
332 array( 'img_name' => $this->name
), __METHOD__
);
334 $this->fromSharedDirectory
= false;
335 $this->fileExists
= true;
336 $this->loadFromRow( $row );
337 $this->imagePath
= $this->getFullPath();
338 // Check for rows from a previous schema, quietly upgrade them
339 if ( is_null($this->type
) ) {
342 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
343 # In case we're on a wgCapitalLinks=false wiki, we
344 # capitalize the first letter of the filename before
345 # looking it up in the shared repository.
346 $name = $wgContLang->ucfirst($this->name
);
347 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
349 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
351 'img_size', 'img_width', 'img_height', 'img_bits',
352 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
353 array( 'img_name' => $name ), __METHOD__
);
355 $this->fromSharedDirectory
= true;
356 $this->fileExists
= true;
357 $this->imagePath
= $this->getFullPath(true);
359 $this->loadFromRow( $row );
361 // Check for rows from a previous schema, quietly upgrade them
362 if ( is_null($this->type
) ) {
374 $this->fileExists
= false;
375 $this->fromSharedDirectory
= false;
376 $this->metadata
= serialize ( array() ) ;
379 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
380 $this->dataLoaded
= true;
381 wfProfileOut( __METHOD__
);
385 * Load image metadata from a DB result row
387 function loadFromRow( &$row ) {
388 $this->size
= $row->img_size
;
389 $this->width
= $row->img_width
;
390 $this->height
= $row->img_height
;
391 $this->bits
= $row->img_bits
;
392 $this->type
= $row->img_media_type
;
394 $major= $row->img_major_mime
;
395 $minor= $row->img_minor_mime
;
397 if (!$major) $this->mime
= "unknown/unknown";
399 if (!$minor) $minor= "unknown";
400 $this->mime
= $major.'/'.$minor;
403 $this->metadata
= $row->img_metadata
;
404 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
406 $this->dataLoaded
= true;
410 * Load image metadata from cache or DB, unless already loaded
413 global $wgSharedUploadDBname, $wgUseSharedUploads;
414 if ( !$this->dataLoaded
) {
415 if ( !$this->loadFromCache() ) {
417 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
418 $this->loadFromFile();
419 } elseif ( $this->fileExists
) {
420 $this->saveToCache();
423 $this->dataLoaded
= true;
428 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
429 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
431 function upgradeRow() {
432 global $wgDBname, $wgSharedUploadDBname;
433 wfProfileIn( __METHOD__
);
435 $this->loadFromFile();
437 if ( $this->fromSharedDirectory
) {
438 if ( !$wgSharedUploadDBname ) {
439 wfProfileOut( __METHOD__
);
443 // Write to the other DB using selectDB, not database selectors
444 // This avoids breaking replication in MySQL
445 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
446 $dbw->selectDB( $wgSharedUploadDBname );
448 $dbw =& wfGetDB( DB_MASTER
);
451 $this->checkDBSchema($dbw);
453 list( $major, $minor ) = self
::splitMime( $this->mime
);
455 wfDebug(__METHOD__
.': upgrading '.$this->name
." to 1.5 schema\n");
457 $dbw->update( 'image',
459 'img_width' => $this->width
,
460 'img_height' => $this->height
,
461 'img_bits' => $this->bits
,
462 'img_media_type' => $this->type
,
463 'img_major_mime' => $major,
464 'img_minor_mime' => $minor,
465 'img_metadata' => $this->metadata
,
466 ), array( 'img_name' => $this->name
), __METHOD__
468 if ( $this->fromSharedDirectory
) {
469 $dbw->selectDB( $wgDBname );
471 wfProfileOut( __METHOD__
);
475 * Split an internet media type into its two components; if not
476 * a two-part name, set the minor type to 'unknown'.
478 * @param $mime "text/html" etc
479 * @return array ("text", "html") etc
481 static function splitMime( $mime ) {
482 if( strpos( $mime, '/' ) !== false ) {
483 return explode( '/', $mime, 2 );
485 return array( $mime, 'unknown' );
490 * Return the name of this image
498 * Return the associated title object
501 function getTitle() {
506 * Return the URL of the image file
512 if($this->fileExists
) {
513 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
521 function getViewURL() {
522 if( $this->mustRender()) {
523 if( $this->canRender() ) {
524 return $this->createThumb( $this->getWidth() );
527 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
528 return $this->getURL(); #hm... return NULL?
531 return $this->getURL();
536 * Return the image path of the image in the
537 * local file system as an absolute path
540 function getImagePath() {
542 return $this->imagePath
;
546 * Return the width of the image
548 * Returns -1 if the file specified is not a known image type
551 function getWidth() {
557 * Return the height of the image
559 * Returns -1 if the file specified is not a known image type
562 function getHeight() {
564 return $this->height
;
568 * Return the size of the image file, in bytes
577 * Returns the mime type of the file.
579 function getMimeType() {
585 * Return the type of the media in the file.
586 * Use the value returned by this function with the MEDIATYPE_xxx constants.
588 function getMediaType() {
594 * Checks if the file can be presented to the browser as a bitmap.
596 * Currently, this checks if the file is an image format
597 * that can be converted to a format
598 * supported by all browsers (namely GIF, PNG and JPEG),
599 * or if it is an SVG image and SVG conversion is enabled.
601 * @todo remember the result of this check.
603 function canRender() {
604 global $wgUseImageMagick;
606 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
608 $mime= $this->getMimeType();
610 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
612 #if it's SVG, check if there's a converter enabled
613 if ($mime === 'image/svg') {
614 global $wgSVGConverters, $wgSVGConverter;
616 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
617 wfDebug( "Image::canRender: SVG is ready!\n" );
620 wfDebug( "Image::canRender: SVG renderer missing\n" );
624 #image formats available on ALL browsers
625 if ( $mime === 'image/gif'
626 ||
$mime === 'image/png'
627 ||
$mime === 'image/jpeg' ) return true;
629 #image formats that can be converted to the above formats
630 if ($wgUseImageMagick) {
631 #convertable by ImageMagick (there are more...)
632 if ( $mime === 'image/vnd.wap.wbmp'
633 ||
$mime === 'image/x-xbitmap'
634 ||
$mime === 'image/x-xpixmap'
635 #|| $mime === 'image/x-icon' #file may be split into multiple parts
636 ||
$mime === 'image/x-portable-anymap'
637 ||
$mime === 'image/x-portable-bitmap'
638 ||
$mime === 'image/x-portable-graymap'
639 ||
$mime === 'image/x-portable-pixmap'
640 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
641 ||
$mime === 'image/x-rgb'
642 ||
$mime === 'image/x-bmp'
643 ||
$mime === 'image/tiff' ) return true;
646 #convertable by the PHP GD image lib
647 if ( $mime === 'image/vnd.wap.wbmp'
648 ||
$mime === 'image/x-xbitmap' ) return true;
656 * Return true if the file is of a type that can't be directly
657 * rendered by typical browsers and needs to be re-rasterized.
659 * This returns true for everything but the bitmap types
660 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
661 * also return true for any non-image formats.
665 function mustRender() {
666 $mime= $this->getMimeType();
668 if ( $mime === "image/gif"
669 ||
$mime === "image/png"
670 ||
$mime === "image/jpeg" ) return false;
676 * Determines if this media file may be shown inline on a page.
678 * This is currently synonymous to canRender(), but this could be
679 * extended to also allow inline display of other media,
680 * like flash animations or videos. If you do so, please keep in mind that
681 * that could be a security risk.
683 function allowInlineDisplay() {
684 return $this->canRender();
688 * Determines if this media file is in a format that is unlikely to
689 * contain viruses or malicious content. It uses the global
690 * $wgTrustedMediaFormats list to determine if the file is safe.
692 * This is used to show a warning on the description page of non-safe files.
693 * It may also be used to disallow direct [[media:...]] links to such files.
695 * Note that this function will always return true if allowInlineDisplay()
696 * or isTrustedFile() is true for this file.
698 function isSafeFile() {
699 if ($this->allowInlineDisplay()) return true;
700 if ($this->isTrustedFile()) return true;
702 global $wgTrustedMediaFormats;
704 $type= $this->getMediaType();
705 $mime= $this->getMimeType();
706 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
708 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
709 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
711 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
712 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
717 /** Returns true if the file is flagged as trusted. Files flagged that way
718 * can be linked to directly, even if that is not allowed for this type of
721 * This is a dummy function right now and always returns false. It could be
722 * implemented to extract a flag from the database. The trusted flag could be
723 * set on upload, if the user has sufficient privileges, to bypass script-
724 * and html-filters. It may even be coupled with cryptographics signatures
727 function isTrustedFile() {
728 #this could be implemented to check a flag in the databas,
729 #look for signatures, etc
734 * Return the escapeLocalURL of this image
737 function getEscapeLocalURL() {
739 return $this->title
->escapeLocalURL();
743 * Return the escapeFullURL of this image
746 function getEscapeFullURL() {
748 return $this->title
->escapeFullURL();
752 * Return the URL of an image, provided its name.
754 * @param string $name Name of the image, without the leading "Image:"
755 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
756 * @return string URL of $name image
760 function imageUrl( $name, $fromSharedDirectory = false ) {
761 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
762 if($fromSharedDirectory) {
764 $path = $wgSharedUploadPath;
766 $base = $wgUploadBaseUrl;
767 $path = $wgUploadPath;
769 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
770 return wfUrlencode( $url );
774 * Returns true if the image file exists on disk.
775 * @return boolean Whether image file exist on disk.
780 return $this->fileExists
;
787 function thumbUrl( $width, $subdir='thumb') {
788 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
789 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
791 // Generate thumb.php URL if possible
795 if ( $this->fromSharedDirectory
) {
796 if ( $wgSharedThumbnailScriptPath ) {
797 $script = $wgSharedThumbnailScriptPath;
800 if ( $wgThumbnailScriptPath ) {
801 $script = $wgThumbnailScriptPath;
805 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
806 if( $this->mustRender() ) {
810 $name = $this->thumbName( $width );
811 if($this->fromSharedDirectory
) {
813 $path = $wgSharedUploadPath;
815 $base = $wgUploadBaseUrl;
816 $path = $wgUploadPath;
818 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
819 $url = "{$base}{$path}/{$subdir}" .
820 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
821 . $this->name
.'/'.$name;
822 $url = wfUrlencode( $url );
824 $url = "{$base}{$path}/{$subdir}/{$name}";
827 return array( $script !== false, $url );
831 * Return the file name of a thumbnail of the specified width
833 * @param integer $width Width of the thumbnail image
834 * @param boolean $shared Does the thumbnail come from the shared repository?
837 function thumbName( $width ) {
838 $thumb = $width."px-".$this->name
;
840 if( $this->mustRender() ) {
841 if( $this->canRender() ) {
842 # Rasterize to PNG (for SVG vector images, etc)
846 #should we use iconThumb here to get a symbolic thumbnail?
847 #or should we fail with an internal error?
848 return NULL; //can't make bitmap
855 * Create a thumbnail of the image having the specified width/height.
856 * The thumbnail will not be created if the width is larger than the
857 * image's width. Let the browser do the scaling in this case.
858 * The thumbnail is stored on disk and is only computed if the thumbnail
859 * file does not exist OR if it is older than the image.
862 * Keeps aspect ratio of original image. If both width and height are
863 * specified, the generated image will be no bigger than width x height,
864 * and will also have correct aspect ratio.
866 * @param integer $width maximum width of the generated thumbnail
867 * @param integer $height maximum height of the image (optional)
870 function createThumb( $width, $height=-1 ) {
871 $thumb = $this->getThumbnail( $width, $height );
872 if( is_null( $thumb ) ) return '';
873 return $thumb->getUrl();
877 * As createThumb, but returns a ThumbnailImage object. This can
878 * provide access to the actual file, the real size of the thumb,
879 * and can produce a convenient <img> tag for you.
881 * For non-image formats, this may return a filetype-specific icon.
883 * @param integer $width maximum width of the generated thumbnail
884 * @param integer $height maximum height of the image (optional)
885 * @return ThumbnailImage or null on failure
888 function getThumbnail( $width, $height=-1 ) {
889 if ($this->canRender()) {
892 if ( $width > $this->width
* $height / $this->height
) {
893 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
896 return $this->renderThumb( $width );
898 // not a bitmap or renderable image, don't try.
899 return $this->iconThumb();
904 * @return ThumbnailImage
906 function iconThumb() {
907 global $wgStylePath, $wgStyleDirectory;
909 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
910 foreach( $try as $icon ) {
911 $path = '/common/images/icons/' . $icon;
912 $filepath = $wgStyleDirectory . $path;
913 if( file_exists( $filepath ) ) {
914 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
921 * Create a thumbnail of the image having the specified width.
922 * The thumbnail will not be created if the width is larger than the
923 * image's width. Let the browser do the scaling in this case.
924 * The thumbnail is stored on disk and is only computed if the thumbnail
925 * file does not exist OR if it is older than the image.
926 * Returns an object which can return the pathname, URL, and physical
927 * pixel size of the thumbnail -- or null on failure.
929 * @return ThumbnailImage or null on failure
932 function renderThumb( $width, $useScript = true ) {
934 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
936 wfProfileIn( __METHOD__
);
938 $width = intval( $width );
941 if ( ! $this->exists() )
943 # If there is no image, there will be no thumbnail
944 wfProfileOut( __METHOD__
);
948 # Sanity check $width
949 if( $width <= 0 ||
$this->width
<= 0) {
951 wfProfileOut( __METHOD__
);
955 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
956 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
957 # an exception for it.
958 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
959 $this->getMimeType() !== 'image/jpeg' &&
960 $this->width
* $this->height
> $wgMaxImageArea )
962 wfProfileOut( __METHOD__
);
966 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
967 if ( $this->mustRender() ) {
968 $width = min( $width, $wgSVGMaxSize );
969 } elseif ( $width > $this->width
- 1 ) {
970 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
971 wfProfileOut( __METHOD__
);
975 $height = round( $this->height
* $width / $this->width
);
977 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
978 if ( $isScriptUrl && $useScript ) {
979 // Use thumb.php to render the image
980 $thumb = new ThumbnailImage( $url, $width, $height );
981 wfProfileOut( __METHOD__
);
985 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
986 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
987 $thumbPath = $thumbDir.'/'.$thumbName;
989 if ( is_dir( $thumbPath ) ) {
990 // Directory where file should be
991 // This happened occasionally due to broken migration code in 1.5
992 // Rename to broken-*
993 global $wgUploadDirectory;
994 for ( $i = 0; $i < 100 ; $i++
) {
995 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
996 if ( !file_exists( $broken ) ) {
997 rename( $thumbPath, $broken );
1001 // Code below will ask if it exists, and the answer is now no
1006 if ( !file_exists( $thumbPath ) ||
1007 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1009 // Create the directory if it doesn't exist
1010 if ( is_file( $thumbDir ) ) {
1011 // File where thumb directory should be, destroy if possible
1012 @unlink
( $thumbDir );
1014 wfMkdirParents( $thumbDir );
1016 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1020 // Migration from old directory structure
1021 if ( is_file( $oldThumbPath ) ) {
1022 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1023 if ( file_exists( $thumbPath ) ) {
1024 if ( !is_dir( $thumbPath ) ) {
1025 // Old image in the way of rename
1026 unlink( $thumbPath );
1028 // This should have been dealt with already
1029 throw new MWException( "Directory where image should be: $thumbPath" );
1032 // Rename the old image into the new location
1033 rename( $oldThumbPath, $thumbPath );
1036 unlink( $oldThumbPath );
1040 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1041 if ( $this->lastError
=== true ) {
1043 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1044 // Log the error but output anyway.
1045 // With luck it's a transitory error...
1050 # This has to be done after the image is updated and present for all machines on NFS,
1051 # or else the old version might be stored into the squid again
1052 if ( $wgUseSquid ) {
1053 $urlArr = array( $url );
1054 wfPurgeSquidServers($urlArr);
1060 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1064 wfProfileOut( __METHOD__
);
1066 } // END OF function renderThumb
1069 * Really render a thumbnail
1070 * Call this only for images for which canRender() returns true.
1072 * @param string $thumbPath Path to thumbnail
1073 * @param int $width Desired width in pixels
1074 * @param int $height Desired height in pixels
1075 * @return bool True on error, false or error string on failure.
1078 function reallyRenderThumb( $thumbPath, $width, $height ) {
1079 global $wgSVGConverters, $wgSVGConverter;
1080 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1081 global $wgCustomConvertCommand;
1089 if( $this->mime
=== "image/svg" ) {
1090 #Right now we have only SVG
1092 global $wgSVGConverters, $wgSVGConverter;
1093 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1094 global $wgSVGConverterPath;
1096 array( '$path/', '$width', '$height', '$input', '$output' ),
1097 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1100 wfEscapeShellArg( $this->imagePath
),
1101 wfEscapeShellArg( $thumbPath ) ),
1102 $wgSVGConverters[$wgSVGConverter] );
1103 wfProfileIn( 'rsvg' );
1104 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1105 $err = wfShellExec( $cmd, $retval );
1106 wfProfileOut( 'rsvg' );
1108 } elseif ( $wgUseImageMagick ) {
1111 if ( $this->mime
== 'image/jpeg' ) {
1112 $quality = "-quality 80"; // 80%
1113 } elseif ( $this->mime
== 'image/png' ) {
1114 $quality = "-quality 95"; // zlib 9, adaptive filtering
1116 $quality = ''; // default
1119 # Specify white background color, will be used for transparent images
1120 # in Internet Explorer/Windows instead of default black.
1122 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1123 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1124 # the wrong size in the second case.
1126 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1127 " {$quality} -background white -size {$width} ".
1128 wfEscapeShellArg($this->imagePath
) .
1129 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1131 // For the -resize option a "!" is needed to force exact size,
1132 // or ImageMagick may decide your ratio is wrong and slice off
1134 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1136 wfEscapeShellArg($thumbPath) . " 2>&1";
1137 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1138 wfProfileIn( 'convert' );
1139 $err = wfShellExec( $cmd, $retval );
1140 wfProfileOut( 'convert' );
1141 } elseif( $wgCustomConvertCommand ) {
1142 # Use a custom convert command
1143 # Variables: %s %d %w %h
1144 $src = wfEscapeShellArg( $this->imagePath
);
1145 $dst = wfEscapeShellArg( $thumbPath );
1146 $cmd = $wgCustomConvertCommand;
1147 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1148 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1149 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1150 wfProfileIn( 'convert' );
1151 $err = wfShellExec( $cmd, $retval );
1152 wfProfileOut( 'convert' );
1154 # Use PHP's builtin GD library functions.
1156 # First find out what kind of file this is, and select the correct
1157 # input routine for this.
1160 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1161 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1162 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1163 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1164 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1166 if( !isset( $typemap[$this->mime
] ) ) {
1167 $err = 'Image type not supported';
1168 wfDebug( "$err\n" );
1171 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1173 if( !function_exists( $loader ) ) {
1174 $err = "Incomplete GD library configuration: missing function $loader";
1175 wfDebug( "$err\n" );
1178 if( $colorStyle == 'palette' ) {
1180 } elseif( $colorStyle == 'truecolor' ) {
1182 } elseif( $colorStyle == 'bits' ) {
1183 $truecolor = ( $this->bits
> 8 );
1186 $src_image = call_user_func( $loader, $this->imagePath
);
1188 $dst_image = imagecreatetruecolor( $width, $height );
1190 $dst_image = imagecreate( $width, $height );
1192 imagecopyresampled( $dst_image, $src_image,
1194 $width, $height, $this->width
, $this->height
);
1195 call_user_func( $saveType, $dst_image, $thumbPath );
1196 imagedestroy( $dst_image );
1197 imagedestroy( $src_image );
1201 # Check for zero-sized thumbnails. Those can be generated when
1202 # no disk space is available or some other error occurs
1204 if( file_exists( $thumbPath ) ) {
1205 $thumbstat = stat( $thumbPath );
1206 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1207 wfDebugLog( 'thumbnail',
1208 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1209 $thumbstat['size'], $thumbPath ) );
1210 unlink( $thumbPath );
1213 if ( $retval != 0 ) {
1214 wfDebugLog( 'thumbnail',
1215 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1216 wfHostname(), $retval, trim($err), $cmd ) );
1217 return wfMsg( 'thumbnail_error', $err );
1223 function getLastError() {
1224 return $this->lastError
;
1227 function imageJpegWrapper( $dst_image, $thumbPath ) {
1228 imageinterlace( $dst_image );
1229 imagejpeg( $dst_image, $thumbPath, 95 );
1233 * Get all thumbnail names previously generated for this image
1235 function getThumbnails( $shared = false ) {
1236 if ( Image
::isHashed( $shared ) ) {
1239 $dir = wfImageThumbDir( $this->name
, $shared );
1241 // This generates an error on failure, hence the @
1242 $handle = @opendir
( $dir );
1245 while ( false !== ( $file = readdir($handle) ) ) {
1246 if ( $file{0} != '.' ) {
1250 closedir( $handle );
1260 * Refresh metadata in memcached, but don't touch thumbnails or squid
1262 function purgeMetadataCache() {
1264 $this->loadFromFile();
1265 $this->saveToCache();
1269 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1271 function purgeCache( $archiveFiles = array(), $shared = false ) {
1274 // Refresh metadata cache
1275 $this->purgeMetadataCache();
1277 // Delete thumbnails
1278 $files = $this->getThumbnails( $shared );
1279 $dir = wfImageThumbDir( $this->name
, $shared );
1281 foreach ( $files as $file ) {
1282 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1283 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1284 @unlink
( "$dir/$file" );
1289 if ( $wgUseSquid ) {
1290 $urls[] = $this->getViewURL();
1291 foreach ( $archiveFiles as $file ) {
1292 $urls[] = wfImageArchiveUrl( $file );
1294 wfPurgeSquidServers( $urls );
1299 * Purge the image description page, but don't go after
1300 * pages using the image. Use when modifying file history
1301 * but not the current data.
1303 function purgeDescription() {
1304 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1305 $page->invalidateCache();
1306 $page->purgeSquid();
1310 * Purge metadata and all affected pages when the image is created,
1311 * deleted, or majorly updated. A set of additional URLs may be
1312 * passed to purge, such as specific image files which have changed.
1313 * @param $urlArray array
1315 function purgeEverything( $urlArr=array() ) {
1316 // Delete thumbnails and refresh image metadata cache
1317 $this->purgeCache();
1318 $this->purgeDescription();
1320 // Purge cache of all pages using this image
1321 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1322 $update->doUpdate();
1325 function checkDBSchema(&$db) {
1326 global $wgCheckDBSchema;
1327 if (!$wgCheckDBSchema) {
1330 # img_name must be unique
1331 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1332 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1335 # new fields must exist
1337 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1338 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1339 # something. The only reason I put the above schema check in was because the absence of that particular
1340 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1343 if ( !$db->fieldExists( 'image', 'img_media_type' )
1344 || !$db->fieldExists( 'image', 'img_metadata' )
1345 || !$db->fieldExists( 'image', 'img_width' ) ) {
1347 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1353 * Return the image history of this image, line by line.
1354 * starts with current version, then old versions.
1355 * uses $this->historyLine to check which line to return:
1356 * 0 return line for current version
1357 * 1 query for old versions, return first one
1358 * 2, ... return next old version from above query
1362 function nextHistoryLine() {
1363 $dbr =& wfGetDB( DB_SLAVE
);
1365 $this->checkDBSchema($dbr);
1367 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1368 $this->historyRes
= $dbr->select( 'image',
1372 'img_user','img_user_text',
1376 "'' AS oi_archive_name"
1378 array( 'img_name' => $this->title
->getDBkey() ),
1381 if ( 0 == wfNumRows( $this->historyRes
) ) {
1384 } else if ( $this->historyLine
== 1 ) {
1385 $this->historyRes
= $dbr->select( 'oldimage',
1387 'oi_size AS img_size',
1388 'oi_description AS img_description',
1389 'oi_user AS img_user',
1390 'oi_user_text AS img_user_text',
1391 'oi_timestamp AS img_timestamp',
1392 'oi_width as img_width',
1393 'oi_height as img_height',
1396 array( 'oi_name' => $this->title
->getDBkey() ),
1398 array( 'ORDER BY' => 'oi_timestamp DESC' )
1401 $this->historyLine ++
;
1403 return $dbr->fetchObject( $this->historyRes
);
1407 * Reset the history pointer to the first element of the history
1410 function resetHistory() {
1411 $this->historyLine
= 0;
1415 * Return the full filesystem path to the file. Note that this does
1416 * not mean that a file actually exists under that location.
1418 * This path depends on whether directory hashing is active or not,
1419 * i.e. whether the images are all found in the same directory,
1420 * or in hashed paths like /images/3/3c.
1423 * @param boolean $fromSharedDirectory Return the path to the file
1424 * in a shared repository (see $wgUseSharedRepository and related
1425 * options in DefaultSettings.php) instead of a local one.
1428 function getFullPath( $fromSharedRepository = false ) {
1429 global $wgUploadDirectory, $wgSharedUploadDirectory;
1431 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1434 // $wgSharedUploadDirectory may be false, if thumb.php is used
1436 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1448 function isHashed( $shared ) {
1449 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1450 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1454 * Record an image upload in the upload log and the image table
1456 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1457 global $wgUser, $wgUseCopyrightUpload;
1459 $dbw =& wfGetDB( DB_MASTER
);
1461 $this->checkDBSchema($dbw);
1463 // Delete thumbnails and refresh the metadata cache
1464 $this->purgeCache();
1466 // Fail now if the image isn't there
1467 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1468 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1472 if ( $wgUseCopyrightUpload ) {
1473 if ( $license != '' ) {
1474 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1476 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1477 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1479 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1481 if ( $license != '' ) {
1482 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1483 $textdesc = $filedesc .
1484 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1490 $now = $dbw->timestamp();
1493 if (strpos($this->mime
,'/')!==false) {
1494 list($major,$minor)= explode('/',$this->mime
,2);
1497 $major= $this->mime
;
1501 # Test to see if the row exists using INSERT IGNORE
1502 # This avoids race conditions by locking the row until the commit, and also
1503 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1504 $dbw->insert( 'image',
1506 'img_name' => $this->name
,
1507 'img_size'=> $this->size
,
1508 'img_width' => intval( $this->width
),
1509 'img_height' => intval( $this->height
),
1510 'img_bits' => $this->bits
,
1511 'img_media_type' => $this->type
,
1512 'img_major_mime' => $major,
1513 'img_minor_mime' => $minor,
1514 'img_timestamp' => $now,
1515 'img_description' => $desc,
1516 'img_user' => $wgUser->getID(),
1517 'img_user_text' => $wgUser->getName(),
1518 'img_metadata' => $this->metadata
,
1524 if( $dbw->affectedRows() == 0 ) {
1525 # Collision, this is an update of an image
1526 # Insert previous contents into oldimage
1527 $dbw->insertSelect( 'oldimage', 'image',
1529 'oi_name' => 'img_name',
1530 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1531 'oi_size' => 'img_size',
1532 'oi_width' => 'img_width',
1533 'oi_height' => 'img_height',
1534 'oi_bits' => 'img_bits',
1535 'oi_timestamp' => 'img_timestamp',
1536 'oi_description' => 'img_description',
1537 'oi_user' => 'img_user',
1538 'oi_user_text' => 'img_user_text',
1539 ), array( 'img_name' => $this->name
), __METHOD__
1542 # Update the current image row
1543 $dbw->update( 'image',
1545 'img_size' => $this->size
,
1546 'img_width' => intval( $this->width
),
1547 'img_height' => intval( $this->height
),
1548 'img_bits' => $this->bits
,
1549 'img_media_type' => $this->type
,
1550 'img_major_mime' => $major,
1551 'img_minor_mime' => $minor,
1552 'img_timestamp' => $now,
1553 'img_description' => $desc,
1554 'img_user' => $wgUser->getID(),
1555 'img_user_text' => $wgUser->getName(),
1556 'img_metadata' => $this->metadata
,
1557 ), array( /* WHERE */
1558 'img_name' => $this->name
1562 # This is a new image
1563 # Update the image count
1564 $site_stats = $dbw->tableName( 'site_stats' );
1565 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1568 $descTitle = $this->getTitle();
1569 $article = new Article( $descTitle );
1571 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1572 $suppressRC = true; // There's already a log entry, so don't double the RC load
1574 if( $descTitle->exists() ) {
1575 // TODO: insert a null revision into the page history for this update.
1577 $wgUser->addWatch( $descTitle );
1580 # Invalidate the cache for the description page
1581 $descTitle->invalidateCache();
1582 $descTitle->purgeSquid();
1584 // New image; create the description page.
1585 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1589 $log = new LogPage( 'upload' );
1590 $log->addEntry( 'upload', $descTitle, $desc );
1592 # Commit the transaction now, in case something goes wrong later
1593 # The most important thing is that images don't get lost, especially archives
1594 $dbw->immediateCommit();
1596 # Invalidate cache for all pages using this image
1597 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1598 $update->doUpdate();
1604 * Get an array of Title objects which are articles which use this image
1605 * Also adds their IDs to the link cache
1607 * This is mostly copied from Title::getLinksTo()
1609 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1611 function getLinksTo( $options = '' ) {
1612 wfProfileIn( __METHOD__
);
1615 $db =& wfGetDB( DB_MASTER
);
1617 $db =& wfGetDB( DB_SLAVE
);
1619 $linkCache =& LinkCache
::singleton();
1621 extract( $db->tableNames( 'page', 'imagelinks' ) );
1622 $encName = $db->addQuotes( $this->name
);
1623 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1624 $res = $db->query( $sql, __METHOD__
);
1627 if ( $db->numRows( $res ) ) {
1628 while ( $row = $db->fetchObject( $res ) ) {
1629 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1630 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1631 $retVal[] = $titleObj;
1635 $db->freeResult( $res );
1636 wfProfileOut( __METHOD__
);
1641 * Retrive Exif data from the file and prune unrecognized tags
1642 * and/or tags with invalid contents
1647 private function retrieveExifData( $filename ) {
1651 if ( $this->getMimeType() !== "image/jpeg" )
1655 if( $wgShowEXIF && file_exists( $filename ) ) {
1656 $exif = new Exif( $filename );
1657 return $exif->getFilteredData();
1663 function getExifData() {
1665 if ( $this->metadata
=== '0' )
1668 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1669 $ret = unserialize( $this->metadata
);
1671 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1672 $newver = Exif
::version();
1674 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1675 $this->purgeMetadataCache();
1676 $this->updateExifData( $newver );
1678 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1679 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1680 $format = new FormatExif( $ret );
1682 return $format->getFormattedData();
1685 function updateExifData( $version ) {
1686 if ( $this->getImagePath() === false ) # Not a local image
1689 # Get EXIF data from image
1690 $exif = $this->retrieveExifData( $this->imagePath
);
1691 if ( count( $exif ) ) {
1692 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1693 $this->metadata
= serialize( $exif );
1695 $this->metadata
= '0';
1698 # Update EXIF data in database
1699 $dbw =& wfGetDB( DB_MASTER
);
1701 $this->checkDBSchema($dbw);
1703 $dbw->update( 'image',
1704 array( 'img_metadata' => $this->metadata
),
1705 array( 'img_name' => $this->name
),
1711 * Returns true if the image does not come from the shared
1716 function isLocal() {
1717 return !$this->fromSharedDirectory
;
1721 * Was this image ever deleted from the wiki?
1725 function wasDeleted() {
1726 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1727 return ( $title->isDeleted() > 0 );
1731 * Delete all versions of the image.
1733 * Moves the files into an archive directory (or deletes them)
1734 * and removes the database rows.
1736 * Cache purging is done; logging is caller's responsibility.
1739 * @return true on success, false on some kind of failure
1741 function delete( $reason ) {
1742 $transaction = new FSTransaction();
1743 $urlArr = array( $this->getURL() );
1745 if( !FileStore
::lock() ) {
1746 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1751 $dbw = wfGetDB( DB_MASTER
);
1754 // Delete old versions
1755 $result = $dbw->select( 'oldimage',
1756 array( 'oi_archive_name' ),
1757 array( 'oi_name' => $this->name
) );
1759 while( $row = $dbw->fetchObject( $result ) ) {
1760 $oldName = $row->oi_archive_name
;
1762 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1764 // We'll need to purge this URL from caches...
1765 $urlArr[] = wfImageArchiveUrl( $oldName );
1767 $dbw->freeResult( $result );
1769 // And the current version...
1770 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1772 $dbw->immediateCommit();
1773 } catch( MWException
$e ) {
1774 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1775 $transaction->rollback();
1776 FileStore
::unlock();
1780 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1781 $transaction->commit();
1782 FileStore
::unlock();
1785 // Update site_stats
1786 $site_stats = $dbw->tableName( 'site_stats' );
1787 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1789 $this->purgeEverything( $urlArr );
1796 * Delete an old version of the image.
1798 * Moves the file into an archive directory (or deletes it)
1799 * and removes the database row.
1801 * Cache purging is done; logging is caller's responsibility.
1804 * @throws MWException or FSException on database or filestore failure
1805 * @return true on success, false on some kind of failure
1807 function deleteOld( $archiveName, $reason ) {
1808 $transaction = new FSTransaction();
1811 if( !FileStore
::lock() ) {
1812 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1816 $transaction = new FSTransaction();
1818 $dbw = wfGetDB( DB_MASTER
);
1820 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1821 $dbw->immediateCommit();
1822 } catch( MWException
$e ) {
1823 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1824 $transaction->rollback();
1825 FileStore
::unlock();
1829 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1830 $transaction->commit();
1831 FileStore
::unlock();
1833 $this->purgeDescription();
1837 if ( $wgUseSquid ) {
1839 wfImageArchiveUrl( $archiveName ),
1841 wfPurgeSquidServers( $urlArr );
1847 * Delete the current version of a file.
1848 * May throw a database error.
1849 * @return true on success, false on failure
1851 private function prepareDeleteCurrent( $reason ) {
1852 return $this->prepareDeleteVersion(
1853 $this->getFullPath(),
1857 'fa_name' => 'img_name',
1858 'fa_archive_name' => 'NULL',
1859 'fa_size' => 'img_size',
1860 'fa_width' => 'img_width',
1861 'fa_height' => 'img_height',
1862 'fa_metadata' => 'img_metadata',
1863 'fa_bits' => 'img_bits',
1864 'fa_media_type' => 'img_media_type',
1865 'fa_major_mime' => 'img_major_mime',
1866 'fa_minor_mime' => 'img_minor_mime',
1867 'fa_description' => 'img_description',
1868 'fa_user' => 'img_user',
1869 'fa_user_text' => 'img_user_text',
1870 'fa_timestamp' => 'img_timestamp' ),
1871 array( 'img_name' => $this->name
),
1876 * Delete a given older version of a file.
1877 * May throw a database error.
1878 * @return true on success, false on failure
1880 private function prepareDeleteOld( $archiveName, $reason ) {
1881 $oldpath = wfImageArchiveDir( $this->name
) .
1882 DIRECTORY_SEPARATOR
. $archiveName;
1883 return $this->prepareDeleteVersion(
1888 'fa_name' => 'oi_name',
1889 'fa_archive_name' => 'oi_archive_name',
1890 'fa_size' => 'oi_size',
1891 'fa_width' => 'oi_width',
1892 'fa_height' => 'oi_height',
1893 'fa_metadata' => 'NULL',
1894 'fa_bits' => 'oi_bits',
1895 'fa_media_type' => 'NULL',
1896 'fa_major_mime' => 'NULL',
1897 'fa_minor_mime' => 'NULL',
1898 'fa_description' => 'oi_description',
1899 'fa_user' => 'oi_user',
1900 'fa_user_text' => 'oi_user_text',
1901 'fa_timestamp' => 'oi_timestamp' ),
1903 'oi_name' => $this->name
,
1904 'oi_archive_name' => $archiveName ),
1909 * Do the dirty work of backing up an image row and its file
1910 * (if $wgSaveDeletedFiles is on) and removing the originals.
1912 * Must be run while the file store is locked and a database
1913 * transaction is open to avoid race conditions.
1915 * @return FSTransaction
1917 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1918 global $wgUser, $wgSaveDeletedFiles;
1920 // Dupe the file into the file store
1921 if( file_exists( $path ) ) {
1922 if( $wgSaveDeletedFiles ) {
1925 $store = FileStore
::get( $group );
1926 $key = FileStore
::calculateKey( $path, $this->extension
);
1927 $transaction = $store->insert( $key, $path,
1928 FileStore
::DELETE_ORIGINAL
);
1932 $transaction = FileStore
::deleteFile( $path );
1935 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1938 $transaction = new FSTransaction(); // empty
1941 if( $transaction === false ) {
1943 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1944 throw new MWException( "Could not archive and delete file $path" );
1948 $dbw = wfGetDB( DB_MASTER
);
1949 $storageMap = array(
1950 'fa_storage_group' => $dbw->addQuotes( $group ),
1951 'fa_storage_key' => $dbw->addQuotes( $key ),
1953 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1954 'fa_deleted_timestamp' => $dbw->timestamp(),
1955 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
1956 $allFields = array_merge( $storageMap, $fieldMap );
1959 if( $wgSaveDeletedFiles ) {
1960 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1962 $dbw->delete( $table, $where, $fname );
1963 } catch( DBQueryError
$e ) {
1964 // Something went horribly wrong!
1965 // Leave the file as it was...
1966 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
1967 $transaction->rollback();
1971 return $transaction;
1975 * Restore all or specified deleted revisions to the given file.
1976 * Permissions and logging are left to the caller.
1978 * May throw database exceptions on error.
1980 * @param $versions set of record ids of deleted items to restore,
1981 * or empty to restore all revisions.
1982 * @return the number of file revisions restored if successful,
1983 * or false on failure
1985 function restore( $versions=array() ) {
1986 if( !FileStore
::lock() ) {
1987 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
1991 $transaction = new FSTransaction();
1993 $dbw = wfGetDB( DB_MASTER
);
1996 // Re-confirm whether this image presently exists;
1997 // if no we'll need to create an image record for the
1998 // first item we restore.
1999 $exists = $dbw->selectField( 'image', '1',
2000 array( 'img_name' => $this->name
),
2003 // Fetch all or selected archived revisions for the file,
2004 // sorted from the most recent to the oldest.
2005 $conditions = array( 'fa_name' => $this->name
);
2007 $conditions['fa_id'] = $versions;
2010 $result = $dbw->select( 'filearchive', '*',
2013 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2015 if( $dbw->numRows( $result ) < count( $versions ) ) {
2016 // There's some kind of conflict or confusion;
2017 // we can't restore everything we were asked to.
2018 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2020 FileStore
::unlock();
2024 if( $dbw->numRows( $result ) == 0 ) {
2026 wfDebug( __METHOD__
.": nothing to do\n" );
2028 FileStore
::unlock();
2033 while( $row = $dbw->fetchObject( $result ) ) {
2035 $store = FileStore
::get( $row->fa_storage_group
);
2037 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2041 if( $revisions == 1 && !$exists ) {
2042 $destDir = wfImageDir( $row->fa_name
);
2043 if ( !is_dir( $destDir ) ) {
2044 wfMkdirParents( $destDir );
2046 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2048 // We may have to fill in data if this was originally
2049 // an archived file revision.
2050 if( is_null( $row->fa_metadata
) ) {
2051 $tempFile = $store->filePath( $row->fa_storage_key
);
2052 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2054 $magic = wfGetMimeMagic();
2055 $mime = $magic->guessMimeType( $tempFile, true );
2056 $media_type = $magic->getMediaType( $tempFile, $mime );
2057 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2059 $metadata = $row->fa_metadata
;
2060 $major_mime = $row->fa_major_mime
;
2061 $minor_mime = $row->fa_minor_mime
;
2062 $media_type = $row->fa_media_type
;
2067 'img_name' => $row->fa_name
,
2068 'img_size' => $row->fa_size
,
2069 'img_width' => $row->fa_width
,
2070 'img_height' => $row->fa_height
,
2071 'img_metadata' => $metadata,
2072 'img_bits' => $row->fa_bits
,
2073 'img_media_type' => $media_type,
2074 'img_major_mime' => $major_mime,
2075 'img_minor_mime' => $minor_mime,
2076 'img_description' => $row->fa_description
,
2077 'img_user' => $row->fa_user
,
2078 'img_user_text' => $row->fa_user_text
,
2079 'img_timestamp' => $row->fa_timestamp
);
2081 $archiveName = $row->fa_archive_name
;
2082 if( $archiveName == '' ) {
2083 // This was originally a current version; we
2084 // have to devise a new archive name for it.
2085 // Format is <timestamp of archiving>!<name>
2087 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2088 '!' . $row->fa_name
;
2090 $destDir = wfImageArchiveDir( $row->fa_name
);
2091 if ( !is_dir( $destDir ) ) {
2092 wfMkdirParents( $destDir );
2094 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2096 $table = 'oldimage';
2098 'oi_name' => $row->fa_name
,
2099 'oi_archive_name' => $archiveName,
2100 'oi_size' => $row->fa_size
,
2101 'oi_width' => $row->fa_width
,
2102 'oi_height' => $row->fa_height
,
2103 'oi_bits' => $row->fa_bits
,
2104 'oi_description' => $row->fa_description
,
2105 'oi_user' => $row->fa_user
,
2106 'oi_user_text' => $row->fa_user_text
,
2107 'oi_timestamp' => $row->fa_timestamp
);
2110 $dbw->insert( $table, $fields, __METHOD__
);
2111 /// @fixme this delete is not totally safe, potentially
2112 $dbw->delete( 'filearchive',
2113 array( 'fa_id' => $row->fa_id
),
2116 // Check if any other stored revisions use this file;
2117 // if so, we shouldn't remove the file from the deletion
2118 // archives so they will still work.
2119 $useCount = $dbw->selectField( 'filearchive',
2122 'fa_storage_group' => $row->fa_storage_group
,
2123 'fa_storage_key' => $row->fa_storage_key
),
2125 if( $useCount == 0 ) {
2126 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2127 $flags = FileStore
::DELETE_ORIGINAL
;
2132 $transaction->add( $store->export( $row->fa_storage_key
,
2133 $destPath, $flags ) );
2136 $dbw->immediateCommit();
2137 } catch( MWException
$e ) {
2138 wfDebug( __METHOD__
." caught error, aborting\n" );
2139 $transaction->rollback();
2143 $transaction->commit();
2144 FileStore
::unlock();
2146 if( $revisions > 0 ) {
2148 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2150 // Update site_stats
2151 $site_stats = $dbw->tableName( 'site_stats' );
2152 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2154 $this->purgeEverything();
2156 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2157 $this->purgeDescription();
2167 * Wrapper class for thumbnail images
2168 * @package MediaWiki
2170 class ThumbnailImage
{
2172 * @param string $path Filesystem path to the thumb
2173 * @param string $url URL path to the thumb
2176 function ThumbnailImage( $url, $width, $height, $path = false ) {
2178 $this->width
= round( $width );
2179 $this->height
= round( $height );
2180 # These should be integers when they get here.
2181 # If not, there's a bug somewhere. But let's at
2182 # least produce valid HTML code regardless.
2183 $this->path
= $path;
2187 * @return string The thumbnail URL
2194 * Return HTML <img ... /> tag for the thumbnail, will include
2195 * width and height attributes and a blank alt text (as required).
2197 * You can set or override additional attributes by passing an
2198 * associative array of name => data pairs. The data will be escaped
2199 * for HTML output, so should be in plaintext.
2201 * @param array $attribs
2205 function toHtml( $attribs = array() ) {
2206 $attribs['src'] = $this->url
;
2207 $attribs['width'] = $this->width
;
2208 $attribs['height'] = $this->height
;
2209 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2212 foreach( $attribs as $name => $data ) {
2213 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';