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 * @param boolean $render True to render the thumbnail if it doesn't exist,
886 * false to just return the URL
888 * @return ThumbnailImage or null on failure
891 function getThumbnail( $width, $height=-1, $render = true ) {
892 wfProfileIn( __METHOD__
);
893 if ($this->canRender()) {
896 if ( $width > $this->width
* $height / $this->height
) {
897 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
901 $thumb = $this->renderThumb( $width );
903 // Don't render, just return the URL
904 if ( $this->validateThumbParams( $width, $height ) ) {
905 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
906 $url = $this->getURL();
908 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
910 $thumb = new ThumbnailImage( $url, $width, $height );
916 // not a bitmap or renderable image, don't try.
917 $thumb = $this->iconThumb();
919 wfProfileOut( __METHOD__
);
924 * @return ThumbnailImage
926 function iconThumb() {
927 global $wgStylePath, $wgStyleDirectory;
929 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
930 foreach( $try as $icon ) {
931 $path = '/common/images/icons/' . $icon;
932 $filepath = $wgStyleDirectory . $path;
933 if( file_exists( $filepath ) ) {
934 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
941 * Validate thumbnail parameters and fill in the correct height
943 * @param integer &$width Specified width (input/output)
944 * @param integer &$height Height (output only)
945 * @return false to indicate that an error should be returned to the user.
947 function validateThumbParams( &$width, &$height ) {
948 global $wgSVGMaxSize, $wgMaxImageArea;
952 if ( ! $this->exists() )
954 # If there is no image, there will be no thumbnail
958 $width = intval( $width );
960 # Sanity check $width
961 if( $width <= 0 ||
$this->width
<= 0) {
966 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
967 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
968 # an exception for it.
969 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
970 $this->getMimeType() !== 'image/jpeg' &&
971 $this->width
* $this->height
> $wgMaxImageArea )
976 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
977 if ( $this->mustRender() ) {
978 $width = min( $width, $wgSVGMaxSize );
979 } elseif ( $width > $this->width
- 1 ) {
980 $width = $this->width
;
981 $height = $this->height
;
985 $height = round( $this->height
* $width / $this->width
);
990 * Create a thumbnail of the image having the specified width.
991 * The thumbnail will not be created if the width is larger than the
992 * image's width. Let the browser do the scaling in this case.
993 * The thumbnail is stored on disk and is only computed if the thumbnail
994 * file does not exist OR if it is older than the image.
995 * Returns an object which can return the pathname, URL, and physical
996 * pixel size of the thumbnail -- or null on failure.
998 * @return ThumbnailImage or null on failure
1001 function renderThumb( $width, $useScript = true ) {
1002 global $wgUseSquid, $wgThumbnailEpoch;
1004 wfProfileIn( __METHOD__
);
1008 if ( !$this->validateThumbParams( $width, $height ) ) {
1010 wfProfileOut( __METHOD__
);
1014 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1015 # validateThumbParams (or the user) wants us to return the unscaled image
1016 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1017 wfProfileOut( __METHOD__
);
1021 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1022 if ( $isScriptUrl && $useScript ) {
1023 // Use thumb.php to render the image
1024 $thumb = new ThumbnailImage( $url, $width, $height );
1025 wfProfileOut( __METHOD__
);
1029 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
1030 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
1031 $thumbPath = $thumbDir.'/'.$thumbName;
1033 if ( is_dir( $thumbPath ) ) {
1034 // Directory where file should be
1035 // This happened occasionally due to broken migration code in 1.5
1036 // Rename to broken-*
1037 global $wgUploadDirectory;
1038 for ( $i = 0; $i < 100 ; $i++
) {
1039 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1040 if ( !file_exists( $broken ) ) {
1041 rename( $thumbPath, $broken );
1045 // Code below will ask if it exists, and the answer is now no
1050 if ( !file_exists( $thumbPath ) ||
1051 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1053 // Create the directory if it doesn't exist
1054 if ( is_file( $thumbDir ) ) {
1055 // File where thumb directory should be, destroy if possible
1056 @unlink
( $thumbDir );
1058 wfMkdirParents( $thumbDir );
1060 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1064 // Migration from old directory structure
1065 if ( is_file( $oldThumbPath ) ) {
1066 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1067 if ( file_exists( $thumbPath ) ) {
1068 if ( !is_dir( $thumbPath ) ) {
1069 // Old image in the way of rename
1070 unlink( $thumbPath );
1072 // This should have been dealt with already
1073 throw new MWException( "Directory where image should be: $thumbPath" );
1076 // Rename the old image into the new location
1077 rename( $oldThumbPath, $thumbPath );
1080 unlink( $oldThumbPath );
1084 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1085 if ( $this->lastError
=== true ) {
1087 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1088 // Log the error but output anyway.
1089 // With luck it's a transitory error...
1094 # This has to be done after the image is updated and present for all machines on NFS,
1095 # or else the old version might be stored into the squid again
1096 if ( $wgUseSquid ) {
1097 $urlArr = array( $url );
1098 wfPurgeSquidServers($urlArr);
1104 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1108 wfProfileOut( __METHOD__
);
1110 } // END OF function renderThumb
1113 * Really render a thumbnail
1114 * Call this only for images for which canRender() returns true.
1116 * @param string $thumbPath Path to thumbnail
1117 * @param int $width Desired width in pixels
1118 * @param int $height Desired height in pixels
1119 * @return bool True on error, false or error string on failure.
1122 function reallyRenderThumb( $thumbPath, $width, $height ) {
1123 global $wgSVGConverters, $wgSVGConverter;
1124 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1125 global $wgCustomConvertCommand;
1133 if( $this->mime
=== "image/svg" ) {
1134 #Right now we have only SVG
1136 global $wgSVGConverters, $wgSVGConverter;
1137 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1138 global $wgSVGConverterPath;
1140 array( '$path/', '$width', '$height', '$input', '$output' ),
1141 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1144 wfEscapeShellArg( $this->imagePath
),
1145 wfEscapeShellArg( $thumbPath ) ),
1146 $wgSVGConverters[$wgSVGConverter] );
1147 wfProfileIn( 'rsvg' );
1148 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1149 $err = wfShellExec( $cmd, $retval );
1150 wfProfileOut( 'rsvg' );
1152 } elseif ( $wgUseImageMagick ) {
1155 if ( $this->mime
== 'image/jpeg' ) {
1156 $quality = "-quality 80"; // 80%
1157 } elseif ( $this->mime
== 'image/png' ) {
1158 $quality = "-quality 95"; // zlib 9, adaptive filtering
1160 $quality = ''; // default
1163 # Specify white background color, will be used for transparent images
1164 # in Internet Explorer/Windows instead of default black.
1166 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1167 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1168 # the wrong size in the second case.
1170 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1171 " {$quality} -background white -size {$width} ".
1172 wfEscapeShellArg($this->imagePath
) .
1173 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1175 // For the -resize option a "!" is needed to force exact size,
1176 // or ImageMagick may decide your ratio is wrong and slice off
1178 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1180 wfEscapeShellArg($thumbPath) . " 2>&1";
1181 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1182 wfProfileIn( 'convert' );
1183 $err = wfShellExec( $cmd, $retval );
1184 wfProfileOut( 'convert' );
1185 } elseif( $wgCustomConvertCommand ) {
1186 # Use a custom convert command
1187 # Variables: %s %d %w %h
1188 $src = wfEscapeShellArg( $this->imagePath
);
1189 $dst = wfEscapeShellArg( $thumbPath );
1190 $cmd = $wgCustomConvertCommand;
1191 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1192 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1193 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1194 wfProfileIn( 'convert' );
1195 $err = wfShellExec( $cmd, $retval );
1196 wfProfileOut( 'convert' );
1198 # Use PHP's builtin GD library functions.
1200 # First find out what kind of file this is, and select the correct
1201 # input routine for this.
1204 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1205 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1206 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1207 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1208 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1210 if( !isset( $typemap[$this->mime
] ) ) {
1211 $err = 'Image type not supported';
1212 wfDebug( "$err\n" );
1215 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1217 if( !function_exists( $loader ) ) {
1218 $err = "Incomplete GD library configuration: missing function $loader";
1219 wfDebug( "$err\n" );
1222 if( $colorStyle == 'palette' ) {
1224 } elseif( $colorStyle == 'truecolor' ) {
1226 } elseif( $colorStyle == 'bits' ) {
1227 $truecolor = ( $this->bits
> 8 );
1230 $src_image = call_user_func( $loader, $this->imagePath
);
1232 $dst_image = imagecreatetruecolor( $width, $height );
1234 $dst_image = imagecreate( $width, $height );
1236 imagecopyresampled( $dst_image, $src_image,
1238 $width, $height, $this->width
, $this->height
);
1239 call_user_func( $saveType, $dst_image, $thumbPath );
1240 imagedestroy( $dst_image );
1241 imagedestroy( $src_image );
1245 # Check for zero-sized thumbnails. Those can be generated when
1246 # no disk space is available or some other error occurs
1248 if( file_exists( $thumbPath ) ) {
1249 $thumbstat = stat( $thumbPath );
1250 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1251 wfDebugLog( 'thumbnail',
1252 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1253 $thumbstat['size'], $thumbPath ) );
1254 unlink( $thumbPath );
1257 if ( $retval != 0 ) {
1258 wfDebugLog( 'thumbnail',
1259 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1260 wfHostname(), $retval, trim($err), $cmd ) );
1261 return wfMsg( 'thumbnail_error', $err );
1267 function getLastError() {
1268 return $this->lastError
;
1271 function imageJpegWrapper( $dst_image, $thumbPath ) {
1272 imageinterlace( $dst_image );
1273 imagejpeg( $dst_image, $thumbPath, 95 );
1277 * Get all thumbnail names previously generated for this image
1279 function getThumbnails( $shared = false ) {
1280 if ( Image
::isHashed( $shared ) ) {
1283 $dir = wfImageThumbDir( $this->name
, $shared );
1285 // This generates an error on failure, hence the @
1286 $handle = @opendir
( $dir );
1289 while ( false !== ( $file = readdir($handle) ) ) {
1290 if ( $file{0} != '.' ) {
1294 closedir( $handle );
1304 * Refresh metadata in memcached, but don't touch thumbnails or squid
1306 function purgeMetadataCache() {
1308 $this->loadFromFile();
1309 $this->saveToCache();
1313 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1315 function purgeCache( $archiveFiles = array(), $shared = false ) {
1318 // Refresh metadata cache
1319 $this->purgeMetadataCache();
1321 // Delete thumbnails
1322 $files = $this->getThumbnails( $shared );
1323 $dir = wfImageThumbDir( $this->name
, $shared );
1325 foreach ( $files as $file ) {
1326 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1327 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1328 @unlink
( "$dir/$file" );
1333 if ( $wgUseSquid ) {
1334 $urls[] = $this->getViewURL();
1335 foreach ( $archiveFiles as $file ) {
1336 $urls[] = wfImageArchiveUrl( $file );
1338 wfPurgeSquidServers( $urls );
1343 * Purge the image description page, but don't go after
1344 * pages using the image. Use when modifying file history
1345 * but not the current data.
1347 function purgeDescription() {
1348 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1349 $page->invalidateCache();
1350 $page->purgeSquid();
1354 * Purge metadata and all affected pages when the image is created,
1355 * deleted, or majorly updated. A set of additional URLs may be
1356 * passed to purge, such as specific image files which have changed.
1357 * @param $urlArray array
1359 function purgeEverything( $urlArr=array() ) {
1360 // Delete thumbnails and refresh image metadata cache
1361 $this->purgeCache();
1362 $this->purgeDescription();
1364 // Purge cache of all pages using this image
1365 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1366 $update->doUpdate();
1369 function checkDBSchema(&$db) {
1370 global $wgCheckDBSchema;
1371 if (!$wgCheckDBSchema) {
1374 # img_name must be unique
1375 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1376 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1379 # new fields must exist
1381 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1382 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1383 # something. The only reason I put the above schema check in was because the absence of that particular
1384 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1387 if ( !$db->fieldExists( 'image', 'img_media_type' )
1388 || !$db->fieldExists( 'image', 'img_metadata' )
1389 || !$db->fieldExists( 'image', 'img_width' ) ) {
1391 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1397 * Return the image history of this image, line by line.
1398 * starts with current version, then old versions.
1399 * uses $this->historyLine to check which line to return:
1400 * 0 return line for current version
1401 * 1 query for old versions, return first one
1402 * 2, ... return next old version from above query
1406 function nextHistoryLine() {
1407 $dbr =& wfGetDB( DB_SLAVE
);
1409 $this->checkDBSchema($dbr);
1411 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1412 $this->historyRes
= $dbr->select( 'image',
1416 'img_user','img_user_text',
1420 "'' AS oi_archive_name"
1422 array( 'img_name' => $this->title
->getDBkey() ),
1425 if ( 0 == wfNumRows( $this->historyRes
) ) {
1428 } else if ( $this->historyLine
== 1 ) {
1429 $this->historyRes
= $dbr->select( 'oldimage',
1431 'oi_size AS img_size',
1432 'oi_description AS img_description',
1433 'oi_user AS img_user',
1434 'oi_user_text AS img_user_text',
1435 'oi_timestamp AS img_timestamp',
1436 'oi_width as img_width',
1437 'oi_height as img_height',
1440 array( 'oi_name' => $this->title
->getDBkey() ),
1442 array( 'ORDER BY' => 'oi_timestamp DESC' )
1445 $this->historyLine ++
;
1447 return $dbr->fetchObject( $this->historyRes
);
1451 * Reset the history pointer to the first element of the history
1454 function resetHistory() {
1455 $this->historyLine
= 0;
1459 * Return the full filesystem path to the file. Note that this does
1460 * not mean that a file actually exists under that location.
1462 * This path depends on whether directory hashing is active or not,
1463 * i.e. whether the images are all found in the same directory,
1464 * or in hashed paths like /images/3/3c.
1467 * @param boolean $fromSharedDirectory Return the path to the file
1468 * in a shared repository (see $wgUseSharedRepository and related
1469 * options in DefaultSettings.php) instead of a local one.
1472 function getFullPath( $fromSharedRepository = false ) {
1473 global $wgUploadDirectory, $wgSharedUploadDirectory;
1475 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1478 // $wgSharedUploadDirectory may be false, if thumb.php is used
1480 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1492 public static function isHashed( $shared ) {
1493 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1494 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1498 * Record an image upload in the upload log and the image table
1500 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1501 global $wgUser, $wgUseCopyrightUpload;
1503 $dbw =& wfGetDB( DB_MASTER
);
1505 $this->checkDBSchema($dbw);
1507 // Delete thumbnails and refresh the metadata cache
1508 $this->purgeCache();
1510 // Fail now if the image isn't there
1511 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1512 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1516 if ( $wgUseCopyrightUpload ) {
1517 if ( $license != '' ) {
1518 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1520 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1521 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1523 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1525 if ( $license != '' ) {
1526 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1527 $textdesc = $filedesc .
1528 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1534 $now = $dbw->timestamp();
1537 if (strpos($this->mime
,'/')!==false) {
1538 list($major,$minor)= explode('/',$this->mime
,2);
1541 $major= $this->mime
;
1545 # Test to see if the row exists using INSERT IGNORE
1546 # This avoids race conditions by locking the row until the commit, and also
1547 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1548 $dbw->insert( 'image',
1550 'img_name' => $this->name
,
1551 'img_size'=> $this->size
,
1552 'img_width' => intval( $this->width
),
1553 'img_height' => intval( $this->height
),
1554 'img_bits' => $this->bits
,
1555 'img_media_type' => $this->type
,
1556 'img_major_mime' => $major,
1557 'img_minor_mime' => $minor,
1558 'img_timestamp' => $now,
1559 'img_description' => $desc,
1560 'img_user' => $wgUser->getID(),
1561 'img_user_text' => $wgUser->getName(),
1562 'img_metadata' => $this->metadata
,
1568 if( $dbw->affectedRows() == 0 ) {
1569 # Collision, this is an update of an image
1570 # Insert previous contents into oldimage
1571 $dbw->insertSelect( 'oldimage', 'image',
1573 'oi_name' => 'img_name',
1574 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1575 'oi_size' => 'img_size',
1576 'oi_width' => 'img_width',
1577 'oi_height' => 'img_height',
1578 'oi_bits' => 'img_bits',
1579 'oi_timestamp' => 'img_timestamp',
1580 'oi_description' => 'img_description',
1581 'oi_user' => 'img_user',
1582 'oi_user_text' => 'img_user_text',
1583 ), array( 'img_name' => $this->name
), __METHOD__
1586 # Update the current image row
1587 $dbw->update( 'image',
1589 'img_size' => $this->size
,
1590 'img_width' => intval( $this->width
),
1591 'img_height' => intval( $this->height
),
1592 'img_bits' => $this->bits
,
1593 'img_media_type' => $this->type
,
1594 'img_major_mime' => $major,
1595 'img_minor_mime' => $minor,
1596 'img_timestamp' => $now,
1597 'img_description' => $desc,
1598 'img_user' => $wgUser->getID(),
1599 'img_user_text' => $wgUser->getName(),
1600 'img_metadata' => $this->metadata
,
1601 ), array( /* WHERE */
1602 'img_name' => $this->name
1606 # This is a new image
1607 # Update the image count
1608 $site_stats = $dbw->tableName( 'site_stats' );
1609 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1612 $descTitle = $this->getTitle();
1613 $article = new Article( $descTitle );
1615 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1616 $suppressRC = true; // There's already a log entry, so don't double the RC load
1618 if( $descTitle->exists() ) {
1619 // TODO: insert a null revision into the page history for this update.
1621 $wgUser->addWatch( $descTitle );
1624 # Invalidate the cache for the description page
1625 $descTitle->invalidateCache();
1626 $descTitle->purgeSquid();
1628 // New image; create the description page.
1629 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1633 $log = new LogPage( 'upload' );
1634 $log->addEntry( 'upload', $descTitle, $desc );
1636 # Commit the transaction now, in case something goes wrong later
1637 # The most important thing is that images don't get lost, especially archives
1638 $dbw->immediateCommit();
1640 # Invalidate cache for all pages using this image
1641 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1642 $update->doUpdate();
1648 * Get an array of Title objects which are articles which use this image
1649 * Also adds their IDs to the link cache
1651 * This is mostly copied from Title::getLinksTo()
1653 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1655 function getLinksTo( $options = '' ) {
1656 wfProfileIn( __METHOD__
);
1659 $db =& wfGetDB( DB_MASTER
);
1661 $db =& wfGetDB( DB_SLAVE
);
1663 $linkCache =& LinkCache
::singleton();
1665 extract( $db->tableNames( 'page', 'imagelinks' ) );
1666 $encName = $db->addQuotes( $this->name
);
1667 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1668 $res = $db->query( $sql, __METHOD__
);
1671 if ( $db->numRows( $res ) ) {
1672 while ( $row = $db->fetchObject( $res ) ) {
1673 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1674 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1675 $retVal[] = $titleObj;
1679 $db->freeResult( $res );
1680 wfProfileOut( __METHOD__
);
1685 * Retrive Exif data from the file and prune unrecognized tags
1686 * and/or tags with invalid contents
1691 private function retrieveExifData( $filename ) {
1695 if ( $this->getMimeType() !== "image/jpeg" )
1699 if( $wgShowEXIF && file_exists( $filename ) ) {
1700 $exif = new Exif( $filename );
1701 return $exif->getFilteredData();
1707 function getExifData() {
1709 if ( $this->metadata
=== '0' )
1712 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1713 $ret = unserialize( $this->metadata
);
1715 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1716 $newver = Exif
::version();
1718 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1719 $this->purgeMetadataCache();
1720 $this->updateExifData( $newver );
1722 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1723 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1724 $format = new FormatExif( $ret );
1726 return $format->getFormattedData();
1729 function updateExifData( $version ) {
1730 if ( $this->getImagePath() === false ) # Not a local image
1733 # Get EXIF data from image
1734 $exif = $this->retrieveExifData( $this->imagePath
);
1735 if ( count( $exif ) ) {
1736 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1737 $this->metadata
= serialize( $exif );
1739 $this->metadata
= '0';
1742 # Update EXIF data in database
1743 $dbw =& wfGetDB( DB_MASTER
);
1745 $this->checkDBSchema($dbw);
1747 $dbw->update( 'image',
1748 array( 'img_metadata' => $this->metadata
),
1749 array( 'img_name' => $this->name
),
1755 * Returns true if the image does not come from the shared
1760 function isLocal() {
1761 return !$this->fromSharedDirectory
;
1765 * Was this image ever deleted from the wiki?
1769 function wasDeleted() {
1770 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1771 return ( $title->isDeleted() > 0 );
1775 * Delete all versions of the image.
1777 * Moves the files into an archive directory (or deletes them)
1778 * and removes the database rows.
1780 * Cache purging is done; logging is caller's responsibility.
1783 * @return true on success, false on some kind of failure
1785 function delete( $reason ) {
1786 $transaction = new FSTransaction();
1787 $urlArr = array( $this->getURL() );
1789 if( !FileStore
::lock() ) {
1790 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1795 $dbw = wfGetDB( DB_MASTER
);
1798 // Delete old versions
1799 $result = $dbw->select( 'oldimage',
1800 array( 'oi_archive_name' ),
1801 array( 'oi_name' => $this->name
) );
1803 while( $row = $dbw->fetchObject( $result ) ) {
1804 $oldName = $row->oi_archive_name
;
1806 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1808 // We'll need to purge this URL from caches...
1809 $urlArr[] = wfImageArchiveUrl( $oldName );
1811 $dbw->freeResult( $result );
1813 // And the current version...
1814 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1816 $dbw->immediateCommit();
1817 } catch( MWException
$e ) {
1818 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1819 $transaction->rollback();
1820 FileStore
::unlock();
1824 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1825 $transaction->commit();
1826 FileStore
::unlock();
1829 // Update site_stats
1830 $site_stats = $dbw->tableName( 'site_stats' );
1831 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1833 $this->purgeEverything( $urlArr );
1840 * Delete an old version of the image.
1842 * Moves the file into an archive directory (or deletes it)
1843 * and removes the database row.
1845 * Cache purging is done; logging is caller's responsibility.
1848 * @throws MWException or FSException on database or filestore failure
1849 * @return true on success, false on some kind of failure
1851 function deleteOld( $archiveName, $reason ) {
1852 $transaction = new FSTransaction();
1855 if( !FileStore
::lock() ) {
1856 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1860 $transaction = new FSTransaction();
1862 $dbw = wfGetDB( DB_MASTER
);
1864 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1865 $dbw->immediateCommit();
1866 } catch( MWException
$e ) {
1867 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1868 $transaction->rollback();
1869 FileStore
::unlock();
1873 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1874 $transaction->commit();
1875 FileStore
::unlock();
1877 $this->purgeDescription();
1881 if ( $wgUseSquid ) {
1883 wfImageArchiveUrl( $archiveName ),
1885 wfPurgeSquidServers( $urlArr );
1891 * Delete the current version of a file.
1892 * May throw a database error.
1893 * @return true on success, false on failure
1895 private function prepareDeleteCurrent( $reason ) {
1896 return $this->prepareDeleteVersion(
1897 $this->getFullPath(),
1901 'fa_name' => 'img_name',
1902 'fa_archive_name' => 'NULL',
1903 'fa_size' => 'img_size',
1904 'fa_width' => 'img_width',
1905 'fa_height' => 'img_height',
1906 'fa_metadata' => 'img_metadata',
1907 'fa_bits' => 'img_bits',
1908 'fa_media_type' => 'img_media_type',
1909 'fa_major_mime' => 'img_major_mime',
1910 'fa_minor_mime' => 'img_minor_mime',
1911 'fa_description' => 'img_description',
1912 'fa_user' => 'img_user',
1913 'fa_user_text' => 'img_user_text',
1914 'fa_timestamp' => 'img_timestamp' ),
1915 array( 'img_name' => $this->name
),
1920 * Delete a given older version of a file.
1921 * May throw a database error.
1922 * @return true on success, false on failure
1924 private function prepareDeleteOld( $archiveName, $reason ) {
1925 $oldpath = wfImageArchiveDir( $this->name
) .
1926 DIRECTORY_SEPARATOR
. $archiveName;
1927 return $this->prepareDeleteVersion(
1932 'fa_name' => 'oi_name',
1933 'fa_archive_name' => 'oi_archive_name',
1934 'fa_size' => 'oi_size',
1935 'fa_width' => 'oi_width',
1936 'fa_height' => 'oi_height',
1937 'fa_metadata' => 'NULL',
1938 'fa_bits' => 'oi_bits',
1939 'fa_media_type' => 'NULL',
1940 'fa_major_mime' => 'NULL',
1941 'fa_minor_mime' => 'NULL',
1942 'fa_description' => 'oi_description',
1943 'fa_user' => 'oi_user',
1944 'fa_user_text' => 'oi_user_text',
1945 'fa_timestamp' => 'oi_timestamp' ),
1947 'oi_name' => $this->name
,
1948 'oi_archive_name' => $archiveName ),
1953 * Do the dirty work of backing up an image row and its file
1954 * (if $wgSaveDeletedFiles is on) and removing the originals.
1956 * Must be run while the file store is locked and a database
1957 * transaction is open to avoid race conditions.
1959 * @return FSTransaction
1961 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1962 global $wgUser, $wgSaveDeletedFiles;
1964 // Dupe the file into the file store
1965 if( file_exists( $path ) ) {
1966 if( $wgSaveDeletedFiles ) {
1969 $store = FileStore
::get( $group );
1970 $key = FileStore
::calculateKey( $path, $this->extension
);
1971 $transaction = $store->insert( $key, $path,
1972 FileStore
::DELETE_ORIGINAL
);
1976 $transaction = FileStore
::deleteFile( $path );
1979 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1982 $transaction = new FSTransaction(); // empty
1985 if( $transaction === false ) {
1987 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1988 throw new MWException( "Could not archive and delete file $path" );
1992 $dbw = wfGetDB( DB_MASTER
);
1993 $storageMap = array(
1994 'fa_storage_group' => $dbw->addQuotes( $group ),
1995 'fa_storage_key' => $dbw->addQuotes( $key ),
1997 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1998 'fa_deleted_timestamp' => $dbw->timestamp(),
1999 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2000 $allFields = array_merge( $storageMap, $fieldMap );
2003 if( $wgSaveDeletedFiles ) {
2004 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2006 $dbw->delete( $table, $where, $fname );
2007 } catch( DBQueryError
$e ) {
2008 // Something went horribly wrong!
2009 // Leave the file as it was...
2010 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
2011 $transaction->rollback();
2015 return $transaction;
2019 * Restore all or specified deleted revisions to the given file.
2020 * Permissions and logging are left to the caller.
2022 * May throw database exceptions on error.
2024 * @param $versions set of record ids of deleted items to restore,
2025 * or empty to restore all revisions.
2026 * @return the number of file revisions restored if successful,
2027 * or false on failure
2029 function restore( $versions=array() ) {
2030 if( !FileStore
::lock() ) {
2031 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
2035 $transaction = new FSTransaction();
2037 $dbw = wfGetDB( DB_MASTER
);
2040 // Re-confirm whether this image presently exists;
2041 // if no we'll need to create an image record for the
2042 // first item we restore.
2043 $exists = $dbw->selectField( 'image', '1',
2044 array( 'img_name' => $this->name
),
2047 // Fetch all or selected archived revisions for the file,
2048 // sorted from the most recent to the oldest.
2049 $conditions = array( 'fa_name' => $this->name
);
2051 $conditions['fa_id'] = $versions;
2054 $result = $dbw->select( 'filearchive', '*',
2057 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2059 if( $dbw->numRows( $result ) < count( $versions ) ) {
2060 // There's some kind of conflict or confusion;
2061 // we can't restore everything we were asked to.
2062 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2064 FileStore
::unlock();
2068 if( $dbw->numRows( $result ) == 0 ) {
2070 wfDebug( __METHOD__
.": nothing to do\n" );
2072 FileStore
::unlock();
2077 while( $row = $dbw->fetchObject( $result ) ) {
2079 $store = FileStore
::get( $row->fa_storage_group
);
2081 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2085 if( $revisions == 1 && !$exists ) {
2086 $destDir = wfImageDir( $row->fa_name
);
2087 if ( !is_dir( $destDir ) ) {
2088 wfMkdirParents( $destDir );
2090 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2092 // We may have to fill in data if this was originally
2093 // an archived file revision.
2094 if( is_null( $row->fa_metadata
) ) {
2095 $tempFile = $store->filePath( $row->fa_storage_key
);
2096 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2098 $magic = wfGetMimeMagic();
2099 $mime = $magic->guessMimeType( $tempFile, true );
2100 $media_type = $magic->getMediaType( $tempFile, $mime );
2101 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2103 $metadata = $row->fa_metadata
;
2104 $major_mime = $row->fa_major_mime
;
2105 $minor_mime = $row->fa_minor_mime
;
2106 $media_type = $row->fa_media_type
;
2111 'img_name' => $row->fa_name
,
2112 'img_size' => $row->fa_size
,
2113 'img_width' => $row->fa_width
,
2114 'img_height' => $row->fa_height
,
2115 'img_metadata' => $metadata,
2116 'img_bits' => $row->fa_bits
,
2117 'img_media_type' => $media_type,
2118 'img_major_mime' => $major_mime,
2119 'img_minor_mime' => $minor_mime,
2120 'img_description' => $row->fa_description
,
2121 'img_user' => $row->fa_user
,
2122 'img_user_text' => $row->fa_user_text
,
2123 'img_timestamp' => $row->fa_timestamp
);
2125 $archiveName = $row->fa_archive_name
;
2126 if( $archiveName == '' ) {
2127 // This was originally a current version; we
2128 // have to devise a new archive name for it.
2129 // Format is <timestamp of archiving>!<name>
2131 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2132 '!' . $row->fa_name
;
2134 $destDir = wfImageArchiveDir( $row->fa_name
);
2135 if ( !is_dir( $destDir ) ) {
2136 wfMkdirParents( $destDir );
2138 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2140 $table = 'oldimage';
2142 'oi_name' => $row->fa_name
,
2143 'oi_archive_name' => $archiveName,
2144 'oi_size' => $row->fa_size
,
2145 'oi_width' => $row->fa_width
,
2146 'oi_height' => $row->fa_height
,
2147 'oi_bits' => $row->fa_bits
,
2148 'oi_description' => $row->fa_description
,
2149 'oi_user' => $row->fa_user
,
2150 'oi_user_text' => $row->fa_user_text
,
2151 'oi_timestamp' => $row->fa_timestamp
);
2154 $dbw->insert( $table, $fields, __METHOD__
);
2155 /// @fixme this delete is not totally safe, potentially
2156 $dbw->delete( 'filearchive',
2157 array( 'fa_id' => $row->fa_id
),
2160 // Check if any other stored revisions use this file;
2161 // if so, we shouldn't remove the file from the deletion
2162 // archives so they will still work.
2163 $useCount = $dbw->selectField( 'filearchive',
2166 'fa_storage_group' => $row->fa_storage_group
,
2167 'fa_storage_key' => $row->fa_storage_key
),
2169 if( $useCount == 0 ) {
2170 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2171 $flags = FileStore
::DELETE_ORIGINAL
;
2176 $transaction->add( $store->export( $row->fa_storage_key
,
2177 $destPath, $flags ) );
2180 $dbw->immediateCommit();
2181 } catch( MWException
$e ) {
2182 wfDebug( __METHOD__
." caught error, aborting\n" );
2183 $transaction->rollback();
2187 $transaction->commit();
2188 FileStore
::unlock();
2190 if( $revisions > 0 ) {
2192 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2194 // Update site_stats
2195 $site_stats = $dbw->tableName( 'site_stats' );
2196 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2198 $this->purgeEverything();
2200 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2201 $this->purgeDescription();
2211 * Wrapper class for thumbnail images
2212 * @package MediaWiki
2214 class ThumbnailImage
{
2216 * @param string $path Filesystem path to the thumb
2217 * @param string $url URL path to the thumb
2220 function ThumbnailImage( $url, $width, $height, $path = false ) {
2222 $this->width
= round( $width );
2223 $this->height
= round( $height );
2224 # These should be integers when they get here.
2225 # If not, there's a bug somewhere. But let's at
2226 # least produce valid HTML code regardless.
2227 $this->path
= $path;
2231 * @return string The thumbnail URL
2238 * Return HTML <img ... /> tag for the thumbnail, will include
2239 * width and height attributes and a blank alt text (as required).
2241 * You can set or override additional attributes by passing an
2242 * associative array of name => data pairs. The data will be escaped
2243 * for HTML output, so should be in plaintext.
2245 * @param array $attribs
2249 function toHtml( $attribs = array() ) {
2250 $attribs['src'] = $this->url
;
2251 $attribs['width'] = $this->width
;
2252 $attribs['height'] = $this->height
;
2253 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2256 foreach( $attribs as $name => $data ) {
2257 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';