6 # NOTE FOR WINDOWS USERS:
7 # To enable EXIF functions, add the folloing lines to the
8 # "Windows extensions" section of php.ini:
10 # extension=extensions/php_mbstring.dll
11 # extension=extensions/php_exif.dll
14 require_once('Exif.php');
18 * Class to represent an image
20 * Provides methods to retrieve paths (physical, logical, URL),
21 * to generate thumbnails or for uploading.
29 var $name, # name of the image (constructor)
30 $imagePath, # Path of the image (loadFromXxx)
31 $url, # Image URL (accessor)
32 $title, # Title object for this image (constructor)
33 $fileExists, # does the image file exist on disk? (loadFromXxx)
34 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
35 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
36 $historyRes, # result of the query for the image's history (nextHistoryLine)
39 $bits, # --- returned by getimagesize (loadFromXxx)
42 $size, # Size in bytes (loadFromXxx)
44 $exif, # The Exif class
45 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
51 * Create an Image object from an image name
53 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
56 function newFromName( $name ) {
57 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
58 return new Image( $title );
62 * Obsolete factory function, use constructor
64 function newFromTitle( $title ) {
65 return new Image( $title );
68 function Image( $title ) {
71 $this->title
=& $title;
72 $this->name
= $title->getDBkey();
73 $this->metadata
= serialize ( array() ) ;
75 $n = strrpos( $this->name
, '.' );
76 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
77 $this->historyLine
= 0;
79 $this->dataLoaded
= false;
82 $this->exif
= new Exif
;
86 * Get the memcached keys
87 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
89 function getCacheKeys( $shared = false ) {
90 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
93 $hashedName = md5($this->name
);
94 $keys = array( "$wgDBname:Image:$hashedName" );
95 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
96 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
102 * Try to load image metadata from memcached. Returns true on success.
104 function loadFromCache() {
105 global $wgUseSharedUploads, $wgMemc;
106 $fname = 'Image::loadFromMemcached';
107 wfProfileIn( $fname );
108 $this->dataLoaded
= false;
109 $keys = $this->getCacheKeys();
110 $cachedValues = $wgMemc->get( $keys[0] );
112 // Check if the key existed and belongs to this version of MediaWiki
113 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
114 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
115 # if this is shared file, we need to check if image
116 # in shared repository has not changed
117 if ( isset( $keys[1] ) ) {
118 $commonsCachedValues = $wgMemc->get( $keys[1] );
119 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
120 $this->name
= $commonsCachedValues['name'];
121 $this->imagePath
= $commonsCachedValues['imagePath'];
122 $this->fileExists
= $commonsCachedValues['fileExists'];
123 $this->width
= $commonsCachedValues['width'];
124 $this->height
= $commonsCachedValues['height'];
125 $this->bits
= $commonsCachedValues['bits'];
126 $this->type
= $commonsCachedValues['type'];
127 $this->metadata
= $commonsCachedValues['metadata'];
128 $this->size
= $commonsCachedValues['size'];
129 $this->fromSharedDirectory
= true;
130 $this->dataLoaded
= true;
131 $this->imagePath
= $this->getFullPath(true);
136 $this->name
= $cachedValues['name'];
137 $this->imagePath
= $cachedValues['imagePath'];
138 $this->fileExists
= $cachedValues['fileExists'];
139 $this->width
= $cachedValues['width'];
140 $this->height
= $cachedValues['height'];
141 $this->bits
= $cachedValues['bits'];
142 $this->type
= $cachedValues['type'];
143 $this->metadata
= $cachedValues['metadata'];
144 $this->size
= $cachedValues['size'];
145 $this->fromSharedDirectory
= false;
146 $this->dataLoaded
= true;
147 $this->imagePath
= $this->getFullPath();
151 wfProfileOut( $fname );
152 return $this->dataLoaded
;
156 * Save the image metadata to memcached
158 function saveToCache() {
161 // We can't cache metadata for non-existent files, because if the file later appears
162 // in commons, the local keys won't be purged.
163 if ( $this->fileExists
) {
164 $keys = $this->getCacheKeys();
166 $cachedValues = array('name' => $this->name
,
167 'imagePath' => $this->imagePath
,
168 'fileExists' => $this->fileExists
,
169 'fromShared' => $this->fromSharedDirectory
,
170 'width' => $this->width
,
171 'height' => $this->height
,
172 'bits' => $this->bits
,
173 'type' => $this->type
,
174 'metadata' => $this->metadata
,
175 'size' => $this->size
);
177 $wgMemc->set( $keys[0], $cachedValues );
182 * Load metadata from the file itself
184 function loadFromFile() {
185 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
186 $fname = 'Image::loadFromFile';
187 wfProfileIn( $fname );
188 $this->imagePath
= $this->getFullPath();
189 $this->fileExists
= file_exists( $this->imagePath
);
190 $this->fromSharedDirectory
= false;
193 # If the file is not found, and a shared upload directory is used, look for it there.
194 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
195 # In case we're on a wgCapitalLinks=false wiki, we
196 # capitalize the first letter of the filename before
197 # looking it up in the shared repository.
198 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
199 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
200 if ( $this->fileExists
) {
201 $this->name
= $sharedImage->name
;
202 $this->imagePath
= $this->getFullPath(true);
203 $this->fromSharedDirectory
= true;
207 if ( $this->fileExists
) {
209 $this->size
= filesize( $this->imagePath
);
212 # Don't try to get the width and height of sound and video files, that's bad for performance
213 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
215 } elseif( $this->extension
== 'svg' ) {
216 wfSuppressWarnings();
217 $gis = wfGetSVGsize( $this->imagePath
);
220 wfSuppressWarnings();
221 $gis = getimagesize( $this->imagePath
);
225 if( $gis === false ) {
230 $this->metadata
= serialize ( array() ) ;
232 $this->width
= $gis[0];
233 $this->height
= $gis[1];
234 $this->type
= $gis[2];
235 $this->metadata
= serialize ( $this->retrieveExifData() ) ;
236 if ( isset( $gis['bits'] ) ) {
237 $this->bits
= $gis['bits'];
242 $this->dataLoaded
= true;
243 wfProfileOut( $fname );
247 * Load image metadata from the DB
249 function loadFromDB() {
250 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
251 $fname = 'Image::loadFromDB';
252 wfProfileIn( $fname );
254 $dbr =& wfGetDB( DB_SLAVE
);
255 $row = $dbr->selectRow( 'image',
256 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
257 array( 'img_name' => $this->name
), $fname );
259 $this->fromSharedDirectory
= false;
260 $this->fileExists
= true;
261 $this->loadFromRow( $row );
262 $this->imagePath
= $this->getFullPath();
263 // Check for rows from a previous schema, quietly upgrade them
264 if ( $this->type
== -1 ) {
267 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
268 # In case we're on a wgCapitalLinks=false wiki, we
269 # capitalize the first letter of the filename before
270 # looking it up in the shared repository.
271 $name = $wgLang->ucfirst($this->name
);
273 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
274 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
275 array( 'img_name' => $name ), $fname );
277 $this->fromSharedDirectory
= true;
278 $this->fileExists
= true;
279 $this->imagePath
= $this->getFullPath(true);
281 $this->loadFromRow( $row );
283 // Check for rows from a previous schema, quietly upgrade them
284 if ( $this->type
== -1 ) {
296 $this->fileExists
= false;
297 $this->fromSharedDirectory
= false;
298 $this->metadata
= serialize ( array() ) ;
301 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
302 $this->dataLoaded
= true;
306 * Load image metadata from a DB result row
308 function loadFromRow( &$row ) {
309 $this->size
= $row->img_size
;
310 $this->width
= $row->img_width
;
311 $this->height
= $row->img_height
;
312 $this->bits
= $row->img_bits
;
313 $this->type
= $row->img_type
;
314 $this->metadata
= $row->img_metadata
;
315 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
316 $this->dataLoaded
= true;
320 * Load image metadata from cache or DB, unless already loaded
323 global $wgSharedUploadDBname, $wgUseSharedUploads;
324 if ( !$this->dataLoaded
) {
325 if ( !$this->loadFromCache() ) {
327 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
328 $this->loadFromFile();
329 } elseif ( $this->fileExists
) {
330 $this->saveToCache();
333 $this->dataLoaded
= true;
338 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
339 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
341 function upgradeRow() {
342 global $wgDBname, $wgSharedUploadDBname;
343 $fname = 'Image::upgradeRow';
344 $this->loadFromFile();
345 $dbw =& wfGetDB( DB_MASTER
);
347 if ( $this->fromSharedDirectory
) {
348 if ( !$wgSharedUploadDBname ) {
352 // Write to the other DB using selectDB, not database selectors
353 // This avoids breaking replication in MySQL
354 $dbw->selectDB( $wgSharedUploadDBname );
356 $dbw->update( 'image',
358 'img_width' => $this->width
,
359 'img_height' => $this->height
,
360 'img_bits' => $this->bits
,
361 'img_type' => $this->type
,
362 'img_metadata' => $this->metadata
,
363 ), array( 'img_name' => $this->name
), $fname
365 if ( $this->fromSharedDirectory
) {
366 $dbw->selectDB( $wgDBname );
371 * Return the name of this image
379 * Return the associated title object
382 function getTitle() {
387 * Return the URL of the image file
393 if($this->fileExists
) {
394 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
402 function getViewURL() {
403 if( $this->mustRender() ) {
404 return $this->createThumb( $this->getWidth() );
406 return $this->getURL();
411 * Return the image path of the image in the
412 * local file system as an absolute path
415 function getImagePath() {
417 return $this->imagePath
;
421 * Return the width of the image
423 * Returns -1 if the file specified is not a known image type
426 function getWidth() {
432 * Return the height of the image
434 * Returns -1 if the file specified is not a known image type
437 function getHeight() {
439 return $this->height
;
443 * Return the size of the image file, in bytes
452 * Return the type of the image
466 * Return the escapeLocalURL of this image
469 function getEscapeLocalURL() {
471 return $this->title
->escapeLocalURL();
475 * Return the escapeFullURL of this image
478 function getEscapeFullURL() {
480 return $this->title
->escapeFullURL();
484 * Return the URL of an image, provided its name.
486 * @param string $name Name of the image, without the leading "Image:"
487 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
491 function imageUrl( $name, $fromSharedDirectory = false ) {
492 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
493 if($fromSharedDirectory) {
495 $path = $wgSharedUploadPath;
497 $base = $wgUploadBaseUrl;
498 $path = $wgUploadPath;
500 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
501 return wfUrlencode( $url );
505 * Returns true if the image file exists on disk.
511 return $this->fileExists
;
518 function thumbUrl( $width, $subdir='thumb') {
519 global $wgUploadPath, $wgUploadBaseUrl,
520 $wgSharedUploadPath,$wgSharedUploadDirectory,
521 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
523 // Generate thumb.php URL if possible
527 if ( $this->fromSharedDirectory
) {
528 if ( $wgSharedThumbnailScriptPath ) {
529 $script = $wgSharedThumbnailScriptPath;
532 if ( $wgThumbnailScriptPath ) {
533 $script = $wgThumbnailScriptPath;
537 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
539 $name = $this->thumbName( $width );
540 if($this->fromSharedDirectory
) {
542 $path = $wgSharedUploadPath;
544 $base = $wgUploadBaseUrl;
545 $path = $wgUploadPath;
547 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
548 $url = "{$base}{$path}/{$subdir}" .
549 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
550 . $this->name
.'/'.$name;
551 $url = wfUrlencode( $url );
553 $url = "{$base}{$path}/{$subdir}/{$name}";
556 return array( $script !== false, $url );
560 * Return the file name of a thumbnail of the specified width
562 * @param integer $width Width of the thumbnail image
563 * @param boolean $shared Does the thumbnail come from the shared repository?
566 function thumbName( $width ) {
567 $thumb = $width."px-".$this->name
;
568 if( $this->extension
== 'svg' ) {
569 # Rasterize SVG vector images to PNG
576 * Create a thumbnail of the image having the specified width/height.
577 * The thumbnail will not be created if the width is larger than the
578 * image's width. Let the browser do the scaling in this case.
579 * The thumbnail is stored on disk and is only computed if the thumbnail
580 * file does not exist OR if it is older than the image.
583 * Keeps aspect ratio of original image. If both width and height are
584 * specified, the generated image will be no bigger than width x height,
585 * and will also have correct aspect ratio.
587 * @param integer $width maximum width of the generated thumbnail
588 * @param integer $height maximum height of the image (optional)
591 function createThumb( $width, $height=-1 ) {
592 $thumb = $this->getThumbnail( $width, $height );
593 if( is_null( $thumb ) ) return '';
594 return $thumb->getUrl();
598 * As createThumb, but returns a ThumbnailImage object. This can
599 * provide access to the actual file, the real size of the thumb,
600 * and can produce a convenient <img> tag for you.
602 * @param integer $width maximum width of the generated thumbnail
603 * @param integer $height maximum height of the image (optional)
604 * @return ThumbnailImage
607 function &getThumbnail( $width, $height=-1 ) {
608 if ( $height == -1 ) {
609 return $this->renderThumb( $width );
612 if ( $width < $this->width
) {
613 $thumbheight = $this->height
* $width / $this->width
;
614 $thumbwidth = $width;
616 $thumbheight = $this->height
;
617 $thumbwidth = $this->width
;
619 if ( $thumbheight > $height ) {
620 $thumbwidth = $thumbwidth * $height / $thumbheight;
621 $thumbheight = $height;
623 $thumb = $this->renderThumb( $thumbwidth );
624 if( is_null( $thumb ) ) {
625 $thumb = $this->iconThumb();
631 * @return ThumbnailImage
633 function iconThumb() {
634 global $wgStylePath, $wgStyleDirectory;
636 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
637 foreach( $try as $icon ) {
638 $path = '/common/images/' . $icon;
639 $filepath = $wgStyleDirectory . $path;
640 if( file_exists( $filepath ) ) {
641 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
648 * Create a thumbnail of the image having the specified width.
649 * The thumbnail will not be created if the width is larger than the
650 * image's width. Let the browser do the scaling in this case.
651 * The thumbnail is stored on disk and is only computed if the thumbnail
652 * file does not exist OR if it is older than the image.
653 * Returns an object which can return the pathname, URL, and physical
654 * pixel size of the thumbnail -- or null on failure.
656 * @return ThumbnailImage
659 function renderThumb( $width, $useScript = true ) {
660 global $wgUseSquid, $wgInternalServer;
661 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
663 $width = IntVal( $width );
666 if ( ! $this->exists() )
668 # If there is no image, there will be no thumbnail
672 # Sanity check $width
678 if( $width > $this->width
&& !$this->mustRender() ) {
679 # Don't make an image bigger than the source
680 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
683 $height = floor( $this->height
* ( $width/$this->width
) );
685 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
686 if ( $isScriptUrl && $useScript ) {
687 // Use thumb.php to render the image
688 return new ThumbnailImage( $url, $width, $height );
691 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
692 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
694 if ( !file_exists( $thumbPath ) ) {
695 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
698 if ( file_exists( $oldThumbPath ) ) {
699 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
700 rename( $oldThumbPath, $thumbPath );
703 unlink( $oldThumbPath );
707 $this->reallyRenderThumb( $thumbPath, $width, $height );
710 # This has to be done after the image is updated and present for all machines on NFS,
711 # or else the old version might be stored into the squid again
713 if ( substr( $url, 0, 4 ) == 'http' ) {
714 $urlArr = array( $url );
716 $urlArr = array( $wgInternalServer.$url );
718 wfPurgeSquidServers($urlArr);
722 return new ThumbnailImage( $url, $width, $height, $thumbPath );
723 } // END OF function renderThumb
726 * Really render a thumbnail
730 function reallyRenderThumb( $thumbPath, $width, $height ) {
731 global $wgSVGConverters, $wgSVGConverter,
732 $wgUseImageMagick, $wgImageMagickConvertCommand;
736 if( $this->extension
== 'svg' ) {
737 global $wgSVGConverters, $wgSVGConverter;
738 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
739 global $wgSVGConverterPath;
741 array( '$path/', '$width', '$input', '$output' ),
742 array( $wgSVGConverterPath,
744 escapeshellarg( $this->imagePath
),
745 escapeshellarg( $thumbPath ) ),
746 $wgSVGConverters[$wgSVGConverter] );
747 $conv = shell_exec( $cmd );
751 } elseif ( $wgUseImageMagick ) {
753 # Specify white background color, will be used for transparent images
754 # in Internet Explorer/Windows instead of default black.
755 $cmd = $wgImageMagickConvertCommand .
756 " -quality 85 -background white -geometry {$width} ".
757 escapeshellarg($this->imagePath
) . " " .
758 escapeshellarg($thumbPath);
759 $conv = shell_exec( $cmd );
761 # Use PHP's builtin GD library functions.
763 # First find out what kind of file this is, and select the correct
764 # input routine for this.
768 switch( $this->type
) {
770 $src_image = imagecreatefromgif( $this->imagePath
);
773 $src_image = imagecreatefromjpeg( $this->imagePath
);
777 $src_image = imagecreatefrompng( $this->imagePath
);
778 $truecolor = ( $this->bits
> 8 );
780 case 15: # WBMP for WML
781 $src_image = imagecreatefromwbmp( $this->imagePath
);
784 $src_image = imagecreatefromxbm( $this->imagePath
);
787 return 'Image type not supported';
791 $dst_image = imagecreatetruecolor( $width, $height );
793 $dst_image = imagecreate( $width, $height );
795 imagecopyresampled( $dst_image, $src_image,
797 $width, $height, $this->width
, $this->height
);
798 switch( $this->type
) {
803 imagepng( $dst_image, $thumbPath );
806 imageinterlace( $dst_image );
807 imagejpeg( $dst_image, $thumbPath, 95 );
812 imagedestroy( $dst_image );
813 imagedestroy( $src_image );
816 # Check for zero-sized thumbnails. Those can be generated when
817 # no disk space is available or some other error occurs
819 if( file_exists( $thumbPath ) ) {
820 $thumbstat = stat( $thumbPath );
821 if( $thumbstat['size'] == 0 ) {
822 unlink( $thumbPath );
828 * Get all thumbnail names previously generated for this image
830 function getThumbnails( $shared = false ) {
831 if ( Image
::isHashed( $shared ) ) {
834 $dir = wfImageThumbDir( $this->name
, $shared );
836 // This generates an error on failure, hence the @
837 $handle = @opendir
( $dir );
840 while ( false !== ( $file = readdir($handle) ) ) {
841 if ( $file{0} != '.' ) {
855 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
857 function purgeCache( $archiveFiles = array(), $shared = false ) {
858 global $wgInternalServer, $wgUseSquid;
860 // Refresh metadata cache
862 $this->loadFromFile();
863 $this->saveToCache();
866 $files = $this->getThumbnails( $shared );
867 $dir = wfImageThumbDir( $this->name
, $shared );
869 foreach ( $files as $file ) {
870 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
871 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
872 @unlink
( "$dir/$file" );
878 $urls[] = $wgInternalServer . $this->getViewURL();
879 foreach ( $archiveFiles as $file ) {
880 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
882 wfPurgeSquidServers( $urls );
887 * Return the image history of this image, line by line.
888 * starts with current version, then old versions.
889 * uses $this->historyLine to check which line to return:
890 * 0 return line for current version
891 * 1 query for old versions, return first one
892 * 2, ... return next old version from above query
896 function nextHistoryLine() {
897 $fname = 'Image::nextHistoryLine()';
898 $dbr =& wfGetDB( DB_SLAVE
);
899 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
900 $this->historyRes
= $dbr->select( 'image',
901 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
902 array( 'img_name' => $this->title
->getDBkey() ),
905 if ( 0 == wfNumRows( $this->historyRes
) ) {
908 } else if ( $this->historyLine
== 1 ) {
909 $this->historyRes
= $dbr->select( 'oldimage',
910 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
911 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
912 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
915 $this->historyLine ++
;
917 return $dbr->fetchObject( $this->historyRes
);
921 * Reset the history pointer to the first element of the history
924 function resetHistory() {
925 $this->historyLine
= 0;
929 * Return true if the file is of a type that can't be directly
930 * rendered by typical browsers and needs to be re-rasterized.
933 function mustRender() {
935 return ( $this->extension
== 'svg' );
939 * Return the full filesystem path to the file. Note that this does
940 * not mean that a file actually exists under that location.
942 * This path depends on whether directory hashing is active or not,
943 * i.e. whether the images are all found in the same directory,
944 * or in hashed paths like /images/3/3c.
947 * @param boolean $fromSharedDirectory Return the path to the file
948 * in a shared repository (see $wgUseSharedRepository and related
949 * options in DefaultSettings.php) instead of a local one.
952 function getFullPath( $fromSharedRepository = false ) {
953 global $wgUploadDirectory, $wgSharedUploadDirectory;
954 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
956 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
959 // $wgSharedUploadDirectory may be false, if thumb.php is used
961 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
973 function isHashed( $shared ) {
974 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
975 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
982 function isKnownImageExtension( $ext ) {
983 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
984 return in_array( $ext, $extensions );
988 * Record an image upload in the upload log and the image table
990 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
991 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
992 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
994 $fname = 'Image::recordUpload';
995 $dbw =& wfGetDB( DB_MASTER
);
997 # img_name must be unique
998 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
999 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1002 // Delete thumbnails and refresh the metadata cache
1003 $this->purgeCache();
1005 // Fail now if the image isn't there
1006 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1010 if ( $wgUseCopyrightUpload ) {
1011 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1012 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1013 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1018 $now = $dbw->timestamp();
1020 # Test to see if the row exists using INSERT IGNORE
1021 # This avoids race conditions by locking the row until the commit, and also
1022 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1023 $dbw->insert( 'image',
1025 'img_name' => $this->name
,
1026 'img_size'=> $this->size
,
1027 'img_width' => $this->width
,
1028 'img_height' => $this->height
,
1029 'img_bits' => $this->bits
,
1030 'img_type' => $this->type
,
1031 'img_timestamp' => $now,
1032 'img_description' => $desc,
1033 'img_user' => $wgUser->getID(),
1034 'img_user_text' => $wgUser->getName(),
1035 'img_metadata' => $this->metadata
,
1038 $descTitle = $this->getTitle();
1039 $purgeURLs = array();
1041 if ( $dbw->affectedRows() ) {
1042 # Successfully inserted, this is a new image
1043 $id = $descTitle->getArticleID();
1046 $article = new Article( $descTitle );
1047 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1050 # Collision, this is an update of an image
1051 # Insert previous contents into oldimage
1052 $dbw->insertSelect( 'oldimage', 'image',
1054 'oi_name' => 'img_name',
1055 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1056 'oi_size' => 'img_size',
1057 'oi_width' => 'img_width',
1058 'oi_height' => 'img_height',
1059 'oi_bits' => 'img_bits',
1060 'oi_type' => 'img_type',
1061 'oi_timestamp' => 'img_timestamp',
1062 'oi_description' => 'img_description',
1063 'oi_user' => 'img_user',
1064 'oi_user_text' => 'img_user_text',
1065 ), array( 'img_name' => $this->name
), $fname
1068 # Update the current image row
1069 $dbw->update( 'image',
1071 'img_size' => $this->size
,
1072 'img_width' => $this->width
,
1073 'img_height' => $this->height
,
1074 'img_bits' => $this->bits
,
1075 'img_type' => $this->type
,
1076 'img_timestamp' => $now,
1077 'img_user' => $wgUser->getID(),
1078 'img_user_text' => $wgUser->getName(),
1079 'img_description' => $desc,
1080 'img_metadata' => $this->metadata
,
1081 ), array( /* WHERE */
1082 'img_name' => $this->name
1086 # Invalidate the cache for the description page
1087 $descTitle->invalidateCache();
1088 $purgeURLs[] = $descTitle->getInternalURL();
1091 # Invalidate cache for all pages using this image
1092 $linksTo = $this->getLinksTo();
1094 if ( $wgUseSquid ) {
1095 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1096 array_push( $wgPostCommitUpdateList, $u );
1098 Title
::touchArray( $linksTo );
1100 $log = new LogPage( 'upload' );
1101 $log->addEntry( 'upload', $descTitle, $desc );
1107 * Get an array of Title objects which are articles which use this image
1108 * Also adds their IDs to the link cache
1110 * This is mostly copied from Title::getLinksTo()
1112 function getLinksTo( $options = '' ) {
1113 global $wgLinkCache;
1114 $fname = 'Image::getLinksTo';
1115 wfProfileIn( $fname );
1118 $db =& wfGetDB( DB_MASTER
);
1120 $db =& wfGetDB( DB_SLAVE
);
1123 extract( $db->tableNames( 'page', 'imagelinks' ) );
1124 $encName = $db->addQuotes( $this->name
);
1125 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1126 $res = $db->query( $sql, $fname );
1129 if ( $db->numRows( $res ) ) {
1130 while ( $row = $db->fetchObject( $res ) ) {
1131 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1132 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1133 $retVal[] = $titleObj;
1137 $db->freeResult( $res );
1141 * Retrive Exif data from the database
1143 * Retrive Exif data from the database and prune unrecognized tags
1144 * and/or tags with invalid contents
1148 function retrieveExifData () {
1149 global $wgShowEXIF ;
1150 if ( ! $wgShowEXIF ) return array ();
1151 if ( $this->type
!== '2' ) return array ();
1153 $exif = exif_read_data( $this->imagePath
);
1154 foreach($exif as $k => $v) {
1155 if ( !in_array($k, array_keys($this->exif
->mFlatExif
)) ) {
1156 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1161 foreach($exif as $k => $v) {
1162 if ( !$this->exif
->validate($k, $v) ) {
1163 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1170 function getExifData () {
1173 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1174 $ret = unserialize ( $this->metadata
);
1176 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1177 $newver = $this->exif
->version();
1179 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1180 $this->updateExifData( $newver );
1181 $ret = unserialize( $this->metadata
);
1183 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1184 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1186 foreach($ret as $k => $v) {
1187 $ret[$k] = $this->exif
->format($k, $v);
1193 function updateExifData( $version ) {
1195 $fname = 'Image:updateExifData';
1197 if ( ! $wgShowEXIF ||
$this->getImagePath() === false ) # Not a local image
1200 # Get EXIF data from image
1201 $exif = $this->retrieveExifData();
1202 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1203 $this->metadata
= serialize( $exif );
1205 # Update EXIF data in database
1206 $dbw =& wfGetDB( DB_MASTER
);
1207 $dbw->update( 'image',
1208 array( 'img_metadata' => $this->metadata
),
1209 array( 'img_name' => $this->name
),
1218 * Returns the image directory of an image
1219 * If the directory does not exist, it is created.
1220 * The result is an absolute path.
1222 * This function is called from thumb.php before Setup.php is included
1224 * @param string $fname file name of the image file
1227 function wfImageDir( $fname ) {
1228 global $wgUploadDirectory, $wgHashedUploadDirectory;
1230 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1232 $hash = md5( $fname );
1233 $oldumask = umask(0);
1234 $dest = $wgUploadDirectory . '/' . $hash{0};
1235 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1236 $dest .= '/' . substr( $hash, 0, 2 );
1237 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1244 * Returns the image directory of an image's thubnail
1245 * If the directory does not exist, it is created.
1246 * The result is an absolute path.
1248 * This function is called from thumb.php before Setup.php is included
1250 * @param string $fname file name of the original image file
1251 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1252 * @param boolean $shared (optional) use the shared upload directory
1255 function wfImageThumbDir( $fname, $shared = false ) {
1256 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1257 if ( Image
::isHashed( $shared ) ) {
1258 $dir = "$base/$fname";
1260 if ( !is_dir( $base ) ) {
1261 $oldumask = umask(0);
1262 @mkdir
( $base, 0777 );
1266 if ( ! is_dir( $dir ) ) {
1267 $oldumask = umask(0);
1268 @mkdir
( $dir, 0777 );
1279 * Old thumbnail directory, kept for conversion
1281 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1282 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1286 * Returns the image directory of an image's old version
1287 * If the directory does not exist, it is created.
1288 * The result is an absolute path.
1290 * This function is called from thumb.php before Setup.php is included
1292 * @param string $fname file name of the thumbnail file, including file size prefix
1293 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1294 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1297 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1298 global $wgUploadDirectory, $wgHashedUploadDirectory,
1299 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1300 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1301 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1302 if (!$hashdir) { return $dir.'/'.$subdir; }
1303 $hash = md5( $fname );
1304 $oldumask = umask(0);
1306 # Suppress warning messages here; if the file itself can't
1307 # be written we'll worry about it then.
1308 wfSuppressWarnings();
1310 $archive = $dir.'/'.$subdir;
1311 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1312 $archive .= '/' . $hash{0};
1313 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1314 $archive .= '/' . substr( $hash, 0, 2 );
1315 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1317 wfRestoreWarnings();
1324 * Return the hash path component of an image path (URL or filesystem),
1325 * e.g. "/3/3c/", or just "/" if hashing is not used.
1327 * @param $dbkey The filesystem / database name of the file
1328 * @param $fromSharedDirectory Use the shared file repository? It may
1329 * use different hash settings from the local one.
1331 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1332 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1333 global $wgHashedUploadDirectory;
1335 if( Image
::isHashed( $fromSharedDirectory ) ) {
1336 $hash = md5($dbkey);
1337 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1344 * Returns the image URL of an image's old version
1346 * @param string $fname file name of the image file
1347 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1350 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1351 global $wgUploadPath, $wgHashedUploadDirectory;
1353 if ($wgHashedUploadDirectory) {
1354 $hash = md5( substr( $name, 15) );
1355 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1356 substr( $hash, 0, 2 ) . '/'.$name;
1358 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1360 return wfUrlencode($url);
1364 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1365 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1367 * @param string $length
1368 * @return int Length in pixels
1370 function wfScaleSVGUnit( $length ) {
1371 static $unitLength = array(
1378 '' => 1.0, // "User units" pixels by default
1379 '%' => 2.0, // Fake it!
1381 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1382 $length = FloatVal( $matches[1] );
1383 $unit = $matches[2];
1384 return round( $length * $unitLength[$unit] );
1387 return round( FloatVal( $length ) );
1392 * Compatible with PHP getimagesize()
1393 * @todo support gzipped SVGZ
1394 * @todo check XML more carefully
1395 * @todo sensible defaults
1397 * @param string $filename
1400 function wfGetSVGsize( $filename ) {
1404 // Read a chunk of the file
1405 $f = fopen( $filename, "rt" );
1406 if( !$f ) return false;
1407 $chunk = fread( $f, 4096 );
1410 // Uber-crappy hack! Run through a real XML parser.
1411 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1415 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1416 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1418 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1419 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1422 return array( $width, $height, 'SVG',
1423 "width=\"$width\" height=\"$height\"" );
1427 * Determine if an image exists on the 'bad image list'
1429 * @param string $name The image to check
1432 function wfIsBadImage( $name ) {
1434 static $titleList = false;
1435 if ( $titleList === false ) {
1436 $titleList = array();
1438 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1439 foreach ( $lines as $line ) {
1440 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1441 $t = Title
::newFromText( $m[1] );
1442 $titleList[$t->getDBkey()] = 1;
1447 return array_key_exists( $name, $titleList );
1453 * Wrapper class for thumbnail images
1454 * @package MediaWiki
1456 class ThumbnailImage
{
1458 * @param string $path Filesystem path to the thumb
1459 * @param string $url URL path to the thumb
1462 function ThumbnailImage( $url, $width, $height, $path = false ) {
1464 $this->width
= $width;
1465 $this->height
= $height;
1466 $this->path
= $path;
1470 * @return string The thumbnail URL
1477 * Return HTML <img ... /> tag for the thumbnail, will include
1478 * width and height attributes and a blank alt text (as required).
1480 * You can set or override additional attributes by passing an
1481 * associative array of name => data pairs. The data will be escaped
1482 * for HTML output, so should be in plaintext.
1484 * @param array $attribs
1488 function toHtml( $attribs = array() ) {
1489 $attribs['src'] = $this->url
;
1490 $attribs['width'] = $this->width
;
1491 $attribs['height'] = $this->height
;
1492 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1495 foreach( $attribs as $name => $data ) {
1496 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';