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'])
114 && $cachedValues['fileExists'] && isset( $cachedValues['metadata'] ) )
116 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
117 # if this is shared file, we need to check if image
118 # in shared repository has not changed
119 if ( isset( $keys[1] ) ) {
120 $commonsCachedValues = $wgMemc->get( $keys[1] );
121 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
122 $this->name
= $commonsCachedValues['name'];
123 $this->imagePath
= $commonsCachedValues['imagePath'];
124 $this->fileExists
= $commonsCachedValues['fileExists'];
125 $this->width
= $commonsCachedValues['width'];
126 $this->height
= $commonsCachedValues['height'];
127 $this->bits
= $commonsCachedValues['bits'];
128 $this->type
= $commonsCachedValues['type'];
129 $this->metadata
= $commonsCachedValues['metadata'];
130 $this->size
= $commonsCachedValues['size'];
131 $this->fromSharedDirectory
= true;
132 $this->dataLoaded
= true;
133 $this->imagePath
= $this->getFullPath(true);
138 $this->name
= $cachedValues['name'];
139 $this->imagePath
= $cachedValues['imagePath'];
140 $this->fileExists
= $cachedValues['fileExists'];
141 $this->width
= $cachedValues['width'];
142 $this->height
= $cachedValues['height'];
143 $this->bits
= $cachedValues['bits'];
144 $this->type
= $cachedValues['type'];
145 $this->metadata
= $cachedValues['metadata'];
146 $this->size
= $cachedValues['size'];
147 $this->fromSharedDirectory
= false;
148 $this->dataLoaded
= true;
149 $this->imagePath
= $this->getFullPath();
153 wfProfileOut( $fname );
154 return $this->dataLoaded
;
158 * Save the image metadata to memcached
160 function saveToCache() {
163 // We can't cache metadata for non-existent files, because if the file later appears
164 // in commons, the local keys won't be purged.
165 if ( $this->fileExists
) {
166 $keys = $this->getCacheKeys();
168 $cachedValues = array('name' => $this->name
,
169 'imagePath' => $this->imagePath
,
170 'fileExists' => $this->fileExists
,
171 'fromShared' => $this->fromSharedDirectory
,
172 'width' => $this->width
,
173 'height' => $this->height
,
174 'bits' => $this->bits
,
175 'type' => $this->type
,
176 'metadata' => $this->metadata
,
177 'size' => $this->size
);
179 $wgMemc->set( $keys[0], $cachedValues );
184 * Load metadata from the file itself
186 function loadFromFile() {
187 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
188 $fname = 'Image::loadFromFile';
189 wfProfileIn( $fname );
190 $this->imagePath
= $this->getFullPath();
191 $this->fileExists
= file_exists( $this->imagePath
);
192 $this->fromSharedDirectory
= false;
195 # If the file is not found, and a shared upload directory is used, look for it there.
196 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
197 # In case we're on a wgCapitalLinks=false wiki, we
198 # capitalize the first letter of the filename before
199 # looking it up in the shared repository.
200 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
201 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
202 if ( $this->fileExists
) {
203 $this->name
= $sharedImage->name
;
204 $this->imagePath
= $this->getFullPath(true);
205 $this->fromSharedDirectory
= true;
209 if ( $this->fileExists
) {
211 $this->size
= filesize( $this->imagePath
);
214 # Don't try to get the width and height of sound and video files, that's bad for performance
215 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
217 } elseif( $this->extension
== 'svg' ) {
218 wfSuppressWarnings();
219 $gis = wfGetSVGsize( $this->imagePath
);
222 wfSuppressWarnings();
223 $gis = getimagesize( $this->imagePath
);
227 if( $gis === false ) {
232 $this->metadata
= serialize ( array() ) ;
234 $this->width
= $gis[0];
235 $this->height
= $gis[1];
236 $this->type
= $gis[2];
237 $this->metadata
= serialize ( $this->retrieveExifData() ) ;
238 if ( isset( $gis['bits'] ) ) {
239 $this->bits
= $gis['bits'];
244 $this->dataLoaded
= true;
245 wfProfileOut( $fname );
249 * Load image metadata from the DB
251 function loadFromDB() {
252 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
253 $fname = 'Image::loadFromDB';
254 wfProfileIn( $fname );
256 $dbr =& wfGetDB( DB_SLAVE
);
257 $row = $dbr->selectRow( 'image',
258 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
259 array( 'img_name' => $this->name
), $fname );
261 $this->fromSharedDirectory
= false;
262 $this->fileExists
= true;
263 $this->loadFromRow( $row );
264 $this->imagePath
= $this->getFullPath();
265 // Check for rows from a previous schema, quietly upgrade them
266 if ( $this->type
== -1 ) {
269 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
270 # In case we're on a wgCapitalLinks=false wiki, we
271 # capitalize the first letter of the filename before
272 # looking it up in the shared repository.
273 $name = $wgLang->ucfirst($this->name
);
275 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
276 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
277 array( 'img_name' => $name ), $fname );
279 $this->fromSharedDirectory
= true;
280 $this->fileExists
= true;
281 $this->imagePath
= $this->getFullPath(true);
283 $this->loadFromRow( $row );
285 // Check for rows from a previous schema, quietly upgrade them
286 if ( $this->type
== -1 ) {
298 $this->fileExists
= false;
299 $this->fromSharedDirectory
= false;
300 $this->metadata
= serialize ( array() ) ;
303 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
304 $this->dataLoaded
= true;
308 * Load image metadata from a DB result row
310 function loadFromRow( &$row ) {
311 $this->size
= $row->img_size
;
312 $this->width
= $row->img_width
;
313 $this->height
= $row->img_height
;
314 $this->bits
= $row->img_bits
;
315 $this->type
= $row->img_type
;
316 $this->metadata
= $row->img_metadata
;
317 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
318 $this->dataLoaded
= true;
322 * Load image metadata from cache or DB, unless already loaded
325 global $wgSharedUploadDBname, $wgUseSharedUploads;
326 if ( !$this->dataLoaded
) {
327 if ( !$this->loadFromCache() ) {
329 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
330 $this->loadFromFile();
331 } elseif ( $this->fileExists
) {
332 $this->saveToCache();
335 $this->dataLoaded
= true;
340 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
341 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
343 function upgradeRow() {
344 global $wgDBname, $wgSharedUploadDBname;
345 $fname = 'Image::upgradeRow';
346 $this->loadFromFile();
347 $dbw =& wfGetDB( DB_MASTER
);
349 if ( $this->fromSharedDirectory
) {
350 if ( !$wgSharedUploadDBname ) {
354 // Write to the other DB using selectDB, not database selectors
355 // This avoids breaking replication in MySQL
356 $dbw->selectDB( $wgSharedUploadDBname );
358 $dbw->update( 'image',
360 'img_width' => $this->width
,
361 'img_height' => $this->height
,
362 'img_bits' => $this->bits
,
363 'img_type' => $this->type
,
364 'img_metadata' => $this->metadata
,
365 ), array( 'img_name' => $this->name
), $fname
367 if ( $this->fromSharedDirectory
) {
368 $dbw->selectDB( $wgDBname );
373 * Return the name of this image
381 * Return the associated title object
384 function getTitle() {
389 * Return the URL of the image file
395 if($this->fileExists
) {
396 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
404 function getViewURL() {
405 if( $this->mustRender() ) {
406 return $this->createThumb( $this->getWidth() );
408 return $this->getURL();
413 * Return the image path of the image in the
414 * local file system as an absolute path
417 function getImagePath() {
419 return $this->imagePath
;
423 * Return the width of the image
425 * Returns -1 if the file specified is not a known image type
428 function getWidth() {
434 * Return the height of the image
436 * Returns -1 if the file specified is not a known image type
439 function getHeight() {
441 return $this->height
;
445 * Return the size of the image file, in bytes
454 * Return the type of the image
468 * Return the escapeLocalURL of this image
471 function getEscapeLocalURL() {
473 return $this->title
->escapeLocalURL();
477 * Return the escapeFullURL of this image
480 function getEscapeFullURL() {
482 return $this->title
->escapeFullURL();
486 * Return the URL of an image, provided its name.
488 * @param string $name Name of the image, without the leading "Image:"
489 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
493 function imageUrl( $name, $fromSharedDirectory = false ) {
494 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
495 if($fromSharedDirectory) {
497 $path = $wgSharedUploadPath;
499 $base = $wgUploadBaseUrl;
500 $path = $wgUploadPath;
502 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
503 return wfUrlencode( $url );
507 * Returns true if the image file exists on disk.
513 return $this->fileExists
;
520 function thumbUrl( $width, $subdir='thumb') {
521 global $wgUploadPath, $wgUploadBaseUrl,
522 $wgSharedUploadPath,$wgSharedUploadDirectory,
523 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
525 // Generate thumb.php URL if possible
529 if ( $this->fromSharedDirectory
) {
530 if ( $wgSharedThumbnailScriptPath ) {
531 $script = $wgSharedThumbnailScriptPath;
534 if ( $wgThumbnailScriptPath ) {
535 $script = $wgThumbnailScriptPath;
539 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
541 $name = $this->thumbName( $width );
542 if($this->fromSharedDirectory
) {
544 $path = $wgSharedUploadPath;
546 $base = $wgUploadBaseUrl;
547 $path = $wgUploadPath;
549 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
550 $url = "{$base}{$path}/{$subdir}" .
551 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
552 . $this->name
.'/'.$name;
553 $url = wfUrlencode( $url );
555 $url = "{$base}{$path}/{$subdir}/{$name}";
558 return array( $script !== false, $url );
562 * Return the file name of a thumbnail of the specified width
564 * @param integer $width Width of the thumbnail image
565 * @param boolean $shared Does the thumbnail come from the shared repository?
568 function thumbName( $width ) {
569 $thumb = $width."px-".$this->name
;
570 if( $this->extension
== 'svg' ) {
571 # Rasterize SVG vector images to PNG
578 * Create a thumbnail of the image having the specified width/height.
579 * The thumbnail will not be created if the width is larger than the
580 * image's width. Let the browser do the scaling in this case.
581 * The thumbnail is stored on disk and is only computed if the thumbnail
582 * file does not exist OR if it is older than the image.
585 * Keeps aspect ratio of original image. If both width and height are
586 * specified, the generated image will be no bigger than width x height,
587 * and will also have correct aspect ratio.
589 * @param integer $width maximum width of the generated thumbnail
590 * @param integer $height maximum height of the image (optional)
593 function createThumb( $width, $height=-1 ) {
594 $thumb = $this->getThumbnail( $width, $height );
595 if( is_null( $thumb ) ) return '';
596 return $thumb->getUrl();
600 * As createThumb, but returns a ThumbnailImage object. This can
601 * provide access to the actual file, the real size of the thumb,
602 * and can produce a convenient <img> tag for you.
604 * @param integer $width maximum width of the generated thumbnail
605 * @param integer $height maximum height of the image (optional)
606 * @return ThumbnailImage
609 function &getThumbnail( $width, $height=-1 ) {
610 if ( $height == -1 ) {
611 return $this->renderThumb( $width );
614 if ( $width < $this->width
) {
615 $thumbheight = $this->height
* $width / $this->width
;
616 $thumbwidth = $width;
618 $thumbheight = $this->height
;
619 $thumbwidth = $this->width
;
621 if ( $thumbheight > $height ) {
622 $thumbwidth = $thumbwidth * $height / $thumbheight;
623 $thumbheight = $height;
625 $thumb = $this->renderThumb( $thumbwidth );
626 if( is_null( $thumb ) ) {
627 $thumb = $this->iconThumb();
633 * @return ThumbnailImage
635 function iconThumb() {
636 global $wgStylePath, $wgStyleDirectory;
638 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
639 foreach( $try as $icon ) {
640 $path = '/common/images/icons/' . $icon;
641 $filepath = $wgStyleDirectory . $path;
642 if( file_exists( $filepath ) ) {
643 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
650 * Create a thumbnail of the image having the specified width.
651 * The thumbnail will not be created if the width is larger than the
652 * image's width. Let the browser do the scaling in this case.
653 * The thumbnail is stored on disk and is only computed if the thumbnail
654 * file does not exist OR if it is older than the image.
655 * Returns an object which can return the pathname, URL, and physical
656 * pixel size of the thumbnail -- or null on failure.
658 * @return ThumbnailImage
661 function renderThumb( $width, $useScript = true ) {
662 global $wgUseSquid, $wgInternalServer;
663 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
665 $width = IntVal( $width );
668 if ( ! $this->exists() )
670 # If there is no image, there will be no thumbnail
674 # Sanity check $width
680 if( $width > $this->width
&& !$this->mustRender() ) {
681 # Don't make an image bigger than the source
682 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
685 $height = floor( $this->height
* ( $width/$this->width
) );
687 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
688 if ( $isScriptUrl && $useScript ) {
689 // Use thumb.php to render the image
690 return new ThumbnailImage( $url, $width, $height );
693 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
694 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
696 if ( !file_exists( $thumbPath ) ) {
697 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
700 if ( file_exists( $oldThumbPath ) ) {
701 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
702 rename( $oldThumbPath, $thumbPath );
705 unlink( $oldThumbPath );
709 $this->reallyRenderThumb( $thumbPath, $width, $height );
712 # This has to be done after the image is updated and present for all machines on NFS,
713 # or else the old version might be stored into the squid again
715 if ( substr( $url, 0, 4 ) == 'http' ) {
716 $urlArr = array( $url );
718 $urlArr = array( $wgInternalServer.$url );
720 wfPurgeSquidServers($urlArr);
724 return new ThumbnailImage( $url, $width, $height, $thumbPath );
725 } // END OF function renderThumb
728 * Really render a thumbnail
732 function reallyRenderThumb( $thumbPath, $width, $height ) {
733 global $wgSVGConverters, $wgSVGConverter,
734 $wgUseImageMagick, $wgImageMagickConvertCommand;
738 if( $this->extension
== 'svg' ) {
739 global $wgSVGConverters, $wgSVGConverter;
740 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
741 global $wgSVGConverterPath;
743 array( '$path/', '$width', '$input', '$output' ),
744 array( $wgSVGConverterPath,
746 escapeshellarg( $this->imagePath
),
747 escapeshellarg( $thumbPath ) ),
748 $wgSVGConverters[$wgSVGConverter] );
749 $conv = shell_exec( $cmd );
753 } elseif ( $wgUseImageMagick ) {
755 # Specify white background color, will be used for transparent images
756 # in Internet Explorer/Windows instead of default black.
757 $cmd = $wgImageMagickConvertCommand .
758 " -quality 85 -background white -geometry {$width} ".
759 escapeshellarg($this->imagePath
) . " " .
760 escapeshellarg($thumbPath);
761 $conv = shell_exec( $cmd );
763 # Use PHP's builtin GD library functions.
765 # First find out what kind of file this is, and select the correct
766 # input routine for this.
770 switch( $this->type
) {
772 $src_image = imagecreatefromgif( $this->imagePath
);
775 $src_image = imagecreatefromjpeg( $this->imagePath
);
779 $src_image = imagecreatefrompng( $this->imagePath
);
780 $truecolor = ( $this->bits
> 8 );
782 case 15: # WBMP for WML
783 $src_image = imagecreatefromwbmp( $this->imagePath
);
786 $src_image = imagecreatefromxbm( $this->imagePath
);
789 return 'Image type not supported';
793 $dst_image = imagecreatetruecolor( $width, $height );
795 $dst_image = imagecreate( $width, $height );
797 imagecopyresampled( $dst_image, $src_image,
799 $width, $height, $this->width
, $this->height
);
800 switch( $this->type
) {
805 imagepng( $dst_image, $thumbPath );
808 imageinterlace( $dst_image );
809 imagejpeg( $dst_image, $thumbPath, 95 );
814 imagedestroy( $dst_image );
815 imagedestroy( $src_image );
818 # Check for zero-sized thumbnails. Those can be generated when
819 # no disk space is available or some other error occurs
821 if( file_exists( $thumbPath ) ) {
822 $thumbstat = stat( $thumbPath );
823 if( $thumbstat['size'] == 0 ) {
824 unlink( $thumbPath );
830 * Get all thumbnail names previously generated for this image
832 function getThumbnails( $shared = false ) {
833 if ( Image
::isHashed( $shared ) ) {
836 $dir = wfImageThumbDir( $this->name
, $shared );
838 // This generates an error on failure, hence the @
839 $handle = @opendir
( $dir );
842 while ( false !== ( $file = readdir($handle) ) ) {
843 if ( $file{0} != '.' ) {
857 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
859 function purgeCache( $archiveFiles = array(), $shared = false ) {
860 global $wgInternalServer, $wgUseSquid;
862 // Refresh metadata cache
864 $this->loadFromFile();
865 $this->saveToCache();
868 $files = $this->getThumbnails( $shared );
869 $dir = wfImageThumbDir( $this->name
, $shared );
871 foreach ( $files as $file ) {
872 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
873 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
874 @unlink
( "$dir/$file" );
880 $urls[] = $wgInternalServer . $this->getViewURL();
881 foreach ( $archiveFiles as $file ) {
882 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
884 wfPurgeSquidServers( $urls );
889 * Return the image history of this image, line by line.
890 * starts with current version, then old versions.
891 * uses $this->historyLine to check which line to return:
892 * 0 return line for current version
893 * 1 query for old versions, return first one
894 * 2, ... return next old version from above query
898 function nextHistoryLine() {
899 $fname = 'Image::nextHistoryLine()';
900 $dbr =& wfGetDB( DB_SLAVE
);
901 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
902 $this->historyRes
= $dbr->select( 'image',
903 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
904 array( 'img_name' => $this->title
->getDBkey() ),
907 if ( 0 == wfNumRows( $this->historyRes
) ) {
910 } else if ( $this->historyLine
== 1 ) {
911 $this->historyRes
= $dbr->select( 'oldimage',
912 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
913 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
914 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
917 $this->historyLine ++
;
919 return $dbr->fetchObject( $this->historyRes
);
923 * Reset the history pointer to the first element of the history
926 function resetHistory() {
927 $this->historyLine
= 0;
931 * Return true if the file is of a type that can't be directly
932 * rendered by typical browsers and needs to be re-rasterized.
935 function mustRender() {
937 return ( $this->extension
== 'svg' );
941 * Return the full filesystem path to the file. Note that this does
942 * not mean that a file actually exists under that location.
944 * This path depends on whether directory hashing is active or not,
945 * i.e. whether the images are all found in the same directory,
946 * or in hashed paths like /images/3/3c.
949 * @param boolean $fromSharedDirectory Return the path to the file
950 * in a shared repository (see $wgUseSharedRepository and related
951 * options in DefaultSettings.php) instead of a local one.
954 function getFullPath( $fromSharedRepository = false ) {
955 global $wgUploadDirectory, $wgSharedUploadDirectory;
956 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
958 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
961 // $wgSharedUploadDirectory may be false, if thumb.php is used
963 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
975 function isHashed( $shared ) {
976 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
977 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
984 function isKnownImageExtension( $ext ) {
985 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
986 return in_array( $ext, $extensions );
990 * Record an image upload in the upload log and the image table
992 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
993 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
994 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
996 $fname = 'Image::recordUpload';
997 $dbw =& wfGetDB( DB_MASTER
);
999 # img_name must be unique
1000 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
1001 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1004 // Delete thumbnails and refresh the metadata cache
1005 $this->purgeCache();
1007 // Fail now if the image isn't there
1008 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1012 if ( $wgUseCopyrightUpload ) {
1013 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1014 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1015 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1020 $now = $dbw->timestamp();
1022 # Test to see if the row exists using INSERT IGNORE
1023 # This avoids race conditions by locking the row until the commit, and also
1024 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1025 $dbw->insert( 'image',
1027 'img_name' => $this->name
,
1028 'img_size'=> $this->size
,
1029 'img_width' => $this->width
,
1030 'img_height' => $this->height
,
1031 'img_bits' => $this->bits
,
1032 'img_type' => $this->type
,
1033 'img_timestamp' => $now,
1034 'img_description' => $desc,
1035 'img_user' => $wgUser->getID(),
1036 'img_user_text' => $wgUser->getName(),
1037 'img_metadata' => $this->metadata
,
1040 $descTitle = $this->getTitle();
1041 $purgeURLs = array();
1043 if ( $dbw->affectedRows() ) {
1044 # Successfully inserted, this is a new image
1045 $id = $descTitle->getArticleID();
1048 $article = new Article( $descTitle );
1049 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1052 # Collision, this is an update of an image
1053 # Insert previous contents into oldimage
1054 $dbw->insertSelect( 'oldimage', 'image',
1056 'oi_name' => 'img_name',
1057 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1058 'oi_size' => 'img_size',
1059 'oi_width' => 'img_width',
1060 'oi_height' => 'img_height',
1061 'oi_bits' => 'img_bits',
1062 'oi_type' => 'img_type',
1063 'oi_timestamp' => 'img_timestamp',
1064 'oi_description' => 'img_description',
1065 'oi_user' => 'img_user',
1066 'oi_user_text' => 'img_user_text',
1067 ), array( 'img_name' => $this->name
), $fname
1070 # Update the current image row
1071 $dbw->update( 'image',
1073 'img_size' => $this->size
,
1074 'img_width' => $this->width
,
1075 'img_height' => $this->height
,
1076 'img_bits' => $this->bits
,
1077 'img_type' => $this->type
,
1078 'img_timestamp' => $now,
1079 'img_user' => $wgUser->getID(),
1080 'img_user_text' => $wgUser->getName(),
1081 'img_description' => $desc,
1082 'img_metadata' => $this->metadata
,
1083 ), array( /* WHERE */
1084 'img_name' => $this->name
1088 # Invalidate the cache for the description page
1089 $descTitle->invalidateCache();
1090 $purgeURLs[] = $descTitle->getInternalURL();
1093 # Invalidate cache for all pages using this image
1094 $linksTo = $this->getLinksTo();
1096 if ( $wgUseSquid ) {
1097 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1098 array_push( $wgPostCommitUpdateList, $u );
1100 Title
::touchArray( $linksTo );
1102 $log = new LogPage( 'upload' );
1103 $log->addEntry( 'upload', $descTitle, $desc );
1109 * Get an array of Title objects which are articles which use this image
1110 * Also adds their IDs to the link cache
1112 * This is mostly copied from Title::getLinksTo()
1114 function getLinksTo( $options = '' ) {
1115 global $wgLinkCache;
1116 $fname = 'Image::getLinksTo';
1117 wfProfileIn( $fname );
1120 $db =& wfGetDB( DB_MASTER
);
1122 $db =& wfGetDB( DB_SLAVE
);
1125 extract( $db->tableNames( 'page', 'imagelinks' ) );
1126 $encName = $db->addQuotes( $this->name
);
1127 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1128 $res = $db->query( $sql, $fname );
1131 if ( $db->numRows( $res ) ) {
1132 while ( $row = $db->fetchObject( $res ) ) {
1133 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1134 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1135 $retVal[] = $titleObj;
1139 $db->freeResult( $res );
1143 * Retrive Exif data from the database
1145 * Retrive Exif data from the database and prune unrecognized tags
1146 * and/or tags with invalid contents
1150 function retrieveExifData () {
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 () {
1172 if ( $this->metadata
=== '0' )
1175 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1176 $ret = unserialize ( $this->metadata
);
1178 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1179 $newver = $this->exif
->version();
1181 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1182 $this->updateExifData( $newver );
1184 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1185 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1187 foreach($ret as $k => $v) {
1188 $ret[$k] = $this->exif
->format($k, $v);
1194 function updateExifData( $version ) {
1195 $fname = 'Image:updateExifData';
1197 if ( $this->getImagePath() === false ) # Not a local image
1200 # Get EXIF data from image
1201 $exif = $this->retrieveExifData();
1202 if ( count( $exif ) ) {
1203 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1204 $this->metadata
= serialize( $exif );
1206 $this->metadata
= '0';
1209 # Update EXIF data in database
1210 $dbw =& wfGetDB( DB_MASTER
);
1211 $dbw->update( 'image',
1212 array( 'img_metadata' => $this->metadata
),
1213 array( 'img_name' => $this->name
),
1222 * Returns the image directory of an image
1223 * If the directory does not exist, it is created.
1224 * The result is an absolute path.
1226 * This function is called from thumb.php before Setup.php is included
1228 * @param string $fname file name of the image file
1231 function wfImageDir( $fname ) {
1232 global $wgUploadDirectory, $wgHashedUploadDirectory;
1234 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1236 $hash = md5( $fname );
1237 $oldumask = umask(0);
1238 $dest = $wgUploadDirectory . '/' . $hash{0};
1239 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1240 $dest .= '/' . substr( $hash, 0, 2 );
1241 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1248 * Returns the image directory of an image's thubnail
1249 * If the directory does not exist, it is created.
1250 * The result is an absolute path.
1252 * This function is called from thumb.php before Setup.php is included
1254 * @param string $fname file name of the original image file
1255 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1256 * @param boolean $shared (optional) use the shared upload directory
1259 function wfImageThumbDir( $fname, $shared = false ) {
1260 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1261 if ( Image
::isHashed( $shared ) ) {
1262 $dir = "$base/$fname";
1264 if ( !is_dir( $base ) ) {
1265 $oldumask = umask(0);
1266 @mkdir
( $base, 0777 );
1270 if ( ! is_dir( $dir ) ) {
1271 $oldumask = umask(0);
1272 @mkdir
( $dir, 0777 );
1283 * Old thumbnail directory, kept for conversion
1285 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1286 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1290 * Returns the image directory of an image's old version
1291 * If the directory does not exist, it is created.
1292 * The result is an absolute path.
1294 * This function is called from thumb.php before Setup.php is included
1296 * @param string $fname file name of the thumbnail file, including file size prefix
1297 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1298 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1301 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1302 global $wgUploadDirectory, $wgHashedUploadDirectory,
1303 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1304 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1305 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1306 if (!$hashdir) { return $dir.'/'.$subdir; }
1307 $hash = md5( $fname );
1308 $oldumask = umask(0);
1310 # Suppress warning messages here; if the file itself can't
1311 # be written we'll worry about it then.
1312 wfSuppressWarnings();
1314 $archive = $dir.'/'.$subdir;
1315 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1316 $archive .= '/' . $hash{0};
1317 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1318 $archive .= '/' . substr( $hash, 0, 2 );
1319 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1321 wfRestoreWarnings();
1328 * Return the hash path component of an image path (URL or filesystem),
1329 * e.g. "/3/3c/", or just "/" if hashing is not used.
1331 * @param $dbkey The filesystem / database name of the file
1332 * @param $fromSharedDirectory Use the shared file repository? It may
1333 * use different hash settings from the local one.
1335 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1336 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1337 global $wgHashedUploadDirectory;
1339 if( Image
::isHashed( $fromSharedDirectory ) ) {
1340 $hash = md5($dbkey);
1341 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1348 * Returns the image URL of an image's old version
1350 * @param string $fname file name of the image file
1351 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1354 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1355 global $wgUploadPath, $wgHashedUploadDirectory;
1357 if ($wgHashedUploadDirectory) {
1358 $hash = md5( substr( $name, 15) );
1359 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1360 substr( $hash, 0, 2 ) . '/'.$name;
1362 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1364 return wfUrlencode($url);
1368 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1369 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1371 * @param string $length
1372 * @return int Length in pixels
1374 function wfScaleSVGUnit( $length ) {
1375 static $unitLength = array(
1382 '' => 1.0, // "User units" pixels by default
1383 '%' => 2.0, // Fake it!
1385 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1386 $length = FloatVal( $matches[1] );
1387 $unit = $matches[2];
1388 return round( $length * $unitLength[$unit] );
1391 return round( FloatVal( $length ) );
1396 * Compatible with PHP getimagesize()
1397 * @todo support gzipped SVGZ
1398 * @todo check XML more carefully
1399 * @todo sensible defaults
1401 * @param string $filename
1404 function wfGetSVGsize( $filename ) {
1408 // Read a chunk of the file
1409 $f = fopen( $filename, "rt" );
1410 if( !$f ) return false;
1411 $chunk = fread( $f, 4096 );
1414 // Uber-crappy hack! Run through a real XML parser.
1415 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1419 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1420 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1422 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1423 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1426 return array( $width, $height, 'SVG',
1427 "width=\"$width\" height=\"$height\"" );
1431 * Determine if an image exists on the 'bad image list'
1433 * @param string $name The image to check
1436 function wfIsBadImage( $name ) {
1438 static $titleList = false;
1439 if ( $titleList === false ) {
1440 $titleList = array();
1442 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1443 foreach ( $lines as $line ) {
1444 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1445 $t = Title
::newFromText( $m[1] );
1446 $titleList[$t->getDBkey()] = 1;
1451 return array_key_exists( $name, $titleList );
1457 * Wrapper class for thumbnail images
1458 * @package MediaWiki
1460 class ThumbnailImage
{
1462 * @param string $path Filesystem path to the thumb
1463 * @param string $url URL path to the thumb
1466 function ThumbnailImage( $url, $width, $height, $path = false ) {
1468 $this->width
= $width;
1469 $this->height
= $height;
1470 $this->path
= $path;
1474 * @return string The thumbnail URL
1481 * Return HTML <img ... /> tag for the thumbnail, will include
1482 * width and height attributes and a blank alt text (as required).
1484 * You can set or override additional attributes by passing an
1485 * associative array of name => data pairs. The data will be escaped
1486 * for HTML output, so should be in plaintext.
1488 * @param array $attribs
1492 function toHtml( $attribs = array() ) {
1493 $attribs['src'] = $this->url
;
1494 $attribs['width'] = $this->width
;
1495 $attribs['height'] = $this->height
;
1496 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1499 foreach( $attribs as $name => $data ) {
1500 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';