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 $page, # Page to render when creating thumbnails
50 $lastError; # Error string associated with a thumbnail display error
56 * Create an Image object from an image name
58 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
61 function newFromName( $name ) {
62 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
63 if ( is_object( $title ) ) {
64 return new Image( $title );
71 * Obsolete factory function, use constructor
74 function newFromTitle( $title ) {
75 return new Image( $title );
78 function Image( $title ) {
79 if( !is_object( $title ) ) {
80 throw new MWException( 'Image constructor given bogus title.' );
82 $this->title
=& $title;
83 $this->name
= $title->getDBkey();
84 $this->metadata
= serialize ( array() ) ;
86 $n = strrpos( $this->name
, '.' );
87 $this->extension
= Image
::normalizeExtension( $n ?
88 substr( $this->name
, $n +
1 ) : '' );
89 $this->historyLine
= 0;
92 $this->dataLoaded
= false;
97 * Normalize a file extension to the common form, and ensure it's clean.
98 * Extensions with non-alphanumeric characters will be discarded.
100 * @param $ext string (without the .)
103 static function normalizeExtension( $ext ) {
104 $lower = strtolower( $ext );
110 if( isset( $squish[$lower] ) ) {
111 return $squish[$lower];
112 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
120 * Get the memcached keys
121 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
123 function getCacheKeys( ) {
124 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
126 $hashedName = md5($this->name
);
127 $keys = array( "$wgDBname:Image:$hashedName" );
128 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
129 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
135 * Try to load image metadata from memcached. Returns true on success.
137 function loadFromCache() {
138 global $wgUseSharedUploads, $wgMemc;
139 wfProfileIn( __METHOD__
);
140 $this->dataLoaded
= false;
141 $keys = $this->getCacheKeys();
142 $cachedValues = $wgMemc->get( $keys[0] );
144 // Check if the key existed and belongs to this version of MediaWiki
145 if (!empty($cachedValues) && is_array($cachedValues)
146 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
147 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
149 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
150 # if this is shared file, we need to check if image
151 # in shared repository has not changed
152 if ( isset( $keys[1] ) ) {
153 $commonsCachedValues = $wgMemc->get( $keys[1] );
154 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
155 && isset($commonsCachedValues['version'])
156 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
157 && isset($commonsCachedValues['mime'])) {
158 wfDebug( "Pulling image metadata from shared repository cache\n" );
159 $this->name
= $commonsCachedValues['name'];
160 $this->imagePath
= $commonsCachedValues['imagePath'];
161 $this->fileExists
= $commonsCachedValues['fileExists'];
162 $this->width
= $commonsCachedValues['width'];
163 $this->height
= $commonsCachedValues['height'];
164 $this->bits
= $commonsCachedValues['bits'];
165 $this->type
= $commonsCachedValues['type'];
166 $this->mime
= $commonsCachedValues['mime'];
167 $this->metadata
= $commonsCachedValues['metadata'];
168 $this->size
= $commonsCachedValues['size'];
169 $this->fromSharedDirectory
= true;
170 $this->dataLoaded
= true;
171 $this->imagePath
= $this->getFullPath(true);
175 wfDebug( "Pulling image metadata from local cache\n" );
176 $this->name
= $cachedValues['name'];
177 $this->imagePath
= $cachedValues['imagePath'];
178 $this->fileExists
= $cachedValues['fileExists'];
179 $this->width
= $cachedValues['width'];
180 $this->height
= $cachedValues['height'];
181 $this->bits
= $cachedValues['bits'];
182 $this->type
= $cachedValues['type'];
183 $this->mime
= $cachedValues['mime'];
184 $this->metadata
= $cachedValues['metadata'];
185 $this->size
= $cachedValues['size'];
186 $this->fromSharedDirectory
= false;
187 $this->dataLoaded
= true;
188 $this->imagePath
= $this->getFullPath();
191 if ( $this->dataLoaded
) {
192 wfIncrStats( 'image_cache_hit' );
194 wfIncrStats( 'image_cache_miss' );
197 wfProfileOut( __METHOD__
);
198 return $this->dataLoaded
;
202 * Save the image metadata to memcached
204 function saveToCache() {
205 global $wgMemc, $wgUseSharedUploads;
207 $keys = $this->getCacheKeys();
208 // We can't cache negative metadata for non-existent files,
209 // because if the file later appears in commons, the local
210 // keys won't be purged.
211 if ( $this->fileExists ||
!$wgUseSharedUploads ) {
212 $cachedValues = array(
213 'version' => MW_IMAGE_VERSION
,
214 'name' => $this->name
,
215 'imagePath' => $this->imagePath
,
216 'fileExists' => $this->fileExists
,
217 'fromShared' => $this->fromSharedDirectory
,
218 'width' => $this->width
,
219 'height' => $this->height
,
220 'bits' => $this->bits
,
221 'type' => $this->type
,
222 'mime' => $this->mime
,
223 'metadata' => $this->metadata
,
224 'size' => $this->size
);
226 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
228 // However we should clear them, so they aren't leftover
229 // if we've deleted the file.
230 $wgMemc->delete( $keys[0] );
235 * Load metadata from the file itself
237 function loadFromFile() {
238 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
239 wfProfileIn( __METHOD__
);
240 $this->imagePath
= $this->getFullPath();
241 $this->fileExists
= file_exists( $this->imagePath
);
242 $this->fromSharedDirectory
= false;
245 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
247 # If the file is not found, and a shared upload directory is used, look for it there.
248 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
249 # In case we're on a wgCapitalLinks=false wiki, we
250 # capitalize the first letter of the filename before
251 # looking it up in the shared repository.
252 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
253 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
254 if ( $this->fileExists
) {
255 $this->name
= $sharedImage->name
;
256 $this->imagePath
= $this->getFullPath(true);
257 $this->fromSharedDirectory
= true;
262 if ( $this->fileExists
) {
263 $magic=& wfGetMimeMagic();
265 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
266 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
269 $this->size
= filesize( $this->imagePath
);
271 $magic=& wfGetMimeMagic();
274 wfSuppressWarnings();
275 if( $this->mime
== 'image/svg' ) {
276 $gis = wfGetSVGsize( $this->imagePath
);
277 } elseif( $this->mime
== 'image/vnd.djvu' ) {
278 $deja = new DjVuImage( $this->imagePath
);
279 $gis = $deja->getImageSize();
280 } elseif ( !$magic->isPHPImageType( $this->mime
) ) {
281 # Don't try to get the width and height of sound and video files, that's bad for performance
284 $gis = getimagesize( $this->imagePath
);
288 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
292 $this->type
= MEDIATYPE_UNKNOWN
;
293 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
297 $this->width
= $gis[0];
298 $this->height
= $gis[1];
304 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
306 #NOTE: we have to set this flag early to avoid load() to be called
307 # be some of the functions below. This may lead to recursion or other bad things!
308 # as ther's only one thread of execution, this should be safe anyway.
309 $this->dataLoaded
= true;
312 if ( $this->mime
== 'image/vnd.djvu' ) {
313 $this->metadata
= $deja->retrieveMetaData();
315 $this->metadata
= serialize( $this->retrieveExifData( $this->imagePath
) );
318 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
319 else $this->bits
= 0;
321 wfProfileOut( __METHOD__
);
325 * Load image metadata from the DB
327 function loadFromDB() {
328 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
329 wfProfileIn( __METHOD__
);
331 $dbr =& wfGetDB( DB_SLAVE
);
332 $this->checkDBSchema($dbr);
334 $row = $dbr->selectRow( 'image',
335 array( 'img_size', 'img_width', 'img_height', 'img_bits',
336 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
337 array( 'img_name' => $this->name
), __METHOD__
);
339 $this->fromSharedDirectory
= false;
340 $this->fileExists
= true;
341 $this->loadFromRow( $row );
342 $this->imagePath
= $this->getFullPath();
343 // Check for rows from a previous schema, quietly upgrade them
344 if ( is_null($this->type
) ) {
347 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
348 # In case we're on a wgCapitalLinks=false wiki, we
349 # capitalize the first letter of the filename before
350 # looking it up in the shared repository.
351 $name = $wgContLang->ucfirst($this->name
);
352 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
354 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
356 'img_size', 'img_width', 'img_height', 'img_bits',
357 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
358 array( 'img_name' => $name ), __METHOD__
);
360 $this->fromSharedDirectory
= true;
361 $this->fileExists
= true;
362 $this->imagePath
= $this->getFullPath(true);
364 $this->loadFromRow( $row );
366 // Check for rows from a previous schema, quietly upgrade them
367 if ( is_null($this->type
) ) {
379 $this->fileExists
= false;
380 $this->fromSharedDirectory
= false;
381 $this->metadata
= serialize ( array() ) ;
385 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
386 $this->dataLoaded
= true;
387 wfProfileOut( __METHOD__
);
391 * Load image metadata from a DB result row
393 function loadFromRow( &$row ) {
394 $this->size
= $row->img_size
;
395 $this->width
= $row->img_width
;
396 $this->height
= $row->img_height
;
397 $this->bits
= $row->img_bits
;
398 $this->type
= $row->img_media_type
;
400 $major= $row->img_major_mime
;
401 $minor= $row->img_minor_mime
;
403 if (!$major) $this->mime
= "unknown/unknown";
405 if (!$minor) $minor= "unknown";
406 $this->mime
= $major.'/'.$minor;
409 $this->metadata
= $row->img_metadata
;
410 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
412 $this->dataLoaded
= true;
416 * Load image metadata from cache or DB, unless already loaded
419 global $wgSharedUploadDBname, $wgUseSharedUploads;
420 if ( !$this->dataLoaded
) {
421 if ( !$this->loadFromCache() ) {
423 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
424 $this->loadFromFile();
425 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
426 // We can do negative caching for local images, because the cache
427 // will be purged on upload. But we can't do it when shared images
428 // are enabled, since updates to that won't purge foreign caches.
429 $this->saveToCache();
432 $this->dataLoaded
= true;
437 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
438 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
440 function upgradeRow() {
441 global $wgDBname, $wgSharedUploadDBname;
442 wfProfileIn( __METHOD__
);
444 $this->loadFromFile();
446 if ( $this->fromSharedDirectory
) {
447 if ( !$wgSharedUploadDBname ) {
448 wfProfileOut( __METHOD__
);
452 // Write to the other DB using selectDB, not database selectors
453 // This avoids breaking replication in MySQL
454 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
455 $dbw->selectDB( $wgSharedUploadDBname );
457 $dbw =& wfGetDB( DB_MASTER
);
460 $this->checkDBSchema($dbw);
462 list( $major, $minor ) = self
::splitMime( $this->mime
);
464 wfDebug(__METHOD__
.': upgrading '.$this->name
." to 1.5 schema\n");
466 $dbw->update( 'image',
468 'img_width' => $this->width
,
469 'img_height' => $this->height
,
470 'img_bits' => $this->bits
,
471 'img_media_type' => $this->type
,
472 'img_major_mime' => $major,
473 'img_minor_mime' => $minor,
474 'img_metadata' => $this->metadata
,
475 ), array( 'img_name' => $this->name
), __METHOD__
477 if ( $this->fromSharedDirectory
) {
478 $dbw->selectDB( $wgDBname );
480 wfProfileOut( __METHOD__
);
484 * Split an internet media type into its two components; if not
485 * a two-part name, set the minor type to 'unknown'.
487 * @param $mime "text/html" etc
488 * @return array ("text", "html") etc
490 static function splitMime( $mime ) {
491 if( strpos( $mime, '/' ) !== false ) {
492 return explode( '/', $mime, 2 );
494 return array( $mime, 'unknown' );
499 * Return the name of this image
507 * Return the associated title object
510 function getTitle() {
515 * Return the URL of the image file
521 if($this->fileExists
) {
522 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
530 function getViewURL() {
531 if( $this->mustRender()) {
532 if( $this->canRender() ) {
533 return $this->createThumb( $this->getWidth() );
536 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
537 return $this->getURL(); #hm... return NULL?
540 return $this->getURL();
545 * Return the image path of the image in the
546 * local file system as an absolute path
549 function getImagePath() {
551 return $this->imagePath
;
555 * Return the width of the image
557 * Returns -1 if the file specified is not a known image type
560 function getWidth() {
566 * Return the height of the image
568 * Returns -1 if the file specified is not a known image type
571 function getHeight() {
573 return $this->height
;
577 * Return the size of the image file, in bytes
586 * Returns the mime type of the file.
588 function getMimeType() {
594 * Return the type of the media in the file.
595 * Use the value returned by this function with the MEDIATYPE_xxx constants.
597 function getMediaType() {
603 * Checks if the file can be presented to the browser as a bitmap.
605 * Currently, this checks if the file is an image format
606 * that can be converted to a format
607 * supported by all browsers (namely GIF, PNG and JPEG),
608 * or if it is an SVG image and SVG conversion is enabled.
610 * @todo remember the result of this check.
612 function canRender() {
613 global $wgUseImageMagick, $wgDjvuRenderer;
615 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
617 $mime= $this->getMimeType();
619 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
621 #if it's SVG, check if there's a converter enabled
622 if ($mime === 'image/svg') {
623 global $wgSVGConverters, $wgSVGConverter;
625 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
626 wfDebug( "Image::canRender: SVG is ready!\n" );
629 wfDebug( "Image::canRender: SVG renderer missing\n" );
633 #image formats available on ALL browsers
634 if ( $mime === 'image/gif'
635 ||
$mime === 'image/png'
636 ||
$mime === 'image/jpeg' ) return true;
638 #image formats that can be converted to the above formats
639 if ($wgUseImageMagick) {
640 #convertable by ImageMagick (there are more...)
641 if ( $mime === 'image/vnd.wap.wbmp'
642 ||
$mime === 'image/x-xbitmap'
643 ||
$mime === 'image/x-xpixmap'
644 #|| $mime === 'image/x-icon' #file may be split into multiple parts
645 ||
$mime === 'image/x-portable-anymap'
646 ||
$mime === 'image/x-portable-bitmap'
647 ||
$mime === 'image/x-portable-graymap'
648 ||
$mime === 'image/x-portable-pixmap'
649 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
650 ||
$mime === 'image/x-rgb'
651 ||
$mime === 'image/x-bmp'
652 ||
$mime === 'image/tiff' ) return true;
655 #convertable by the PHP GD image lib
656 if ( $mime === 'image/vnd.wap.wbmp'
657 ||
$mime === 'image/x-xbitmap' ) return true;
659 if ( $mime === 'image/vnd.djvu' && isset( $wgDjvuRenderer ) && $wgDjvuRenderer ) return true;
666 * Return true if the file is of a type that can't be directly
667 * rendered by typical browsers and needs to be re-rasterized.
669 * This returns true for everything but the bitmap types
670 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
671 * also return true for any non-image formats.
675 function mustRender() {
676 $mime= $this->getMimeType();
678 if ( $mime === "image/gif"
679 ||
$mime === "image/png"
680 ||
$mime === "image/jpeg" ) return false;
686 * Determines if this media file may be shown inline on a page.
688 * This is currently synonymous to canRender(), but this could be
689 * extended to also allow inline display of other media,
690 * like flash animations or videos. If you do so, please keep in mind that
691 * that could be a security risk.
693 function allowInlineDisplay() {
694 return $this->canRender();
698 * Determines if this media file is in a format that is unlikely to
699 * contain viruses or malicious content. It uses the global
700 * $wgTrustedMediaFormats list to determine if the file is safe.
702 * This is used to show a warning on the description page of non-safe files.
703 * It may also be used to disallow direct [[media:...]] links to such files.
705 * Note that this function will always return true if allowInlineDisplay()
706 * or isTrustedFile() is true for this file.
708 function isSafeFile() {
709 if ($this->allowInlineDisplay()) return true;
710 if ($this->isTrustedFile()) return true;
712 global $wgTrustedMediaFormats;
714 $type= $this->getMediaType();
715 $mime= $this->getMimeType();
716 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
718 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
719 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
721 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
722 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
727 /** Returns true if the file is flagged as trusted. Files flagged that way
728 * can be linked to directly, even if that is not allowed for this type of
731 * This is a dummy function right now and always returns false. It could be
732 * implemented to extract a flag from the database. The trusted flag could be
733 * set on upload, if the user has sufficient privileges, to bypass script-
734 * and html-filters. It may even be coupled with cryptographics signatures
737 function isTrustedFile() {
738 #this could be implemented to check a flag in the databas,
739 #look for signatures, etc
744 * Return the escapeLocalURL of this image
747 function getEscapeLocalURL( $query=false) {
749 if ( $query === false ) {
750 if ( $this->page
!= 1 ) {
751 $query = 'page=' . $this->page
;
756 return $this->title
->escapeLocalURL( $query );
760 * Return the escapeFullURL of this image
763 function getEscapeFullURL() {
765 return $this->title
->escapeFullURL();
769 * Return the URL of an image, provided its name.
771 * @param string $name Name of the image, without the leading "Image:"
772 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
773 * @return string URL of $name image
777 function imageUrl( $name, $fromSharedDirectory = false ) {
778 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
779 if($fromSharedDirectory) {
781 $path = $wgSharedUploadPath;
783 $base = $wgUploadBaseUrl;
784 $path = $wgUploadPath;
786 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
787 return wfUrlencode( $url );
791 * Returns true if the image file exists on disk.
792 * @return boolean Whether image file exist on disk.
797 return $this->fileExists
;
804 function thumbUrl( $width, $subdir='thumb') {
805 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
806 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
808 // Generate thumb.php URL if possible
812 if ( $this->fromSharedDirectory
) {
813 if ( $wgSharedThumbnailScriptPath ) {
814 $script = $wgSharedThumbnailScriptPath;
817 if ( $wgThumbnailScriptPath ) {
818 $script = $wgThumbnailScriptPath;
822 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
823 if( $this->mustRender() ) {
827 $name = $this->thumbName( $width );
828 if($this->fromSharedDirectory
) {
830 $path = $wgSharedUploadPath;
832 $base = $wgUploadBaseUrl;
833 $path = $wgUploadPath;
835 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
836 $url = "{$base}{$path}/{$subdir}" .
837 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
838 . $this->name
.'/'.$name;
839 $url = wfUrlencode( $url );
841 $url = "{$base}{$path}/{$subdir}/{$name}";
844 return array( $script !== false, $url );
848 * Return the file name of a thumbnail of the specified width
850 * @param integer $width Width of the thumbnail image
851 * @param boolean $shared Does the thumbnail come from the shared repository?
854 function thumbName( $width ) {
855 $thumb = $width."px-".$this->name
;
856 if ( $this->page
!= 1 ) {
857 $thumb = "page{$this->page}-$thumb";
860 if( $this->mustRender() ) {
861 if( $this->canRender() ) {
862 # Rasterize to PNG (for SVG vector images, etc)
866 #should we use iconThumb here to get a symbolic thumbnail?
867 #or should we fail with an internal error?
868 return NULL; //can't make bitmap
875 * Create a thumbnail of the image having the specified width/height.
876 * The thumbnail will not be created if the width is larger than the
877 * image's width. Let the browser do the scaling in this case.
878 * The thumbnail is stored on disk and is only computed if the thumbnail
879 * file does not exist OR if it is older than the image.
882 * Keeps aspect ratio of original image. If both width and height are
883 * specified, the generated image will be no bigger than width x height,
884 * and will also have correct aspect ratio.
886 * @param integer $width maximum width of the generated thumbnail
887 * @param integer $height maximum height of the image (optional)
890 function createThumb( $width, $height=-1 ) {
891 $thumb = $this->getThumbnail( $width, $height );
892 if( is_null( $thumb ) ) return '';
893 return $thumb->getUrl();
897 * As createThumb, but returns a ThumbnailImage object. This can
898 * provide access to the actual file, the real size of the thumb,
899 * and can produce a convenient <img> tag for you.
901 * For non-image formats, this may return a filetype-specific icon.
903 * @param integer $width maximum width of the generated thumbnail
904 * @param integer $height maximum height of the image (optional)
905 * @param boolean $render True to render the thumbnail if it doesn't exist,
906 * false to just return the URL
908 * @return ThumbnailImage or null on failure
911 function getThumbnail( $width, $height=-1, $render = true ) {
912 wfProfileIn( __METHOD__
);
913 if ($this->canRender()) {
916 if ( $width > $this->width
* $height / $this->height
) {
917 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
921 $thumb = $this->renderThumb( $width );
923 // Don't render, just return the URL
924 if ( $this->validateThumbParams( $width, $height ) ) {
925 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
926 $url = $this->getURL();
928 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
930 $thumb = new ThumbnailImage( $url, $width, $height );
936 // not a bitmap or renderable image, don't try.
937 $thumb = $this->iconThumb();
939 wfProfileOut( __METHOD__
);
944 * @return ThumbnailImage
946 function iconThumb() {
947 global $wgStylePath, $wgStyleDirectory;
949 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
950 foreach( $try as $icon ) {
951 $path = '/common/images/icons/' . $icon;
952 $filepath = $wgStyleDirectory . $path;
953 if( file_exists( $filepath ) ) {
954 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
961 * Validate thumbnail parameters and fill in the correct height
963 * @param integer &$width Specified width (input/output)
964 * @param integer &$height Height (output only)
965 * @return false to indicate that an error should be returned to the user.
967 function validateThumbParams( &$width, &$height ) {
968 global $wgSVGMaxSize, $wgMaxImageArea;
972 if ( ! $this->exists() )
974 # If there is no image, there will be no thumbnail
978 $width = intval( $width );
980 # Sanity check $width
981 if( $width <= 0 ||
$this->width
<= 0) {
986 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
987 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
988 # an exception for it.
989 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
990 $this->getMimeType() !== 'image/jpeg' &&
991 $this->width
* $this->height
> $wgMaxImageArea )
996 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
997 if ( $this->mustRender() ) {
998 $width = min( $width, $wgSVGMaxSize );
999 } elseif ( $width > $this->width
- 1 ) {
1000 $width = $this->width
;
1001 $height = $this->height
;
1005 $height = round( $this->height
* $width / $this->width
);
1010 * Create a thumbnail of the image having the specified width.
1011 * The thumbnail will not be created if the width is larger than the
1012 * image's width. Let the browser do the scaling in this case.
1013 * The thumbnail is stored on disk and is only computed if the thumbnail
1014 * file does not exist OR if it is older than the image.
1015 * Returns an object which can return the pathname, URL, and physical
1016 * pixel size of the thumbnail -- or null on failure.
1018 * @return ThumbnailImage or null on failure
1021 function renderThumb( $width, $useScript = true ) {
1022 global $wgUseSquid, $wgThumbnailEpoch;
1024 wfProfileIn( __METHOD__
);
1028 if ( !$this->validateThumbParams( $width, $height ) ) {
1030 wfProfileOut( __METHOD__
);
1034 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1035 # validateThumbParams (or the user) wants us to return the unscaled image
1036 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1037 wfProfileOut( __METHOD__
);
1041 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1042 if ( $isScriptUrl && $useScript ) {
1043 // Use thumb.php to render the image
1044 $thumb = new ThumbnailImage( $url, $width, $height );
1045 wfProfileOut( __METHOD__
);
1049 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
1050 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
1051 $thumbPath = $thumbDir.'/'.$thumbName;
1053 if ( is_dir( $thumbPath ) ) {
1054 // Directory where file should be
1055 // This happened occasionally due to broken migration code in 1.5
1056 // Rename to broken-*
1057 global $wgUploadDirectory;
1058 for ( $i = 0; $i < 100 ; $i++
) {
1059 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1060 if ( !file_exists( $broken ) ) {
1061 rename( $thumbPath, $broken );
1065 // Code below will ask if it exists, and the answer is now no
1070 if ( !file_exists( $thumbPath ) ||
1071 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1073 // Create the directory if it doesn't exist
1074 if ( is_file( $thumbDir ) ) {
1075 // File where thumb directory should be, destroy if possible
1076 @unlink
( $thumbDir );
1078 wfMkdirParents( $thumbDir );
1080 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1084 // Migration from old directory structure
1085 if ( is_file( $oldThumbPath ) ) {
1086 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1087 if ( file_exists( $thumbPath ) ) {
1088 if ( !is_dir( $thumbPath ) ) {
1089 // Old image in the way of rename
1090 unlink( $thumbPath );
1092 // This should have been dealt with already
1093 throw new MWException( "Directory where image should be: $thumbPath" );
1096 // Rename the old image into the new location
1097 rename( $oldThumbPath, $thumbPath );
1100 unlink( $oldThumbPath );
1104 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1105 if ( $this->lastError
=== true ) {
1107 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1108 // Log the error but output anyway.
1109 // With luck it's a transitory error...
1114 # This has to be done after the image is updated and present for all machines on NFS,
1115 # or else the old version might be stored into the squid again
1116 if ( $wgUseSquid ) {
1117 $urlArr = array( $url );
1118 wfPurgeSquidServers($urlArr);
1124 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1128 wfProfileOut( __METHOD__
);
1130 } // END OF function renderThumb
1133 * Really render a thumbnail
1134 * Call this only for images for which canRender() returns true.
1136 * @param string $thumbPath Path to thumbnail
1137 * @param int $width Desired width in pixels
1138 * @param int $height Desired height in pixels
1139 * @return bool True on error, false or error string on failure.
1142 function reallyRenderThumb( $thumbPath, $width, $height ) {
1143 global $wgSVGConverters, $wgSVGConverter;
1144 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1145 global $wgCustomConvertCommand;
1146 global $wgDjvuRenderer, $wgDjvuPostProcessor;
1154 if( $this->mime
=== "image/svg" ) {
1155 #Right now we have only SVG
1157 global $wgSVGConverters, $wgSVGConverter;
1158 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1159 global $wgSVGConverterPath;
1161 array( '$path/', '$width', '$height', '$input', '$output' ),
1162 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1165 wfEscapeShellArg( $this->imagePath
),
1166 wfEscapeShellArg( $thumbPath ) ),
1167 $wgSVGConverters[$wgSVGConverter] );
1168 wfProfileIn( 'rsvg' );
1169 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1170 $err = wfShellExec( $cmd, $retval );
1171 wfProfileOut( 'rsvg' );
1174 if ( $this->mime
=== "image/vnd.djvu" && $wgDjvuRenderer ) {
1176 // The file contains several images. First, extract the
1177 // page in hi-res, if it doesn't yet exist. Then, thumbnail
1180 $cmd = "{$wgDjvuRenderer} -page={$this->page} -size=${width}x${height} " .
1181 wfEscapeShellArg( $this->imagePath
) .
1182 " | {$wgDjvuPostProcessor} > " . wfEscapeShellArg($thumbPath);
1183 wfProfileIn( 'ddjvu' );
1184 wfDebug( "reallyRenderThumb DJVU: $cmd\n" );
1185 $err = wfShellExec( $cmd, $retval );
1186 wfProfileOut( 'ddjvu' );
1188 } elseif ( $wgUseImageMagick ) {
1191 if ( $this->mime
== 'image/jpeg' ) {
1192 $quality = "-quality 80"; // 80%
1193 } elseif ( $this->mime
== 'image/png' ) {
1194 $quality = "-quality 95"; // zlib 9, adaptive filtering
1196 $quality = ''; // default
1199 # Specify white background color, will be used for transparent images
1200 # in Internet Explorer/Windows instead of default black.
1202 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1203 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1204 # the wrong size in the second case.
1206 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1207 " {$quality} -background white -size {$width} ".
1208 wfEscapeShellArg($this->imagePath
) .
1209 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1211 // For the -resize option a "!" is needed to force exact size,
1212 // or ImageMagick may decide your ratio is wrong and slice off
1214 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1216 wfEscapeShellArg($thumbPath) . " 2>&1";
1217 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1218 wfProfileIn( 'convert' );
1219 $err = wfShellExec( $cmd, $retval );
1220 wfProfileOut( 'convert' );
1221 } elseif( $wgCustomConvertCommand ) {
1222 # Use a custom convert command
1223 # Variables: %s %d %w %h
1224 $src = wfEscapeShellArg( $this->imagePath
);
1225 $dst = wfEscapeShellArg( $thumbPath );
1226 $cmd = $wgCustomConvertCommand;
1227 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1228 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1229 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1230 wfProfileIn( 'convert' );
1231 $err = wfShellExec( $cmd, $retval );
1232 wfProfileOut( 'convert' );
1234 # Use PHP's builtin GD library functions.
1236 # First find out what kind of file this is, and select the correct
1237 # input routine for this.
1240 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1241 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1242 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1243 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1244 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1246 if( !isset( $typemap[$this->mime
] ) ) {
1247 $err = 'Image type not supported';
1248 wfDebug( "$err\n" );
1251 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1253 if( !function_exists( $loader ) ) {
1254 $err = "Incomplete GD library configuration: missing function $loader";
1255 wfDebug( "$err\n" );
1258 if( $colorStyle == 'palette' ) {
1260 } elseif( $colorStyle == 'truecolor' ) {
1262 } elseif( $colorStyle == 'bits' ) {
1263 $truecolor = ( $this->bits
> 8 );
1266 $src_image = call_user_func( $loader, $this->imagePath
);
1268 $dst_image = imagecreatetruecolor( $width, $height );
1270 $dst_image = imagecreate( $width, $height );
1272 imagecopyresampled( $dst_image, $src_image,
1274 $width, $height, $this->width
, $this->height
);
1275 call_user_func( $saveType, $dst_image, $thumbPath );
1276 imagedestroy( $dst_image );
1277 imagedestroy( $src_image );
1282 # Check for zero-sized thumbnails. Those can be generated when
1283 # no disk space is available or some other error occurs
1285 if( file_exists( $thumbPath ) ) {
1286 $thumbstat = stat( $thumbPath );
1287 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1288 wfDebugLog( 'thumbnail',
1289 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1290 $thumbstat['size'], $thumbPath ) );
1291 unlink( $thumbPath );
1294 if ( $retval != 0 ) {
1295 wfDebugLog( 'thumbnail',
1296 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1297 wfHostname(), $retval, trim($err), $cmd ) );
1298 return wfMsg( 'thumbnail_error', $err );
1304 function getLastError() {
1305 return $this->lastError
;
1308 function imageJpegWrapper( $dst_image, $thumbPath ) {
1309 imageinterlace( $dst_image );
1310 imagejpeg( $dst_image, $thumbPath, 95 );
1314 * Get all thumbnail names previously generated for this image
1316 function getThumbnails( $shared = false ) {
1317 if ( Image
::isHashed( $shared ) ) {
1320 $dir = wfImageThumbDir( $this->name
, $shared );
1322 // This generates an error on failure, hence the @
1323 $handle = @opendir
( $dir );
1326 while ( false !== ( $file = readdir($handle) ) ) {
1327 if ( $file{0} != '.' ) {
1331 closedir( $handle );
1341 * Refresh metadata in memcached, but don't touch thumbnails or squid
1343 function purgeMetadataCache() {
1345 $this->loadFromFile();
1346 $this->saveToCache();
1350 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1352 function purgeCache( $archiveFiles = array(), $shared = false ) {
1355 // Refresh metadata cache
1356 $this->purgeMetadataCache();
1358 // Delete thumbnails
1359 $files = $this->getThumbnails( $shared );
1360 $dir = wfImageThumbDir( $this->name
, $shared );
1362 foreach ( $files as $file ) {
1363 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1364 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1365 @unlink
( "$dir/$file" );
1370 if ( $wgUseSquid ) {
1371 $urls[] = $this->getViewURL();
1372 foreach ( $archiveFiles as $file ) {
1373 $urls[] = wfImageArchiveUrl( $file );
1375 wfPurgeSquidServers( $urls );
1380 * Purge the image description page, but don't go after
1381 * pages using the image. Use when modifying file history
1382 * but not the current data.
1384 function purgeDescription() {
1385 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1386 $page->invalidateCache();
1387 $page->purgeSquid();
1391 * Purge metadata and all affected pages when the image is created,
1392 * deleted, or majorly updated. A set of additional URLs may be
1393 * passed to purge, such as specific image files which have changed.
1394 * @param $urlArray array
1396 function purgeEverything( $urlArr=array() ) {
1397 // Delete thumbnails and refresh image metadata cache
1398 $this->purgeCache();
1399 $this->purgeDescription();
1401 // Purge cache of all pages using this image
1402 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1403 $update->doUpdate();
1406 function checkDBSchema(&$db) {
1407 static $checkDone = false;
1408 global $wgCheckDBSchema;
1409 if (!$wgCheckDBSchema ||
$checkDone) {
1412 # img_name must be unique
1413 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1414 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1418 # new fields must exist
1420 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1421 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1422 # something. The only reason I put the above schema check in was because the absence of that particular
1423 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1426 if ( !$db->fieldExists( 'image', 'img_media_type' )
1427 || !$db->fieldExists( 'image', 'img_metadata' )
1428 || !$db->fieldExists( 'image', 'img_width' ) ) {
1430 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1436 * Return the image history of this image, line by line.
1437 * starts with current version, then old versions.
1438 * uses $this->historyLine to check which line to return:
1439 * 0 return line for current version
1440 * 1 query for old versions, return first one
1441 * 2, ... return next old version from above query
1445 function nextHistoryLine() {
1446 $dbr =& wfGetDB( DB_SLAVE
);
1448 $this->checkDBSchema($dbr);
1450 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1451 $this->historyRes
= $dbr->select( 'image',
1455 'img_user','img_user_text',
1459 "'' AS oi_archive_name"
1461 array( 'img_name' => $this->title
->getDBkey() ),
1464 if ( 0 == wfNumRows( $this->historyRes
) ) {
1467 } else if ( $this->historyLine
== 1 ) {
1468 $this->historyRes
= $dbr->select( 'oldimage',
1470 'oi_size AS img_size',
1471 'oi_description AS img_description',
1472 'oi_user AS img_user',
1473 'oi_user_text AS img_user_text',
1474 'oi_timestamp AS img_timestamp',
1475 'oi_width as img_width',
1476 'oi_height as img_height',
1479 array( 'oi_name' => $this->title
->getDBkey() ),
1481 array( 'ORDER BY' => 'oi_timestamp DESC' )
1484 $this->historyLine ++
;
1486 return $dbr->fetchObject( $this->historyRes
);
1490 * Reset the history pointer to the first element of the history
1493 function resetHistory() {
1494 $this->historyLine
= 0;
1498 * Return the full filesystem path to the file. Note that this does
1499 * not mean that a file actually exists under that location.
1501 * This path depends on whether directory hashing is active or not,
1502 * i.e. whether the images are all found in the same directory,
1503 * or in hashed paths like /images/3/3c.
1506 * @param boolean $fromSharedDirectory Return the path to the file
1507 * in a shared repository (see $wgUseSharedRepository and related
1508 * options in DefaultSettings.php) instead of a local one.
1511 function getFullPath( $fromSharedRepository = false ) {
1512 global $wgUploadDirectory, $wgSharedUploadDirectory;
1514 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1517 // $wgSharedUploadDirectory may be false, if thumb.php is used
1519 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1531 public static function isHashed( $shared ) {
1532 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1533 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1537 * Record an image upload in the upload log and the image table
1539 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1540 global $wgUser, $wgUseCopyrightUpload;
1542 $dbw =& wfGetDB( DB_MASTER
);
1544 $this->checkDBSchema($dbw);
1546 // Delete thumbnails and refresh the metadata cache
1547 $this->purgeCache();
1549 // Fail now if the image isn't there
1550 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1551 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1555 if ( $wgUseCopyrightUpload ) {
1556 if ( $license != '' ) {
1557 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1559 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1560 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1562 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1564 if ( $license != '' ) {
1565 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1566 $textdesc = $filedesc .
1567 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1573 $now = $dbw->timestamp();
1576 if (strpos($this->mime
,'/')!==false) {
1577 list($major,$minor)= explode('/',$this->mime
,2);
1580 $major= $this->mime
;
1584 # Test to see if the row exists using INSERT IGNORE
1585 # This avoids race conditions by locking the row until the commit, and also
1586 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1587 $dbw->insert( 'image',
1589 'img_name' => $this->name
,
1590 'img_size'=> $this->size
,
1591 'img_width' => intval( $this->width
),
1592 'img_height' => intval( $this->height
),
1593 'img_bits' => $this->bits
,
1594 'img_media_type' => $this->type
,
1595 'img_major_mime' => $major,
1596 'img_minor_mime' => $minor,
1597 'img_timestamp' => $now,
1598 'img_description' => $desc,
1599 'img_user' => $wgUser->getID(),
1600 'img_user_text' => $wgUser->getName(),
1601 'img_metadata' => $this->metadata
,
1607 if( $dbw->affectedRows() == 0 ) {
1608 # Collision, this is an update of an image
1609 # Insert previous contents into oldimage
1610 $dbw->insertSelect( 'oldimage', 'image',
1612 'oi_name' => 'img_name',
1613 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1614 'oi_size' => 'img_size',
1615 'oi_width' => 'img_width',
1616 'oi_height' => 'img_height',
1617 'oi_bits' => 'img_bits',
1618 'oi_timestamp' => 'img_timestamp',
1619 'oi_description' => 'img_description',
1620 'oi_user' => 'img_user',
1621 'oi_user_text' => 'img_user_text',
1622 ), array( 'img_name' => $this->name
), __METHOD__
1625 # Update the current image row
1626 $dbw->update( 'image',
1628 'img_size' => $this->size
,
1629 'img_width' => intval( $this->width
),
1630 'img_height' => intval( $this->height
),
1631 'img_bits' => $this->bits
,
1632 'img_media_type' => $this->type
,
1633 'img_major_mime' => $major,
1634 'img_minor_mime' => $minor,
1635 'img_timestamp' => $now,
1636 'img_description' => $desc,
1637 'img_user' => $wgUser->getID(),
1638 'img_user_text' => $wgUser->getName(),
1639 'img_metadata' => $this->metadata
,
1640 ), array( /* WHERE */
1641 'img_name' => $this->name
1645 # This is a new image
1646 # Update the image count
1647 $site_stats = $dbw->tableName( 'site_stats' );
1648 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1651 $descTitle = $this->getTitle();
1652 $article = new Article( $descTitle );
1654 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1655 $suppressRC = true; // There's already a log entry, so don't double the RC load
1657 if( $descTitle->exists() ) {
1658 // TODO: insert a null revision into the page history for this update.
1660 $wgUser->addWatch( $descTitle );
1663 # Invalidate the cache for the description page
1664 $descTitle->invalidateCache();
1665 $descTitle->purgeSquid();
1667 // New image; create the description page.
1668 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1672 $log = new LogPage( 'upload' );
1673 $log->addEntry( 'upload', $descTitle, $desc );
1675 # Commit the transaction now, in case something goes wrong later
1676 # The most important thing is that images don't get lost, especially archives
1677 $dbw->immediateCommit();
1679 # Invalidate cache for all pages using this image
1680 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1681 $update->doUpdate();
1687 * Get an array of Title objects which are articles which use this image
1688 * Also adds their IDs to the link cache
1690 * This is mostly copied from Title::getLinksTo()
1692 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1694 function getLinksTo( $options = '' ) {
1695 wfProfileIn( __METHOD__
);
1698 $db =& wfGetDB( DB_MASTER
);
1700 $db =& wfGetDB( DB_SLAVE
);
1702 $linkCache =& LinkCache
::singleton();
1704 extract( $db->tableNames( 'page', 'imagelinks' ) );
1705 $encName = $db->addQuotes( $this->name
);
1706 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1707 $res = $db->query( $sql, __METHOD__
);
1710 if ( $db->numRows( $res ) ) {
1711 while ( $row = $db->fetchObject( $res ) ) {
1712 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1713 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1714 $retVal[] = $titleObj;
1718 $db->freeResult( $res );
1719 wfProfileOut( __METHOD__
);
1724 * Retrive Exif data from the file and prune unrecognized tags
1725 * and/or tags with invalid contents
1730 private function retrieveExifData( $filename ) {
1734 if ( $this->getMimeType() !== "image/jpeg" )
1738 if( $wgShowEXIF && file_exists( $filename ) ) {
1739 $exif = new Exif( $filename );
1740 return $exif->getFilteredData();
1746 function getExifData() {
1748 if ( $this->metadata
=== '0' ||
$this->mime
== 'image/vnd.djvu' )
1751 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1752 $ret = unserialize( $this->metadata
);
1754 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1755 $newver = Exif
::version();
1757 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1758 $this->purgeMetadataCache();
1759 $this->updateExifData( $newver );
1761 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1762 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1763 $format = new FormatExif( $ret );
1765 return $format->getFormattedData();
1768 function updateExifData( $version ) {
1769 if ( $this->getImagePath() === false ) # Not a local image
1772 # Get EXIF data from image
1773 $exif = $this->retrieveExifData( $this->imagePath
);
1774 if ( count( $exif ) ) {
1775 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1776 $this->metadata
= serialize( $exif );
1778 $this->metadata
= '0';
1781 # Update EXIF data in database
1782 $dbw =& wfGetDB( DB_MASTER
);
1784 $this->checkDBSchema($dbw);
1786 $dbw->update( 'image',
1787 array( 'img_metadata' => $this->metadata
),
1788 array( 'img_name' => $this->name
),
1794 * Returns true if the image does not come from the shared
1799 function isLocal() {
1800 return !$this->fromSharedDirectory
;
1804 * Was this image ever deleted from the wiki?
1808 function wasDeleted() {
1809 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1810 return ( $title->isDeleted() > 0 );
1814 * Delete all versions of the image.
1816 * Moves the files into an archive directory (or deletes them)
1817 * and removes the database rows.
1819 * Cache purging is done; logging is caller's responsibility.
1822 * @return true on success, false on some kind of failure
1824 function delete( $reason ) {
1825 $transaction = new FSTransaction();
1826 $urlArr = array( $this->getURL() );
1828 if( !FileStore
::lock() ) {
1829 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1834 $dbw = wfGetDB( DB_MASTER
);
1837 // Delete old versions
1838 $result = $dbw->select( 'oldimage',
1839 array( 'oi_archive_name' ),
1840 array( 'oi_name' => $this->name
) );
1842 while( $row = $dbw->fetchObject( $result ) ) {
1843 $oldName = $row->oi_archive_name
;
1845 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1847 // We'll need to purge this URL from caches...
1848 $urlArr[] = wfImageArchiveUrl( $oldName );
1850 $dbw->freeResult( $result );
1852 // And the current version...
1853 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1855 $dbw->immediateCommit();
1856 } catch( MWException
$e ) {
1857 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1858 $transaction->rollback();
1859 FileStore
::unlock();
1863 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1864 $transaction->commit();
1865 FileStore
::unlock();
1868 // Update site_stats
1869 $site_stats = $dbw->tableName( 'site_stats' );
1870 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1872 $this->purgeEverything( $urlArr );
1879 * Delete an old version of the image.
1881 * Moves the file into an archive directory (or deletes it)
1882 * and removes the database row.
1884 * Cache purging is done; logging is caller's responsibility.
1887 * @throws MWException or FSException on database or filestore failure
1888 * @return true on success, false on some kind of failure
1890 function deleteOld( $archiveName, $reason ) {
1891 $transaction = new FSTransaction();
1894 if( !FileStore
::lock() ) {
1895 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1899 $transaction = new FSTransaction();
1901 $dbw = wfGetDB( DB_MASTER
);
1903 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1904 $dbw->immediateCommit();
1905 } catch( MWException
$e ) {
1906 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1907 $transaction->rollback();
1908 FileStore
::unlock();
1912 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1913 $transaction->commit();
1914 FileStore
::unlock();
1916 $this->purgeDescription();
1920 if ( $wgUseSquid ) {
1922 wfImageArchiveUrl( $archiveName ),
1924 wfPurgeSquidServers( $urlArr );
1930 * Delete the current version of a file.
1931 * May throw a database error.
1932 * @return true on success, false on failure
1934 private function prepareDeleteCurrent( $reason ) {
1935 return $this->prepareDeleteVersion(
1936 $this->getFullPath(),
1940 'fa_name' => 'img_name',
1941 'fa_archive_name' => 'NULL',
1942 'fa_size' => 'img_size',
1943 'fa_width' => 'img_width',
1944 'fa_height' => 'img_height',
1945 'fa_metadata' => 'img_metadata',
1946 'fa_bits' => 'img_bits',
1947 'fa_media_type' => 'img_media_type',
1948 'fa_major_mime' => 'img_major_mime',
1949 'fa_minor_mime' => 'img_minor_mime',
1950 'fa_description' => 'img_description',
1951 'fa_user' => 'img_user',
1952 'fa_user_text' => 'img_user_text',
1953 'fa_timestamp' => 'img_timestamp' ),
1954 array( 'img_name' => $this->name
),
1959 * Delete a given older version of a file.
1960 * May throw a database error.
1961 * @return true on success, false on failure
1963 private function prepareDeleteOld( $archiveName, $reason ) {
1964 $oldpath = wfImageArchiveDir( $this->name
) .
1965 DIRECTORY_SEPARATOR
. $archiveName;
1966 return $this->prepareDeleteVersion(
1971 'fa_name' => 'oi_name',
1972 'fa_archive_name' => 'oi_archive_name',
1973 'fa_size' => 'oi_size',
1974 'fa_width' => 'oi_width',
1975 'fa_height' => 'oi_height',
1976 'fa_metadata' => 'NULL',
1977 'fa_bits' => 'oi_bits',
1978 'fa_media_type' => 'NULL',
1979 'fa_major_mime' => 'NULL',
1980 'fa_minor_mime' => 'NULL',
1981 'fa_description' => 'oi_description',
1982 'fa_user' => 'oi_user',
1983 'fa_user_text' => 'oi_user_text',
1984 'fa_timestamp' => 'oi_timestamp' ),
1986 'oi_name' => $this->name
,
1987 'oi_archive_name' => $archiveName ),
1992 * Do the dirty work of backing up an image row and its file
1993 * (if $wgSaveDeletedFiles is on) and removing the originals.
1995 * Must be run while the file store is locked and a database
1996 * transaction is open to avoid race conditions.
1998 * @return FSTransaction
2000 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
2001 global $wgUser, $wgSaveDeletedFiles;
2003 // Dupe the file into the file store
2004 if( file_exists( $path ) ) {
2005 if( $wgSaveDeletedFiles ) {
2008 $store = FileStore
::get( $group );
2009 $key = FileStore
::calculateKey( $path, $this->extension
);
2010 $transaction = $store->insert( $key, $path,
2011 FileStore
::DELETE_ORIGINAL
);
2015 $transaction = FileStore
::deleteFile( $path );
2018 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
2021 $transaction = new FSTransaction(); // empty
2024 if( $transaction === false ) {
2026 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
2027 throw new MWException( "Could not archive and delete file $path" );
2031 $dbw = wfGetDB( DB_MASTER
);
2032 $storageMap = array(
2033 'fa_storage_group' => $dbw->addQuotes( $group ),
2034 'fa_storage_key' => $dbw->addQuotes( $key ),
2036 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2037 'fa_deleted_timestamp' => $dbw->timestamp(),
2038 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2039 $allFields = array_merge( $storageMap, $fieldMap );
2042 if( $wgSaveDeletedFiles ) {
2043 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2045 $dbw->delete( $table, $where, $fname );
2046 } catch( DBQueryError
$e ) {
2047 // Something went horribly wrong!
2048 // Leave the file as it was...
2049 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
2050 $transaction->rollback();
2054 return $transaction;
2058 * Restore all or specified deleted revisions to the given file.
2059 * Permissions and logging are left to the caller.
2061 * May throw database exceptions on error.
2063 * @param $versions set of record ids of deleted items to restore,
2064 * or empty to restore all revisions.
2065 * @return the number of file revisions restored if successful,
2066 * or false on failure
2068 function restore( $versions=array() ) {
2069 if( !FileStore
::lock() ) {
2070 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
2074 $transaction = new FSTransaction();
2076 $dbw = wfGetDB( DB_MASTER
);
2079 // Re-confirm whether this image presently exists;
2080 // if no we'll need to create an image record for the
2081 // first item we restore.
2082 $exists = $dbw->selectField( 'image', '1',
2083 array( 'img_name' => $this->name
),
2086 // Fetch all or selected archived revisions for the file,
2087 // sorted from the most recent to the oldest.
2088 $conditions = array( 'fa_name' => $this->name
);
2090 $conditions['fa_id'] = $versions;
2093 $result = $dbw->select( 'filearchive', '*',
2096 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2098 if( $dbw->numRows( $result ) < count( $versions ) ) {
2099 // There's some kind of conflict or confusion;
2100 // we can't restore everything we were asked to.
2101 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2103 FileStore
::unlock();
2107 if( $dbw->numRows( $result ) == 0 ) {
2109 wfDebug( __METHOD__
.": nothing to do\n" );
2111 FileStore
::unlock();
2116 while( $row = $dbw->fetchObject( $result ) ) {
2118 $store = FileStore
::get( $row->fa_storage_group
);
2120 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2124 if( $revisions == 1 && !$exists ) {
2125 $destDir = wfImageDir( $row->fa_name
);
2126 if ( !is_dir( $destDir ) ) {
2127 wfMkdirParents( $destDir );
2129 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2131 // We may have to fill in data if this was originally
2132 // an archived file revision.
2133 if( is_null( $row->fa_metadata
) ) {
2134 $tempFile = $store->filePath( $row->fa_storage_key
);
2135 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2137 $magic = wfGetMimeMagic();
2138 $mime = $magic->guessMimeType( $tempFile, true );
2139 $media_type = $magic->getMediaType( $tempFile, $mime );
2140 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2142 $metadata = $row->fa_metadata
;
2143 $major_mime = $row->fa_major_mime
;
2144 $minor_mime = $row->fa_minor_mime
;
2145 $media_type = $row->fa_media_type
;
2150 'img_name' => $row->fa_name
,
2151 'img_size' => $row->fa_size
,
2152 'img_width' => $row->fa_width
,
2153 'img_height' => $row->fa_height
,
2154 'img_metadata' => $metadata,
2155 'img_bits' => $row->fa_bits
,
2156 'img_media_type' => $media_type,
2157 'img_major_mime' => $major_mime,
2158 'img_minor_mime' => $minor_mime,
2159 'img_description' => $row->fa_description
,
2160 'img_user' => $row->fa_user
,
2161 'img_user_text' => $row->fa_user_text
,
2162 'img_timestamp' => $row->fa_timestamp
);
2164 $archiveName = $row->fa_archive_name
;
2165 if( $archiveName == '' ) {
2166 // This was originally a current version; we
2167 // have to devise a new archive name for it.
2168 // Format is <timestamp of archiving>!<name>
2170 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2171 '!' . $row->fa_name
;
2173 $destDir = wfImageArchiveDir( $row->fa_name
);
2174 if ( !is_dir( $destDir ) ) {
2175 wfMkdirParents( $destDir );
2177 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2179 $table = 'oldimage';
2181 'oi_name' => $row->fa_name
,
2182 'oi_archive_name' => $archiveName,
2183 'oi_size' => $row->fa_size
,
2184 'oi_width' => $row->fa_width
,
2185 'oi_height' => $row->fa_height
,
2186 'oi_bits' => $row->fa_bits
,
2187 'oi_description' => $row->fa_description
,
2188 'oi_user' => $row->fa_user
,
2189 'oi_user_text' => $row->fa_user_text
,
2190 'oi_timestamp' => $row->fa_timestamp
);
2193 $dbw->insert( $table, $fields, __METHOD__
);
2194 /// @fixme this delete is not totally safe, potentially
2195 $dbw->delete( 'filearchive',
2196 array( 'fa_id' => $row->fa_id
),
2199 // Check if any other stored revisions use this file;
2200 // if so, we shouldn't remove the file from the deletion
2201 // archives so they will still work.
2202 $useCount = $dbw->selectField( 'filearchive',
2205 'fa_storage_group' => $row->fa_storage_group
,
2206 'fa_storage_key' => $row->fa_storage_key
),
2208 if( $useCount == 0 ) {
2209 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2210 $flags = FileStore
::DELETE_ORIGINAL
;
2215 $transaction->add( $store->export( $row->fa_storage_key
,
2216 $destPath, $flags ) );
2219 $dbw->immediateCommit();
2220 } catch( MWException
$e ) {
2221 wfDebug( __METHOD__
." caught error, aborting\n" );
2222 $transaction->rollback();
2226 $transaction->commit();
2227 FileStore
::unlock();
2229 if( $revisions > 0 ) {
2231 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2233 // Update site_stats
2234 $site_stats = $dbw->tableName( 'site_stats' );
2235 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2237 $this->purgeEverything();
2239 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2240 $this->purgeDescription();
2248 * Select a page from a multipage document. Determines the page used for
2249 * rendering thumbnails.
2251 * @param $page Integer: page number, starting with 1
2253 function selectPage( $page ) {
2254 wfDebug( __METHOD__
." selecting page $page \n" );
2255 $this->page
= $page;
2256 if ( ! $this->dataLoaded
) {
2259 if ( ! isset( $this->multiPageXML
) ) {
2260 $this->initializeMultiPageXML();
2262 $o = $this->multiPageXML
->BODY
[0]->OBJECT[$page-1];
2263 $this->height
= intval( $o['height'] );
2264 $this->width
= intval( $o['width'] );
2267 function initializeMultiPageXML() {
2269 # Check for files uploaded prior to DJVU support activation
2270 # They have a '0' in their metadata field.
2272 if ( $this->metadata
== '0' ) {
2273 $deja = new DjVuImage( $this->imagePath
);
2274 $this->metadata
= $deja->retrieveMetaData();
2275 $this->purgeMetadataCache();
2277 # Update metadata in the database
2278 $dbw =& wfGetDB( DB_MASTER
);
2279 $dbw->update( 'image',
2280 array( 'img_metadata' => $this->metadata
),
2281 array( 'img_name' => $this->name
),
2285 $this->multiPageXML
= new SimpleXMLElement( $this->metadata
);
2289 * Returns 'true' if this image is a multipage document, e.g. a DJVU
2294 function isMultipage() {
2295 return ( $this->mime
== 'image/vnd.djvu' );
2299 * Returns the number of pages of a multipage document, or NULL for
2300 * documents which aren't multipage documents
2302 function pageCount() {
2303 if ( ! $this->isMultipage() ) {
2306 if ( ! isset( $this->multiPageXML
) ) {
2307 $this->initializeMultiPageXML();
2309 return count( $this->multiPageXML
->xpath( '//OBJECT' ) );
2315 * Wrapper class for thumbnail images
2316 * @package MediaWiki
2318 class ThumbnailImage
{
2320 * @param string $path Filesystem path to the thumb
2321 * @param string $url URL path to the thumb
2324 function ThumbnailImage( $url, $width, $height, $path = false ) {
2326 $this->width
= round( $width );
2327 $this->height
= round( $height );
2328 # These should be integers when they get here.
2329 # If not, there's a bug somewhere. But let's at
2330 # least produce valid HTML code regardless.
2331 $this->path
= $path;
2335 * @return string The thumbnail URL
2342 * Return HTML <img ... /> tag for the thumbnail, will include
2343 * width and height attributes and a blank alt text (as required).
2345 * You can set or override additional attributes by passing an
2346 * associative array of name => data pairs. The data will be escaped
2347 * for HTML output, so should be in plaintext.
2349 * @param array $attribs
2353 function toHtml( $attribs = array() ) {
2354 $attribs['src'] = $this->url
;
2355 $attribs['width'] = $this->width
;
2356 $attribs['height'] = $this->height
;
2357 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2360 foreach( $attribs as $name => $data ) {
2361 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';