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 && 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() {
203 global $wgMemc, $wgUseSharedUploads;
205 $keys = $this->getCacheKeys();
206 // We can't cache negative metadata for non-existent files,
207 // because if the file later appears in commons, the local
208 // keys won't be purged.
209 if ( $this->fileExists ||
!$wgUseSharedUploads ) {
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() ) ;
380 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
381 $this->dataLoaded
= true;
382 wfProfileOut( __METHOD__
);
386 * Load image metadata from a DB result row
388 function loadFromRow( &$row ) {
389 $this->size
= $row->img_size
;
390 $this->width
= $row->img_width
;
391 $this->height
= $row->img_height
;
392 $this->bits
= $row->img_bits
;
393 $this->type
= $row->img_media_type
;
395 $major= $row->img_major_mime
;
396 $minor= $row->img_minor_mime
;
398 if (!$major) $this->mime
= "unknown/unknown";
400 if (!$minor) $minor= "unknown";
401 $this->mime
= $major.'/'.$minor;
404 $this->metadata
= $row->img_metadata
;
405 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
407 $this->dataLoaded
= true;
411 * Load image metadata from cache or DB, unless already loaded
414 global $wgSharedUploadDBname, $wgUseSharedUploads;
415 if ( !$this->dataLoaded
) {
416 if ( !$this->loadFromCache() ) {
418 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
419 $this->loadFromFile();
420 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
421 // We can do negative caching for local images, because the cache
422 // will be purged on upload. But we can't do it when shared images
423 // are enabled, since updates to that won't purge foreign caches.
424 $this->saveToCache();
427 $this->dataLoaded
= true;
432 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
433 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
435 function upgradeRow() {
436 global $wgDBname, $wgSharedUploadDBname;
437 wfProfileIn( __METHOD__
);
439 $this->loadFromFile();
441 if ( $this->fromSharedDirectory
) {
442 if ( !$wgSharedUploadDBname ) {
443 wfProfileOut( __METHOD__
);
447 // Write to the other DB using selectDB, not database selectors
448 // This avoids breaking replication in MySQL
449 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
450 $dbw->selectDB( $wgSharedUploadDBname );
452 $dbw =& wfGetDB( DB_MASTER
);
455 $this->checkDBSchema($dbw);
457 list( $major, $minor ) = self
::splitMime( $this->mime
);
459 wfDebug(__METHOD__
.': upgrading '.$this->name
." to 1.5 schema\n");
461 $dbw->update( 'image',
463 'img_width' => $this->width
,
464 'img_height' => $this->height
,
465 'img_bits' => $this->bits
,
466 'img_media_type' => $this->type
,
467 'img_major_mime' => $major,
468 'img_minor_mime' => $minor,
469 'img_metadata' => $this->metadata
,
470 ), array( 'img_name' => $this->name
), __METHOD__
472 if ( $this->fromSharedDirectory
) {
473 $dbw->selectDB( $wgDBname );
475 wfProfileOut( __METHOD__
);
479 * Split an internet media type into its two components; if not
480 * a two-part name, set the minor type to 'unknown'.
482 * @param $mime "text/html" etc
483 * @return array ("text", "html") etc
485 static function splitMime( $mime ) {
486 if( strpos( $mime, '/' ) !== false ) {
487 return explode( '/', $mime, 2 );
489 return array( $mime, 'unknown' );
494 * Return the name of this image
502 * Return the associated title object
505 function getTitle() {
510 * Return the URL of the image file
516 if($this->fileExists
) {
517 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
525 function getViewURL() {
526 if( $this->mustRender()) {
527 if( $this->canRender() ) {
528 return $this->createThumb( $this->getWidth() );
531 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
532 return $this->getURL(); #hm... return NULL?
535 return $this->getURL();
540 * Return the image path of the image in the
541 * local file system as an absolute path
544 function getImagePath() {
546 return $this->imagePath
;
550 * Return the width of the image
552 * Returns -1 if the file specified is not a known image type
555 function getWidth() {
561 * Return the height of the image
563 * Returns -1 if the file specified is not a known image type
566 function getHeight() {
568 return $this->height
;
572 * Return the size of the image file, in bytes
581 * Returns the mime type of the file.
583 function getMimeType() {
589 * Return the type of the media in the file.
590 * Use the value returned by this function with the MEDIATYPE_xxx constants.
592 function getMediaType() {
598 * Checks if the file can be presented to the browser as a bitmap.
600 * Currently, this checks if the file is an image format
601 * that can be converted to a format
602 * supported by all browsers (namely GIF, PNG and JPEG),
603 * or if it is an SVG image and SVG conversion is enabled.
605 * @todo remember the result of this check.
607 function canRender() {
608 global $wgUseImageMagick;
610 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
612 $mime= $this->getMimeType();
614 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
616 #if it's SVG, check if there's a converter enabled
617 if ($mime === 'image/svg') {
618 global $wgSVGConverters, $wgSVGConverter;
620 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
621 wfDebug( "Image::canRender: SVG is ready!\n" );
624 wfDebug( "Image::canRender: SVG renderer missing\n" );
628 #image formats available on ALL browsers
629 if ( $mime === 'image/gif'
630 ||
$mime === 'image/png'
631 ||
$mime === 'image/jpeg' ) return true;
633 #image formats that can be converted to the above formats
634 if ($wgUseImageMagick) {
635 #convertable by ImageMagick (there are more...)
636 if ( $mime === 'image/vnd.wap.wbmp'
637 ||
$mime === 'image/x-xbitmap'
638 ||
$mime === 'image/x-xpixmap'
639 #|| $mime === 'image/x-icon' #file may be split into multiple parts
640 ||
$mime === 'image/x-portable-anymap'
641 ||
$mime === 'image/x-portable-bitmap'
642 ||
$mime === 'image/x-portable-graymap'
643 ||
$mime === 'image/x-portable-pixmap'
644 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
645 ||
$mime === 'image/x-rgb'
646 ||
$mime === 'image/x-bmp'
647 ||
$mime === 'image/tiff' ) return true;
650 #convertable by the PHP GD image lib
651 if ( $mime === 'image/vnd.wap.wbmp'
652 ||
$mime === 'image/x-xbitmap' ) return true;
660 * Return true if the file is of a type that can't be directly
661 * rendered by typical browsers and needs to be re-rasterized.
663 * This returns true for everything but the bitmap types
664 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
665 * also return true for any non-image formats.
669 function mustRender() {
670 $mime= $this->getMimeType();
672 if ( $mime === "image/gif"
673 ||
$mime === "image/png"
674 ||
$mime === "image/jpeg" ) return false;
680 * Determines if this media file may be shown inline on a page.
682 * This is currently synonymous to canRender(), but this could be
683 * extended to also allow inline display of other media,
684 * like flash animations or videos. If you do so, please keep in mind that
685 * that could be a security risk.
687 function allowInlineDisplay() {
688 return $this->canRender();
692 * Determines if this media file is in a format that is unlikely to
693 * contain viruses or malicious content. It uses the global
694 * $wgTrustedMediaFormats list to determine if the file is safe.
696 * This is used to show a warning on the description page of non-safe files.
697 * It may also be used to disallow direct [[media:...]] links to such files.
699 * Note that this function will always return true if allowInlineDisplay()
700 * or isTrustedFile() is true for this file.
702 function isSafeFile() {
703 if ($this->allowInlineDisplay()) return true;
704 if ($this->isTrustedFile()) return true;
706 global $wgTrustedMediaFormats;
708 $type= $this->getMediaType();
709 $mime= $this->getMimeType();
710 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
712 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
713 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
715 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
716 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
721 /** Returns true if the file is flagged as trusted. Files flagged that way
722 * can be linked to directly, even if that is not allowed for this type of
725 * This is a dummy function right now and always returns false. It could be
726 * implemented to extract a flag from the database. The trusted flag could be
727 * set on upload, if the user has sufficient privileges, to bypass script-
728 * and html-filters. It may even be coupled with cryptographics signatures
731 function isTrustedFile() {
732 #this could be implemented to check a flag in the databas,
733 #look for signatures, etc
738 * Return the escapeLocalURL of this image
741 function getEscapeLocalURL() {
743 return $this->title
->escapeLocalURL();
747 * Return the escapeFullURL of this image
750 function getEscapeFullURL() {
752 return $this->title
->escapeFullURL();
756 * Return the URL of an image, provided its name.
758 * @param string $name Name of the image, without the leading "Image:"
759 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
760 * @return string URL of $name image
764 function imageUrl( $name, $fromSharedDirectory = false ) {
765 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
766 if($fromSharedDirectory) {
768 $path = $wgSharedUploadPath;
770 $base = $wgUploadBaseUrl;
771 $path = $wgUploadPath;
773 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
774 return wfUrlencode( $url );
778 * Returns true if the image file exists on disk.
779 * @return boolean Whether image file exist on disk.
784 return $this->fileExists
;
791 function thumbUrl( $width, $subdir='thumb') {
792 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
793 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
795 // Generate thumb.php URL if possible
799 if ( $this->fromSharedDirectory
) {
800 if ( $wgSharedThumbnailScriptPath ) {
801 $script = $wgSharedThumbnailScriptPath;
804 if ( $wgThumbnailScriptPath ) {
805 $script = $wgThumbnailScriptPath;
809 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
810 if( $this->mustRender() ) {
814 $name = $this->thumbName( $width );
815 if($this->fromSharedDirectory
) {
817 $path = $wgSharedUploadPath;
819 $base = $wgUploadBaseUrl;
820 $path = $wgUploadPath;
822 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
823 $url = "{$base}{$path}/{$subdir}" .
824 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
825 . $this->name
.'/'.$name;
826 $url = wfUrlencode( $url );
828 $url = "{$base}{$path}/{$subdir}/{$name}";
831 return array( $script !== false, $url );
835 * Return the file name of a thumbnail of the specified width
837 * @param integer $width Width of the thumbnail image
838 * @param boolean $shared Does the thumbnail come from the shared repository?
841 function thumbName( $width ) {
842 $thumb = $width."px-".$this->name
;
844 if( $this->mustRender() ) {
845 if( $this->canRender() ) {
846 # Rasterize to PNG (for SVG vector images, etc)
850 #should we use iconThumb here to get a symbolic thumbnail?
851 #or should we fail with an internal error?
852 return NULL; //can't make bitmap
859 * Create a thumbnail of the image having the specified width/height.
860 * The thumbnail will not be created if the width is larger than the
861 * image's width. Let the browser do the scaling in this case.
862 * The thumbnail is stored on disk and is only computed if the thumbnail
863 * file does not exist OR if it is older than the image.
866 * Keeps aspect ratio of original image. If both width and height are
867 * specified, the generated image will be no bigger than width x height,
868 * and will also have correct aspect ratio.
870 * @param integer $width maximum width of the generated thumbnail
871 * @param integer $height maximum height of the image (optional)
874 function createThumb( $width, $height=-1 ) {
875 $thumb = $this->getThumbnail( $width, $height );
876 if( is_null( $thumb ) ) return '';
877 return $thumb->getUrl();
881 * As createThumb, but returns a ThumbnailImage object. This can
882 * provide access to the actual file, the real size of the thumb,
883 * and can produce a convenient <img> tag for you.
885 * For non-image formats, this may return a filetype-specific icon.
887 * @param integer $width maximum width of the generated thumbnail
888 * @param integer $height maximum height of the image (optional)
889 * @param boolean $render True to render the thumbnail if it doesn't exist,
890 * false to just return the URL
892 * @return ThumbnailImage or null on failure
895 function getThumbnail( $width, $height=-1, $render = true ) {
896 wfProfileIn( __METHOD__
);
897 if ($this->canRender()) {
900 if ( $width > $this->width
* $height / $this->height
) {
901 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
905 $thumb = $this->renderThumb( $width );
907 // Don't render, just return the URL
908 if ( $this->validateThumbParams( $width, $height ) ) {
909 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
910 $url = $this->getURL();
912 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
914 $thumb = new ThumbnailImage( $url, $width, $height );
920 // not a bitmap or renderable image, don't try.
921 $thumb = $this->iconThumb();
923 wfProfileOut( __METHOD__
);
928 * @return ThumbnailImage
930 function iconThumb() {
931 global $wgStylePath, $wgStyleDirectory;
933 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
934 foreach( $try as $icon ) {
935 $path = '/common/images/icons/' . $icon;
936 $filepath = $wgStyleDirectory . $path;
937 if( file_exists( $filepath ) ) {
938 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
945 * Validate thumbnail parameters and fill in the correct height
947 * @param integer &$width Specified width (input/output)
948 * @param integer &$height Height (output only)
949 * @return false to indicate that an error should be returned to the user.
951 function validateThumbParams( &$width, &$height ) {
952 global $wgSVGMaxSize, $wgMaxImageArea;
956 if ( ! $this->exists() )
958 # If there is no image, there will be no thumbnail
962 $width = intval( $width );
964 # Sanity check $width
965 if( $width <= 0 ||
$this->width
<= 0) {
970 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
971 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
972 # an exception for it.
973 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
974 $this->getMimeType() !== 'image/jpeg' &&
975 $this->width
* $this->height
> $wgMaxImageArea )
980 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
981 if ( $this->mustRender() ) {
982 $width = min( $width, $wgSVGMaxSize );
983 } elseif ( $width > $this->width
- 1 ) {
984 $width = $this->width
;
985 $height = $this->height
;
989 $height = round( $this->height
* $width / $this->width
);
994 * Create a thumbnail of the image having the specified width.
995 * The thumbnail will not be created if the width is larger than the
996 * image's width. Let the browser do the scaling in this case.
997 * The thumbnail is stored on disk and is only computed if the thumbnail
998 * file does not exist OR if it is older than the image.
999 * Returns an object which can return the pathname, URL, and physical
1000 * pixel size of the thumbnail -- or null on failure.
1002 * @return ThumbnailImage or null on failure
1005 function renderThumb( $width, $useScript = true ) {
1006 global $wgUseSquid, $wgThumbnailEpoch;
1008 wfProfileIn( __METHOD__
);
1012 if ( !$this->validateThumbParams( $width, $height ) ) {
1014 wfProfileOut( __METHOD__
);
1018 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1019 # validateThumbParams (or the user) wants us to return the unscaled image
1020 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1021 wfProfileOut( __METHOD__
);
1025 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1026 if ( $isScriptUrl && $useScript ) {
1027 // Use thumb.php to render the image
1028 $thumb = new ThumbnailImage( $url, $width, $height );
1029 wfProfileOut( __METHOD__
);
1033 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
1034 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
1035 $thumbPath = $thumbDir.'/'.$thumbName;
1037 if ( is_dir( $thumbPath ) ) {
1038 // Directory where file should be
1039 // This happened occasionally due to broken migration code in 1.5
1040 // Rename to broken-*
1041 global $wgUploadDirectory;
1042 for ( $i = 0; $i < 100 ; $i++
) {
1043 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1044 if ( !file_exists( $broken ) ) {
1045 rename( $thumbPath, $broken );
1049 // Code below will ask if it exists, and the answer is now no
1054 if ( !file_exists( $thumbPath ) ||
1055 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1057 // Create the directory if it doesn't exist
1058 if ( is_file( $thumbDir ) ) {
1059 // File where thumb directory should be, destroy if possible
1060 @unlink
( $thumbDir );
1062 wfMkdirParents( $thumbDir );
1064 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1068 // Migration from old directory structure
1069 if ( is_file( $oldThumbPath ) ) {
1070 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1071 if ( file_exists( $thumbPath ) ) {
1072 if ( !is_dir( $thumbPath ) ) {
1073 // Old image in the way of rename
1074 unlink( $thumbPath );
1076 // This should have been dealt with already
1077 throw new MWException( "Directory where image should be: $thumbPath" );
1080 // Rename the old image into the new location
1081 rename( $oldThumbPath, $thumbPath );
1084 unlink( $oldThumbPath );
1088 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1089 if ( $this->lastError
=== true ) {
1091 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1092 // Log the error but output anyway.
1093 // With luck it's a transitory error...
1098 # This has to be done after the image is updated and present for all machines on NFS,
1099 # or else the old version might be stored into the squid again
1100 if ( $wgUseSquid ) {
1101 $urlArr = array( $url );
1102 wfPurgeSquidServers($urlArr);
1108 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1112 wfProfileOut( __METHOD__
);
1114 } // END OF function renderThumb
1117 * Really render a thumbnail
1118 * Call this only for images for which canRender() returns true.
1120 * @param string $thumbPath Path to thumbnail
1121 * @param int $width Desired width in pixels
1122 * @param int $height Desired height in pixels
1123 * @return bool True on error, false or error string on failure.
1126 function reallyRenderThumb( $thumbPath, $width, $height ) {
1127 global $wgSVGConverters, $wgSVGConverter;
1128 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1129 global $wgCustomConvertCommand;
1137 if( $this->mime
=== "image/svg" ) {
1138 #Right now we have only SVG
1140 global $wgSVGConverters, $wgSVGConverter;
1141 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1142 global $wgSVGConverterPath;
1144 array( '$path/', '$width', '$height', '$input', '$output' ),
1145 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1148 wfEscapeShellArg( $this->imagePath
),
1149 wfEscapeShellArg( $thumbPath ) ),
1150 $wgSVGConverters[$wgSVGConverter] );
1151 wfProfileIn( 'rsvg' );
1152 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1153 $err = wfShellExec( $cmd, $retval );
1154 wfProfileOut( 'rsvg' );
1156 } elseif ( $wgUseImageMagick ) {
1159 if ( $this->mime
== 'image/jpeg' ) {
1160 $quality = "-quality 80"; // 80%
1161 } elseif ( $this->mime
== 'image/png' ) {
1162 $quality = "-quality 95"; // zlib 9, adaptive filtering
1164 $quality = ''; // default
1167 # Specify white background color, will be used for transparent images
1168 # in Internet Explorer/Windows instead of default black.
1170 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1171 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1172 # the wrong size in the second case.
1174 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1175 " {$quality} -background white -size {$width} ".
1176 wfEscapeShellArg($this->imagePath
) .
1177 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1179 // For the -resize option a "!" is needed to force exact size,
1180 // or ImageMagick may decide your ratio is wrong and slice off
1182 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1184 wfEscapeShellArg($thumbPath) . " 2>&1";
1185 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1186 wfProfileIn( 'convert' );
1187 $err = wfShellExec( $cmd, $retval );
1188 wfProfileOut( 'convert' );
1189 } elseif( $wgCustomConvertCommand ) {
1190 # Use a custom convert command
1191 # Variables: %s %d %w %h
1192 $src = wfEscapeShellArg( $this->imagePath
);
1193 $dst = wfEscapeShellArg( $thumbPath );
1194 $cmd = $wgCustomConvertCommand;
1195 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1196 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1197 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1198 wfProfileIn( 'convert' );
1199 $err = wfShellExec( $cmd, $retval );
1200 wfProfileOut( 'convert' );
1202 # Use PHP's builtin GD library functions.
1204 # First find out what kind of file this is, and select the correct
1205 # input routine for this.
1208 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1209 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1210 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1211 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1212 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1214 if( !isset( $typemap[$this->mime
] ) ) {
1215 $err = 'Image type not supported';
1216 wfDebug( "$err\n" );
1219 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1221 if( !function_exists( $loader ) ) {
1222 $err = "Incomplete GD library configuration: missing function $loader";
1223 wfDebug( "$err\n" );
1226 if( $colorStyle == 'palette' ) {
1228 } elseif( $colorStyle == 'truecolor' ) {
1230 } elseif( $colorStyle == 'bits' ) {
1231 $truecolor = ( $this->bits
> 8 );
1234 $src_image = call_user_func( $loader, $this->imagePath
);
1236 $dst_image = imagecreatetruecolor( $width, $height );
1238 $dst_image = imagecreate( $width, $height );
1240 imagecopyresampled( $dst_image, $src_image,
1242 $width, $height, $this->width
, $this->height
);
1243 call_user_func( $saveType, $dst_image, $thumbPath );
1244 imagedestroy( $dst_image );
1245 imagedestroy( $src_image );
1249 # Check for zero-sized thumbnails. Those can be generated when
1250 # no disk space is available or some other error occurs
1252 if( file_exists( $thumbPath ) ) {
1253 $thumbstat = stat( $thumbPath );
1254 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1255 wfDebugLog( 'thumbnail',
1256 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1257 $thumbstat['size'], $thumbPath ) );
1258 unlink( $thumbPath );
1261 if ( $retval != 0 ) {
1262 wfDebugLog( 'thumbnail',
1263 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1264 wfHostname(), $retval, trim($err), $cmd ) );
1265 return wfMsg( 'thumbnail_error', $err );
1271 function getLastError() {
1272 return $this->lastError
;
1275 function imageJpegWrapper( $dst_image, $thumbPath ) {
1276 imageinterlace( $dst_image );
1277 imagejpeg( $dst_image, $thumbPath, 95 );
1281 * Get all thumbnail names previously generated for this image
1283 function getThumbnails( $shared = false ) {
1284 if ( Image
::isHashed( $shared ) ) {
1287 $dir = wfImageThumbDir( $this->name
, $shared );
1289 // This generates an error on failure, hence the @
1290 $handle = @opendir
( $dir );
1293 while ( false !== ( $file = readdir($handle) ) ) {
1294 if ( $file{0} != '.' ) {
1298 closedir( $handle );
1308 * Refresh metadata in memcached, but don't touch thumbnails or squid
1310 function purgeMetadataCache() {
1312 $this->loadFromFile();
1313 $this->saveToCache();
1317 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1319 function purgeCache( $archiveFiles = array(), $shared = false ) {
1322 // Refresh metadata cache
1323 $this->purgeMetadataCache();
1325 // Delete thumbnails
1326 $files = $this->getThumbnails( $shared );
1327 $dir = wfImageThumbDir( $this->name
, $shared );
1329 foreach ( $files as $file ) {
1330 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1331 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1332 @unlink
( "$dir/$file" );
1337 if ( $wgUseSquid ) {
1338 $urls[] = $this->getViewURL();
1339 foreach ( $archiveFiles as $file ) {
1340 $urls[] = wfImageArchiveUrl( $file );
1342 wfPurgeSquidServers( $urls );
1347 * Purge the image description page, but don't go after
1348 * pages using the image. Use when modifying file history
1349 * but not the current data.
1351 function purgeDescription() {
1352 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1353 $page->invalidateCache();
1354 $page->purgeSquid();
1358 * Purge metadata and all affected pages when the image is created,
1359 * deleted, or majorly updated. A set of additional URLs may be
1360 * passed to purge, such as specific image files which have changed.
1361 * @param $urlArray array
1363 function purgeEverything( $urlArr=array() ) {
1364 // Delete thumbnails and refresh image metadata cache
1365 $this->purgeCache();
1366 $this->purgeDescription();
1368 // Purge cache of all pages using this image
1369 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1370 $update->doUpdate();
1373 function checkDBSchema(&$db) {
1374 static $checkDone = false;
1375 global $wgCheckDBSchema;
1376 if (!$wgCheckDBSchema ||
$checkDone) {
1379 # img_name must be unique
1380 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1381 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1385 # new fields must exist
1387 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1388 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1389 # something. The only reason I put the above schema check in was because the absence of that particular
1390 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1393 if ( !$db->fieldExists( 'image', 'img_media_type' )
1394 || !$db->fieldExists( 'image', 'img_metadata' )
1395 || !$db->fieldExists( 'image', 'img_width' ) ) {
1397 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1403 * Return the image history of this image, line by line.
1404 * starts with current version, then old versions.
1405 * uses $this->historyLine to check which line to return:
1406 * 0 return line for current version
1407 * 1 query for old versions, return first one
1408 * 2, ... return next old version from above query
1412 function nextHistoryLine() {
1413 $dbr =& wfGetDB( DB_SLAVE
);
1415 $this->checkDBSchema($dbr);
1417 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1418 $this->historyRes
= $dbr->select( 'image',
1422 'img_user','img_user_text',
1426 "'' AS oi_archive_name"
1428 array( 'img_name' => $this->title
->getDBkey() ),
1431 if ( 0 == wfNumRows( $this->historyRes
) ) {
1434 } else if ( $this->historyLine
== 1 ) {
1435 $this->historyRes
= $dbr->select( 'oldimage',
1437 'oi_size AS img_size',
1438 'oi_description AS img_description',
1439 'oi_user AS img_user',
1440 'oi_user_text AS img_user_text',
1441 'oi_timestamp AS img_timestamp',
1442 'oi_width as img_width',
1443 'oi_height as img_height',
1446 array( 'oi_name' => $this->title
->getDBkey() ),
1448 array( 'ORDER BY' => 'oi_timestamp DESC' )
1451 $this->historyLine ++
;
1453 return $dbr->fetchObject( $this->historyRes
);
1457 * Reset the history pointer to the first element of the history
1460 function resetHistory() {
1461 $this->historyLine
= 0;
1465 * Return the full filesystem path to the file. Note that this does
1466 * not mean that a file actually exists under that location.
1468 * This path depends on whether directory hashing is active or not,
1469 * i.e. whether the images are all found in the same directory,
1470 * or in hashed paths like /images/3/3c.
1473 * @param boolean $fromSharedDirectory Return the path to the file
1474 * in a shared repository (see $wgUseSharedRepository and related
1475 * options in DefaultSettings.php) instead of a local one.
1478 function getFullPath( $fromSharedRepository = false ) {
1479 global $wgUploadDirectory, $wgSharedUploadDirectory;
1481 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1484 // $wgSharedUploadDirectory may be false, if thumb.php is used
1486 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1498 public static function isHashed( $shared ) {
1499 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1500 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1504 * Record an image upload in the upload log and the image table
1506 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1507 global $wgUser, $wgUseCopyrightUpload;
1509 $dbw =& wfGetDB( DB_MASTER
);
1511 $this->checkDBSchema($dbw);
1513 // Delete thumbnails and refresh the metadata cache
1514 $this->purgeCache();
1516 // Fail now if the image isn't there
1517 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1518 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1522 if ( $wgUseCopyrightUpload ) {
1523 if ( $license != '' ) {
1524 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1526 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1527 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1529 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1531 if ( $license != '' ) {
1532 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1533 $textdesc = $filedesc .
1534 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1540 $now = $dbw->timestamp();
1543 if (strpos($this->mime
,'/')!==false) {
1544 list($major,$minor)= explode('/',$this->mime
,2);
1547 $major= $this->mime
;
1551 # Test to see if the row exists using INSERT IGNORE
1552 # This avoids race conditions by locking the row until the commit, and also
1553 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1554 $dbw->insert( 'image',
1556 'img_name' => $this->name
,
1557 'img_size'=> $this->size
,
1558 'img_width' => intval( $this->width
),
1559 'img_height' => intval( $this->height
),
1560 'img_bits' => $this->bits
,
1561 'img_media_type' => $this->type
,
1562 'img_major_mime' => $major,
1563 'img_minor_mime' => $minor,
1564 'img_timestamp' => $now,
1565 'img_description' => $desc,
1566 'img_user' => $wgUser->getID(),
1567 'img_user_text' => $wgUser->getName(),
1568 'img_metadata' => $this->metadata
,
1574 if( $dbw->affectedRows() == 0 ) {
1575 # Collision, this is an update of an image
1576 # Insert previous contents into oldimage
1577 $dbw->insertSelect( 'oldimage', 'image',
1579 'oi_name' => 'img_name',
1580 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1581 'oi_size' => 'img_size',
1582 'oi_width' => 'img_width',
1583 'oi_height' => 'img_height',
1584 'oi_bits' => 'img_bits',
1585 'oi_timestamp' => 'img_timestamp',
1586 'oi_description' => 'img_description',
1587 'oi_user' => 'img_user',
1588 'oi_user_text' => 'img_user_text',
1589 ), array( 'img_name' => $this->name
), __METHOD__
1592 # Update the current image row
1593 $dbw->update( 'image',
1595 'img_size' => $this->size
,
1596 'img_width' => intval( $this->width
),
1597 'img_height' => intval( $this->height
),
1598 'img_bits' => $this->bits
,
1599 'img_media_type' => $this->type
,
1600 'img_major_mime' => $major,
1601 'img_minor_mime' => $minor,
1602 'img_timestamp' => $now,
1603 'img_description' => $desc,
1604 'img_user' => $wgUser->getID(),
1605 'img_user_text' => $wgUser->getName(),
1606 'img_metadata' => $this->metadata
,
1607 ), array( /* WHERE */
1608 'img_name' => $this->name
1612 # This is a new image
1613 # Update the image count
1614 $site_stats = $dbw->tableName( 'site_stats' );
1615 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1618 $descTitle = $this->getTitle();
1619 $article = new Article( $descTitle );
1621 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1622 $suppressRC = true; // There's already a log entry, so don't double the RC load
1624 if( $descTitle->exists() ) {
1625 // TODO: insert a null revision into the page history for this update.
1627 $wgUser->addWatch( $descTitle );
1630 # Invalidate the cache for the description page
1631 $descTitle->invalidateCache();
1632 $descTitle->purgeSquid();
1634 // New image; create the description page.
1635 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1639 $log = new LogPage( 'upload' );
1640 $log->addEntry( 'upload', $descTitle, $desc );
1642 # Commit the transaction now, in case something goes wrong later
1643 # The most important thing is that images don't get lost, especially archives
1644 $dbw->immediateCommit();
1646 # Invalidate cache for all pages using this image
1647 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1648 $update->doUpdate();
1654 * Get an array of Title objects which are articles which use this image
1655 * Also adds their IDs to the link cache
1657 * This is mostly copied from Title::getLinksTo()
1659 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1661 function getLinksTo( $options = '' ) {
1662 wfProfileIn( __METHOD__
);
1665 $db =& wfGetDB( DB_MASTER
);
1667 $db =& wfGetDB( DB_SLAVE
);
1669 $linkCache =& LinkCache
::singleton();
1671 extract( $db->tableNames( 'page', 'imagelinks' ) );
1672 $encName = $db->addQuotes( $this->name
);
1673 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1674 $res = $db->query( $sql, __METHOD__
);
1677 if ( $db->numRows( $res ) ) {
1678 while ( $row = $db->fetchObject( $res ) ) {
1679 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1680 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1681 $retVal[] = $titleObj;
1685 $db->freeResult( $res );
1686 wfProfileOut( __METHOD__
);
1691 * Retrive Exif data from the file and prune unrecognized tags
1692 * and/or tags with invalid contents
1697 private function retrieveExifData( $filename ) {
1701 if ( $this->getMimeType() !== "image/jpeg" )
1705 if( $wgShowEXIF && file_exists( $filename ) ) {
1706 $exif = new Exif( $filename );
1707 return $exif->getFilteredData();
1713 function getExifData() {
1715 if ( $this->metadata
=== '0' )
1718 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1719 $ret = unserialize( $this->metadata
);
1721 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1722 $newver = Exif
::version();
1724 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1725 $this->purgeMetadataCache();
1726 $this->updateExifData( $newver );
1728 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1729 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1730 $format = new FormatExif( $ret );
1732 return $format->getFormattedData();
1735 function updateExifData( $version ) {
1736 if ( $this->getImagePath() === false ) # Not a local image
1739 # Get EXIF data from image
1740 $exif = $this->retrieveExifData( $this->imagePath
);
1741 if ( count( $exif ) ) {
1742 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1743 $this->metadata
= serialize( $exif );
1745 $this->metadata
= '0';
1748 # Update EXIF data in database
1749 $dbw =& wfGetDB( DB_MASTER
);
1751 $this->checkDBSchema($dbw);
1753 $dbw->update( 'image',
1754 array( 'img_metadata' => $this->metadata
),
1755 array( 'img_name' => $this->name
),
1761 * Returns true if the image does not come from the shared
1766 function isLocal() {
1767 return !$this->fromSharedDirectory
;
1771 * Was this image ever deleted from the wiki?
1775 function wasDeleted() {
1776 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1777 return ( $title->isDeleted() > 0 );
1781 * Delete all versions of the image.
1783 * Moves the files into an archive directory (or deletes them)
1784 * and removes the database rows.
1786 * Cache purging is done; logging is caller's responsibility.
1789 * @return true on success, false on some kind of failure
1791 function delete( $reason ) {
1792 $transaction = new FSTransaction();
1793 $urlArr = array( $this->getURL() );
1795 if( !FileStore
::lock() ) {
1796 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1801 $dbw = wfGetDB( DB_MASTER
);
1804 // Delete old versions
1805 $result = $dbw->select( 'oldimage',
1806 array( 'oi_archive_name' ),
1807 array( 'oi_name' => $this->name
) );
1809 while( $row = $dbw->fetchObject( $result ) ) {
1810 $oldName = $row->oi_archive_name
;
1812 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1814 // We'll need to purge this URL from caches...
1815 $urlArr[] = wfImageArchiveUrl( $oldName );
1817 $dbw->freeResult( $result );
1819 // And the current version...
1820 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1822 $dbw->immediateCommit();
1823 } catch( MWException
$e ) {
1824 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1825 $transaction->rollback();
1826 FileStore
::unlock();
1830 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1831 $transaction->commit();
1832 FileStore
::unlock();
1835 // Update site_stats
1836 $site_stats = $dbw->tableName( 'site_stats' );
1837 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1839 $this->purgeEverything( $urlArr );
1846 * Delete an old version of the image.
1848 * Moves the file into an archive directory (or deletes it)
1849 * and removes the database row.
1851 * Cache purging is done; logging is caller's responsibility.
1854 * @throws MWException or FSException on database or filestore failure
1855 * @return true on success, false on some kind of failure
1857 function deleteOld( $archiveName, $reason ) {
1858 $transaction = new FSTransaction();
1861 if( !FileStore
::lock() ) {
1862 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1866 $transaction = new FSTransaction();
1868 $dbw = wfGetDB( DB_MASTER
);
1870 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1871 $dbw->immediateCommit();
1872 } catch( MWException
$e ) {
1873 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1874 $transaction->rollback();
1875 FileStore
::unlock();
1879 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1880 $transaction->commit();
1881 FileStore
::unlock();
1883 $this->purgeDescription();
1887 if ( $wgUseSquid ) {
1889 wfImageArchiveUrl( $archiveName ),
1891 wfPurgeSquidServers( $urlArr );
1897 * Delete the current version of a file.
1898 * May throw a database error.
1899 * @return true on success, false on failure
1901 private function prepareDeleteCurrent( $reason ) {
1902 return $this->prepareDeleteVersion(
1903 $this->getFullPath(),
1907 'fa_name' => 'img_name',
1908 'fa_archive_name' => 'NULL',
1909 'fa_size' => 'img_size',
1910 'fa_width' => 'img_width',
1911 'fa_height' => 'img_height',
1912 'fa_metadata' => 'img_metadata',
1913 'fa_bits' => 'img_bits',
1914 'fa_media_type' => 'img_media_type',
1915 'fa_major_mime' => 'img_major_mime',
1916 'fa_minor_mime' => 'img_minor_mime',
1917 'fa_description' => 'img_description',
1918 'fa_user' => 'img_user',
1919 'fa_user_text' => 'img_user_text',
1920 'fa_timestamp' => 'img_timestamp' ),
1921 array( 'img_name' => $this->name
),
1926 * Delete a given older version of a file.
1927 * May throw a database error.
1928 * @return true on success, false on failure
1930 private function prepareDeleteOld( $archiveName, $reason ) {
1931 $oldpath = wfImageArchiveDir( $this->name
) .
1932 DIRECTORY_SEPARATOR
. $archiveName;
1933 return $this->prepareDeleteVersion(
1938 'fa_name' => 'oi_name',
1939 'fa_archive_name' => 'oi_archive_name',
1940 'fa_size' => 'oi_size',
1941 'fa_width' => 'oi_width',
1942 'fa_height' => 'oi_height',
1943 'fa_metadata' => 'NULL',
1944 'fa_bits' => 'oi_bits',
1945 'fa_media_type' => 'NULL',
1946 'fa_major_mime' => 'NULL',
1947 'fa_minor_mime' => 'NULL',
1948 'fa_description' => 'oi_description',
1949 'fa_user' => 'oi_user',
1950 'fa_user_text' => 'oi_user_text',
1951 'fa_timestamp' => 'oi_timestamp' ),
1953 'oi_name' => $this->name
,
1954 'oi_archive_name' => $archiveName ),
1959 * Do the dirty work of backing up an image row and its file
1960 * (if $wgSaveDeletedFiles is on) and removing the originals.
1962 * Must be run while the file store is locked and a database
1963 * transaction is open to avoid race conditions.
1965 * @return FSTransaction
1967 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1968 global $wgUser, $wgSaveDeletedFiles;
1970 // Dupe the file into the file store
1971 if( file_exists( $path ) ) {
1972 if( $wgSaveDeletedFiles ) {
1975 $store = FileStore
::get( $group );
1976 $key = FileStore
::calculateKey( $path, $this->extension
);
1977 $transaction = $store->insert( $key, $path,
1978 FileStore
::DELETE_ORIGINAL
);
1982 $transaction = FileStore
::deleteFile( $path );
1985 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1988 $transaction = new FSTransaction(); // empty
1991 if( $transaction === false ) {
1993 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1994 throw new MWException( "Could not archive and delete file $path" );
1998 $dbw = wfGetDB( DB_MASTER
);
1999 $storageMap = array(
2000 'fa_storage_group' => $dbw->addQuotes( $group ),
2001 'fa_storage_key' => $dbw->addQuotes( $key ),
2003 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2004 'fa_deleted_timestamp' => $dbw->timestamp(),
2005 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2006 $allFields = array_merge( $storageMap, $fieldMap );
2009 if( $wgSaveDeletedFiles ) {
2010 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2012 $dbw->delete( $table, $where, $fname );
2013 } catch( DBQueryError
$e ) {
2014 // Something went horribly wrong!
2015 // Leave the file as it was...
2016 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
2017 $transaction->rollback();
2021 return $transaction;
2025 * Restore all or specified deleted revisions to the given file.
2026 * Permissions and logging are left to the caller.
2028 * May throw database exceptions on error.
2030 * @param $versions set of record ids of deleted items to restore,
2031 * or empty to restore all revisions.
2032 * @return the number of file revisions restored if successful,
2033 * or false on failure
2035 function restore( $versions=array() ) {
2036 if( !FileStore
::lock() ) {
2037 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
2041 $transaction = new FSTransaction();
2043 $dbw = wfGetDB( DB_MASTER
);
2046 // Re-confirm whether this image presently exists;
2047 // if no we'll need to create an image record for the
2048 // first item we restore.
2049 $exists = $dbw->selectField( 'image', '1',
2050 array( 'img_name' => $this->name
),
2053 // Fetch all or selected archived revisions for the file,
2054 // sorted from the most recent to the oldest.
2055 $conditions = array( 'fa_name' => $this->name
);
2057 $conditions['fa_id'] = $versions;
2060 $result = $dbw->select( 'filearchive', '*',
2063 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2065 if( $dbw->numRows( $result ) < count( $versions ) ) {
2066 // There's some kind of conflict or confusion;
2067 // we can't restore everything we were asked to.
2068 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2070 FileStore
::unlock();
2074 if( $dbw->numRows( $result ) == 0 ) {
2076 wfDebug( __METHOD__
.": nothing to do\n" );
2078 FileStore
::unlock();
2083 while( $row = $dbw->fetchObject( $result ) ) {
2085 $store = FileStore
::get( $row->fa_storage_group
);
2087 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2091 if( $revisions == 1 && !$exists ) {
2092 $destDir = wfImageDir( $row->fa_name
);
2093 if ( !is_dir( $destDir ) ) {
2094 wfMkdirParents( $destDir );
2096 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2098 // We may have to fill in data if this was originally
2099 // an archived file revision.
2100 if( is_null( $row->fa_metadata
) ) {
2101 $tempFile = $store->filePath( $row->fa_storage_key
);
2102 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2104 $magic = wfGetMimeMagic();
2105 $mime = $magic->guessMimeType( $tempFile, true );
2106 $media_type = $magic->getMediaType( $tempFile, $mime );
2107 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2109 $metadata = $row->fa_metadata
;
2110 $major_mime = $row->fa_major_mime
;
2111 $minor_mime = $row->fa_minor_mime
;
2112 $media_type = $row->fa_media_type
;
2117 'img_name' => $row->fa_name
,
2118 'img_size' => $row->fa_size
,
2119 'img_width' => $row->fa_width
,
2120 'img_height' => $row->fa_height
,
2121 'img_metadata' => $metadata,
2122 'img_bits' => $row->fa_bits
,
2123 'img_media_type' => $media_type,
2124 'img_major_mime' => $major_mime,
2125 'img_minor_mime' => $minor_mime,
2126 'img_description' => $row->fa_description
,
2127 'img_user' => $row->fa_user
,
2128 'img_user_text' => $row->fa_user_text
,
2129 'img_timestamp' => $row->fa_timestamp
);
2131 $archiveName = $row->fa_archive_name
;
2132 if( $archiveName == '' ) {
2133 // This was originally a current version; we
2134 // have to devise a new archive name for it.
2135 // Format is <timestamp of archiving>!<name>
2137 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2138 '!' . $row->fa_name
;
2140 $destDir = wfImageArchiveDir( $row->fa_name
);
2141 if ( !is_dir( $destDir ) ) {
2142 wfMkdirParents( $destDir );
2144 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2146 $table = 'oldimage';
2148 'oi_name' => $row->fa_name
,
2149 'oi_archive_name' => $archiveName,
2150 'oi_size' => $row->fa_size
,
2151 'oi_width' => $row->fa_width
,
2152 'oi_height' => $row->fa_height
,
2153 'oi_bits' => $row->fa_bits
,
2154 'oi_description' => $row->fa_description
,
2155 'oi_user' => $row->fa_user
,
2156 'oi_user_text' => $row->fa_user_text
,
2157 'oi_timestamp' => $row->fa_timestamp
);
2160 $dbw->insert( $table, $fields, __METHOD__
);
2161 /// @fixme this delete is not totally safe, potentially
2162 $dbw->delete( 'filearchive',
2163 array( 'fa_id' => $row->fa_id
),
2166 // Check if any other stored revisions use this file;
2167 // if so, we shouldn't remove the file from the deletion
2168 // archives so they will still work.
2169 $useCount = $dbw->selectField( 'filearchive',
2172 'fa_storage_group' => $row->fa_storage_group
,
2173 'fa_storage_key' => $row->fa_storage_key
),
2175 if( $useCount == 0 ) {
2176 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2177 $flags = FileStore
::DELETE_ORIGINAL
;
2182 $transaction->add( $store->export( $row->fa_storage_key
,
2183 $destPath, $flags ) );
2186 $dbw->immediateCommit();
2187 } catch( MWException
$e ) {
2188 wfDebug( __METHOD__
." caught error, aborting\n" );
2189 $transaction->rollback();
2193 $transaction->commit();
2194 FileStore
::unlock();
2196 if( $revisions > 0 ) {
2198 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2200 // Update site_stats
2201 $site_stats = $dbw->tableName( 'site_stats' );
2202 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2204 $this->purgeEverything();
2206 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2207 $this->purgeDescription();
2217 * Wrapper class for thumbnail images
2218 * @package MediaWiki
2220 class ThumbnailImage
{
2222 * @param string $path Filesystem path to the thumb
2223 * @param string $url URL path to the thumb
2226 function ThumbnailImage( $url, $width, $height, $path = false ) {
2228 $this->width
= round( $width );
2229 $this->height
= round( $height );
2230 # These should be integers when they get here.
2231 # If not, there's a bug somewhere. But let's at
2232 # least produce valid HTML code regardless.
2233 $this->path
= $path;
2237 * @return string The thumbnail URL
2244 * Return HTML <img ... /> tag for the thumbnail, will include
2245 * width and height attributes and a blank alt text (as required).
2247 * You can set or override additional attributes by passing an
2248 * associative array of name => data pairs. The data will be escaped
2249 * for HTML output, so should be in plaintext.
2251 * @param array $attribs
2255 function toHtml( $attribs = array() ) {
2256 $attribs['src'] = $this->url
;
2257 $attribs['width'] = $this->width
;
2258 $attribs['height'] = $this->height
;
2259 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2262 foreach( $attribs as $name => $data ) {
2263 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';