65a46e318c27719a618528c62ecfd4698952f2fa
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
15 * Class to represent an image
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate thumbnails or for uploading.
26 var $name, # name of the image (constructor)
27 $imagePath, # Path of the image (loadFromXxx)
28 $url, # Image URL (accessor)
29 $title, # Title object for this image (constructor)
30 $fileExists, # does the image file exist on disk? (loadFromXxx)
31 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
32 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
33 $historyRes, # result of the query for the image's history (nextHistoryLine)
36 $bits, # --- returned by getimagesize (loadFromXxx)
39 $size, # Size in bytes (loadFromXxx)
41 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
47 * Create an Image object from an image name
49 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
52 function newFromName( $name ) {
53 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
54 return new Image( $title );
58 * Obsolete factory function, use constructor
60 function newFromTitle( $title ) {
61 return new Image( $title );
64 function Image( $title ) {
65 $this->title
=& $title;
66 $this->name
= $title->getDBkey();
67 $this->exif
= serialize ( array() ) ;
69 $n = strrpos( $this->name
, '.' );
70 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
71 $this->historyLine
= 0;
73 $this->dataLoaded
= false;
77 * Get the memcached keys
78 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
80 function getCacheKeys( $shared = false ) {
81 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
84 $hashedName = md5($this->name
);
85 $keys = array( "$wgDBname:Image:$hashedName" );
86 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
87 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
93 * Try to load image metadata from memcached. Returns true on success.
95 function loadFromCache() {
96 global $wgUseSharedUploads, $wgMemc;
97 $fname = 'Image::loadFromMemcached';
98 wfProfileIn( $fname );
99 $this->dataLoaded
= false;
100 $keys = $this->getCacheKeys();
101 $cachedValues = $wgMemc->get( $keys[0] );
103 // Check if the key existed and belongs to this version of MediaWiki
104 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
105 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
106 # if this is shared file, we need to check if image
107 # in shared repository has not changed
108 if ( isset( $keys[1] ) ) {
109 $commonsCachedValues = $wgMemc->get( $keys[1] );
110 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
111 $this->name
= $commonsCachedValues['name'];
112 $this->imagePath
= $commonsCachedValues['imagePath'];
113 $this->fileExists
= $commonsCachedValues['fileExists'];
114 $this->width
= $commonsCachedValues['width'];
115 $this->height
= $commonsCachedValues['height'];
116 $this->bits
= $commonsCachedValues['bits'];
117 $this->type
= $commonsCachedValues['type'];
118 $this->exif
= $commonsCachedValues['exif'];
119 $this->size
= $commonsCachedValues['size'];
120 $this->fromSharedDirectory
= true;
121 $this->dataLoaded
= true;
122 $this->imagePath
= $this->getFullPath(true);
127 $this->name
= $cachedValues['name'];
128 $this->imagePath
= $cachedValues['imagePath'];
129 $this->fileExists
= $cachedValues['fileExists'];
130 $this->width
= $cachedValues['width'];
131 $this->height
= $cachedValues['height'];
132 $this->bits
= $cachedValues['bits'];
133 $this->type
= $cachedValues['type'];
134 $this->exif
= $cachedValues['exif'];
135 $this->size
= $cachedValues['size'];
136 $this->fromSharedDirectory
= false;
137 $this->dataLoaded
= true;
138 $this->imagePath
= $this->getFullPath();
142 wfProfileOut( $fname );
143 return $this->dataLoaded
;
147 * Save the image metadata to memcached
149 function saveToCache() {
152 // We can't cache metadata for non-existent files, because if the file later appears
153 // in commons, the local keys won't be purged.
154 if ( $this->fileExists
) {
155 $keys = $this->getCacheKeys();
157 $cachedValues = array('name' => $this->name
,
158 'imagePath' => $this->imagePath
,
159 'fileExists' => $this->fileExists
,
160 'fromShared' => $this->fromSharedDirectory
,
161 'width' => $this->width
,
162 'height' => $this->height
,
163 'bits' => $this->bits
,
164 'type' => $this->type
,
165 'exif' => $this->exif
,
166 'size' => $this->size
);
168 $wgMemc->set( $keys[0], $cachedValues );
173 * Load metadata from the file itself
175 function loadFromFile() {
176 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
177 $fname = 'Image::loadFromFile';
178 wfProfileIn( $fname );
179 $this->imagePath
= $this->getFullPath();
180 $this->fileExists
= file_exists( $this->imagePath
);
181 $this->fromSharedDirectory
= false;
184 # If the file is not found, and a shared upload directory is used, look for it there.
185 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
186 # In case we're on a wgCapitalLinks=false wiki, we
187 # capitalize the first letter of the filename before
188 # looking it up in the shared repository.
189 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
190 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
191 if ( $this->fileExists
) {
192 $this->name
= $sharedImage->name
;
193 $this->imagePath
= $this->getFullPath(true);
194 $this->fromSharedDirectory
= true;
198 if ( $this->fileExists
) {
200 $this->size
= filesize( $this->imagePath
);
203 # Don't try to get the width and height of sound and video files, that's bad for performance
204 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
206 } elseif( $this->extension
== 'svg' ) {
207 wfSuppressWarnings();
208 $gis = wfGetSVGsize( $this->imagePath
);
211 wfSuppressWarnings();
212 $gis = getimagesize( $this->imagePath
);
216 if( $gis === false ) {
221 $this->exif
= serialize ( array() ) ;
223 $this->width
= $gis[0];
224 $this->height
= $gis[1];
225 $this->type
= $gis[2];
226 $this->exif
= serialize ( $this->retrieveExifData() ) ;
227 if ( isset( $gis['bits'] ) ) {
228 $this->bits
= $gis['bits'];
233 $this->dataLoaded
= true;
234 wfProfileOut( $fname );
238 * Load image metadata from the DB
240 function loadFromDB() {
241 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
242 $fname = 'Image::loadFromDB';
243 wfProfileIn( $fname );
245 $dbr =& wfGetDB( DB_SLAVE
);
246 $row = $dbr->selectRow( 'image',
247 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
248 array( 'img_name' => $this->name
), $fname );
250 $this->fromSharedDirectory
= false;
251 $this->fileExists
= true;
252 $this->loadFromRow( $row );
253 $this->imagePath
= $this->getFullPath();
254 // Check for rows from a previous schema, quietly upgrade them
255 if ( $this->type
== -1 ) {
258 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
259 # In case we're on a wgCapitalLinks=false wiki, we
260 # capitalize the first letter of the filename before
261 # looking it up in the shared repository.
262 $name = $wgLang->ucfirst($this->name
);
264 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
265 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
266 array( 'img_name' => $name ), $fname );
268 $this->fromSharedDirectory
= true;
269 $this->fileExists
= true;
270 $this->imagePath
= $this->getFullPath(true);
272 $this->loadFromRow( $row );
274 // Check for rows from a previous schema, quietly upgrade them
275 if ( $this->type
== -1 ) {
287 $this->fileExists
= false;
288 $this->fromSharedDirectory
= false;
289 $this->exif
= serialize ( array() ) ;
292 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
293 $this->dataLoaded
= true;
297 * Load image metadata from a DB result row
299 function loadFromRow( &$row ) {
300 $this->size
= $row->img_size
;
301 $this->width
= $row->img_width
;
302 $this->height
= $row->img_height
;
303 $this->bits
= $row->img_bits
;
304 $this->type
= $row->img_type
;
305 $this->exif
= $row->img_metadata
;
306 if ( $this->exif
== "" ) $this->exif
= serialize ( array() ) ;
307 $this->dataLoaded
= true;
311 * Load image metadata from cache or DB, unless already loaded
314 global $wgSharedUploadDBname, $wgUseSharedUploads;
315 if ( !$this->dataLoaded
) {
316 if ( !$this->loadFromCache() ) {
318 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
319 $this->loadFromFile();
320 } elseif ( $this->fileExists
) {
321 $this->saveToCache();
324 $this->dataLoaded
= true;
329 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
330 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
332 function upgradeRow() {
333 global $wgDBname, $wgSharedUploadDBname;
334 $fname = 'Image::upgradeRow';
335 $this->loadFromFile();
336 $dbw =& wfGetDB( DB_MASTER
);
338 if ( $this->fromSharedDirectory
) {
339 if ( !$wgSharedUploadDBname ) {
343 // Write to the other DB using selectDB, not database selectors
344 // This avoids breaking replication in MySQL
345 $dbw->selectDB( $wgSharedUploadDBname );
347 $dbw->update( 'image',
349 'img_width' => $this->width
,
350 'img_height' => $this->height
,
351 'img_bits' => $this->bits
,
352 'img_type' => $this->type
,
353 'img_metadata' => $this->exif
,
354 ), array( 'img_name' => $this->name
), $fname
356 if ( $this->fromSharedDirectory
) {
357 $dbw->selectDB( $wgDBname );
362 * Return the name of this image
370 * Return the associated title object
373 function getTitle() {
378 * Return the URL of the image file
384 if($this->fileExists
) {
385 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
393 function getViewURL() {
394 if( $this->mustRender() ) {
395 return $this->createThumb( $this->getWidth() );
397 return $this->getURL();
402 * Return the image path of the image in the
403 * local file system as an absolute path
406 function getImagePath() {
408 return $this->imagePath
;
412 * Return the width of the image
414 * Returns -1 if the file specified is not a known image type
417 function getWidth() {
423 * Return the height of the image
425 * Returns -1 if the file specified is not a known image type
428 function getHeight() {
430 return $this->height
;
434 * Return the size of the image file, in bytes
443 * Return the type of the image
457 * Return the escapeLocalURL of this image
460 function getEscapeLocalURL() {
462 return $this->title
->escapeLocalURL();
466 * Return the escapeFullURL of this image
469 function getEscapeFullURL() {
471 return $this->title
->escapeFullURL();
475 * Return the URL of an image, provided its name.
477 * @param string $name Name of the image, without the leading "Image:"
478 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
482 function imageUrl( $name, $fromSharedDirectory = false ) {
483 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
484 if($fromSharedDirectory) {
486 $path = $wgSharedUploadPath;
488 $base = $wgUploadBaseUrl;
489 $path = $wgUploadPath;
491 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
492 return wfUrlencode( $url );
496 * Returns true if the image file exists on disk.
502 return $this->fileExists
;
509 function thumbUrl( $width, $subdir='thumb') {
510 global $wgUploadPath, $wgUploadBaseUrl,
511 $wgSharedUploadPath,$wgSharedUploadDirectory,
512 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
514 // Generate thumb.php URL if possible
518 if ( $this->fromSharedDirectory
) {
519 if ( $wgSharedThumbnailScriptPath ) {
520 $script = $wgSharedThumbnailScriptPath;
523 if ( $wgThumbnailScriptPath ) {
524 $script = $wgThumbnailScriptPath;
528 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
530 $name = $this->thumbName( $width );
531 if($this->fromSharedDirectory
) {
533 $path = $wgSharedUploadPath;
535 $base = $wgUploadBaseUrl;
536 $path = $wgUploadPath;
538 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
539 $url = "{$base}{$path}/{$subdir}" .
540 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
541 . $this->name
.'/'.$name;
542 $url = wfUrlencode( $url );
544 $url = "{$base}{$path}/{$subdir}/{$name}";
547 return array( $script !== false, $url );
551 * Return the file name of a thumbnail of the specified width
553 * @param integer $width Width of the thumbnail image
554 * @param boolean $shared Does the thumbnail come from the shared repository?
557 function thumbName( $width ) {
558 $thumb = $width."px-".$this->name
;
559 if( $this->extension
== 'svg' ) {
560 # Rasterize SVG vector images to PNG
567 * Create a thumbnail of the image having the specified width/height.
568 * The thumbnail will not be created if the width is larger than the
569 * image's width. Let the browser do the scaling in this case.
570 * The thumbnail is stored on disk and is only computed if the thumbnail
571 * file does not exist OR if it is older than the image.
574 * Keeps aspect ratio of original image. If both width and height are
575 * specified, the generated image will be no bigger than width x height,
576 * and will also have correct aspect ratio.
578 * @param integer $width maximum width of the generated thumbnail
579 * @param integer $height maximum height of the image (optional)
582 function createThumb( $width, $height=-1 ) {
583 $thumb = $this->getThumbnail( $width, $height );
584 if( is_null( $thumb ) ) return '';
585 return $thumb->getUrl();
589 * As createThumb, but returns a ThumbnailImage object. This can
590 * provide access to the actual file, the real size of the thumb,
591 * and can produce a convenient <img> tag for you.
593 * @param integer $width maximum width of the generated thumbnail
594 * @param integer $height maximum height of the image (optional)
595 * @return ThumbnailImage
598 function &getThumbnail( $width, $height=-1 ) {
599 if ( $height == -1 ) {
600 return $this->renderThumb( $width );
603 if ( $width < $this->width
) {
604 $thumbheight = $this->height
* $width / $this->width
;
605 $thumbwidth = $width;
607 $thumbheight = $this->height
;
608 $thumbwidth = $this->width
;
610 if ( $thumbheight > $height ) {
611 $thumbwidth = $thumbwidth * $height / $thumbheight;
612 $thumbheight = $height;
614 $thumb = $this->renderThumb( $thumbwidth );
615 if( is_null( $thumb ) ) {
616 $thumb = $this->iconThumb();
622 * @return ThumbnailImage
624 function iconThumb() {
625 global $wgStylePath, $wgStyleDirectory;
627 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
628 foreach( $try as $icon ) {
629 $path = '/common/images/' . $icon;
630 $filepath = $wgStyleDirectory . $path;
631 if( file_exists( $filepath ) ) {
632 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
639 * Create a thumbnail of the image having the specified width.
640 * The thumbnail will not be created if the width is larger than the
641 * image's width. Let the browser do the scaling in this case.
642 * The thumbnail is stored on disk and is only computed if the thumbnail
643 * file does not exist OR if it is older than the image.
644 * Returns an object which can return the pathname, URL, and physical
645 * pixel size of the thumbnail -- or null on failure.
647 * @return ThumbnailImage
650 function /* private */ renderThumb( $width, $useScript = true ) {
651 global $wgUseSquid, $wgInternalServer;
652 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
654 $width = IntVal( $width );
657 if ( ! $this->exists() )
659 # If there is no image, there will be no thumbnail
663 # Sanity check $width
669 if( $width > $this->width
&& !$this->mustRender() ) {
670 # Don't make an image bigger than the source
671 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
674 $height = floor( $this->height
* ( $width/$this->width
) );
676 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
677 if ( $isScriptUrl && $useScript ) {
678 // Use thumb.php to render the image
679 return new ThumbnailImage( $url, $width, $height );
682 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
683 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
685 if ( !file_exists( $thumbPath ) ) {
686 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
689 if ( file_exists( $oldThumbPath ) ) {
690 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
691 rename( $oldThumbPath, $thumbPath );
694 unlink( $oldThumbPath );
698 $this->reallyRenderThumb( $thumbPath, $width, $height );
701 # This has to be done after the image is updated and present for all machines on NFS,
702 # or else the old version might be stored into the squid again
704 if ( substr( $url, 0, 4 ) == 'http' ) {
705 $urlArr = array( $url );
707 $urlArr = array( $wgInternalServer.$url );
709 wfPurgeSquidServers($urlArr);
713 return new ThumbnailImage( $url, $width, $height, $thumbPath );
714 } // END OF function renderThumb
717 * Really render a thumbnail
721 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
722 global $wgSVGConverters, $wgSVGConverter,
723 $wgUseImageMagick, $wgImageMagickConvertCommand;
727 if( $this->extension
== 'svg' ) {
728 global $wgSVGConverters, $wgSVGConverter;
729 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
730 global $wgSVGConverterPath;
732 array( '$path/', '$width', '$input', '$output' ),
733 array( $wgSVGConverterPath,
735 escapeshellarg( $this->imagePath
),
736 escapeshellarg( $thumbPath ) ),
737 $wgSVGConverters[$wgSVGConverter] );
738 $conv = shell_exec( $cmd );
742 } elseif ( $wgUseImageMagick ) {
744 # Specify white background color, will be used for transparent images
745 # in Internet Explorer/Windows instead of default black.
746 $cmd = $wgImageMagickConvertCommand .
747 " -quality 85 -background white -geometry {$width} ".
748 escapeshellarg($this->imagePath
) . " " .
749 escapeshellarg($thumbPath);
750 $conv = shell_exec( $cmd );
752 # Use PHP's builtin GD library functions.
754 # First find out what kind of file this is, and select the correct
755 # input routine for this.
759 switch( $this->type
) {
761 $src_image = imagecreatefromgif( $this->imagePath
);
764 $src_image = imagecreatefromjpeg( $this->imagePath
);
768 $src_image = imagecreatefrompng( $this->imagePath
);
769 $truecolor = ( $this->bits
> 8 );
771 case 15: # WBMP for WML
772 $src_image = imagecreatefromwbmp( $this->imagePath
);
775 $src_image = imagecreatefromxbm( $this->imagePath
);
778 return 'Image type not supported';
782 $dst_image = imagecreatetruecolor( $width, $height );
784 $dst_image = imagecreate( $width, $height );
786 imagecopyresampled( $dst_image, $src_image,
788 $width, $height, $this->width
, $this->height
);
789 switch( $this->type
) {
794 imagepng( $dst_image, $thumbPath );
797 imageinterlace( $dst_image );
798 imagejpeg( $dst_image, $thumbPath, 95 );
803 imagedestroy( $dst_image );
804 imagedestroy( $src_image );
807 # Check for zero-sized thumbnails. Those can be generated when
808 # no disk space is available or some other error occurs
810 if( file_exists( $thumbPath ) ) {
811 $thumbstat = stat( $thumbPath );
812 if( $thumbstat['size'] == 0 ) {
813 unlink( $thumbPath );
819 * Get all thumbnail names previously generated for this image
821 function getThumbnails( $shared = false ) {
822 if ( Image
::isHashed( $shared ) ) {
825 $dir = wfImageThumbDir( $this->name
, $shared );
827 // This generates an error on failure, hence the @
828 $handle = @opendir
( $dir );
831 while ( false !== ( $file = readdir($handle) ) ) {
832 if ( $file{0} != '.' ) {
846 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
848 function purgeCache( $archiveFiles = array(), $shared = false ) {
849 global $wgInternalServer, $wgUseSquid;
851 // Refresh metadata cache
853 $this->loadFromFile();
854 $this->saveToCache();
857 $files = $this->getThumbnails( $shared );
858 $dir = wfImageThumbDir( $this->name
, $shared );
860 foreach ( $files as $file ) {
861 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
862 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
863 @unlink
( "$dir/$file" );
869 $urls[] = $wgInternalServer . $this->getViewURL();
870 foreach ( $archiveFiles as $file ) {
871 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
873 wfPurgeSquidServers( $urls );
878 * Return the image history of this image, line by line.
879 * starts with current version, then old versions.
880 * uses $this->historyLine to check which line to return:
881 * 0 return line for current version
882 * 1 query for old versions, return first one
883 * 2, ... return next old version from above query
887 function nextHistoryLine() {
888 $fname = 'Image::nextHistoryLine()';
889 $dbr =& wfGetDB( DB_SLAVE
);
890 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
891 $this->historyRes
= $dbr->select( 'image',
892 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
893 array( 'img_name' => $this->title
->getDBkey() ),
896 if ( 0 == wfNumRows( $this->historyRes
) ) {
899 } else if ( $this->historyLine
== 1 ) {
900 $this->historyRes
= $dbr->select( 'oldimage',
901 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
902 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
903 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
906 $this->historyLine ++
;
908 return $dbr->fetchObject( $this->historyRes
);
912 * Reset the history pointer to the first element of the history
915 function resetHistory() {
916 $this->historyLine
= 0;
920 * Return true if the file is of a type that can't be directly
921 * rendered by typical browsers and needs to be re-rasterized.
924 function mustRender() {
926 return ( $this->extension
== 'svg' );
930 * Return the full filesystem path to the file. Note that this does
931 * not mean that a file actually exists under that location.
933 * This path depends on whether directory hashing is active or not,
934 * i.e. whether the images are all found in the same directory,
935 * or in hashed paths like /images/3/3c.
938 * @param boolean $fromSharedDirectory Return the path to the file
939 * in a shared repository (see $wgUseSharedRepository and related
940 * options in DefaultSettings.php) instead of a local one.
943 function getFullPath( $fromSharedRepository = false ) {
944 global $wgUploadDirectory, $wgSharedUploadDirectory;
945 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
947 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
950 // $wgSharedUploadDirectory may be false, if thumb.php is used
952 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
964 function isHashed( $shared ) {
965 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
966 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
973 function isKnownImageExtension( $ext ) {
974 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
975 return in_array( $ext, $extensions );
979 * Record an image upload in the upload log and the image table
981 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
982 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
983 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
985 $fname = 'Image::recordUpload';
986 $dbw =& wfGetDB( DB_MASTER
);
988 # img_name must be unique
989 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
990 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
993 // Delete thumbnails and refresh the metadata cache
996 // Fail now if the image isn't there
997 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1001 if ( $wgUseCopyrightUpload ) {
1002 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1003 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1004 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1009 $now = $dbw->timestamp();
1011 # Test to see if the row exists using INSERT IGNORE
1012 # This avoids race conditions by locking the row until the commit, and also
1013 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1014 $dbw->insert( 'image',
1016 'img_name' => $this->name
,
1017 'img_size'=> $this->size
,
1018 'img_width' => $this->width
,
1019 'img_height' => $this->height
,
1020 'img_bits' => $this->bits
,
1021 'img_type' => $this->type
,
1022 'img_timestamp' => $now,
1023 'img_description' => $desc,
1024 'img_user' => $wgUser->getID(),
1025 'img_user_text' => $wgUser->getName(),
1026 'img_metadata' => $this->exif
,
1029 $descTitle = $this->getTitle();
1030 $purgeURLs = array();
1032 if ( $dbw->affectedRows() ) {
1033 # Successfully inserted, this is a new image
1034 $id = $descTitle->getArticleID();
1037 $article = new Article( $descTitle );
1038 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1041 # Collision, this is an update of an image
1042 # Insert previous contents into oldimage
1043 $dbw->insertSelect( 'oldimage', 'image',
1045 'oi_name' => 'img_name',
1046 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1047 'oi_size' => 'img_size',
1048 'oi_width' => 'img_width',
1049 'oi_height' => 'img_height',
1050 'oi_bits' => 'img_bits',
1051 'oi_type' => 'img_type',
1052 'oi_timestamp' => 'img_timestamp',
1053 'oi_description' => 'img_description',
1054 'oi_user' => 'img_user',
1055 'oi_user_text' => 'img_user_text',
1056 ), array( 'img_name' => $this->name
), $fname
1059 # Update the current image row
1060 $dbw->update( 'image',
1062 'img_size' => $this->size
,
1063 'img_width' => $this->width
,
1064 'img_height' => $this->height
,
1065 'img_bits' => $this->bits
,
1066 'img_type' => $this->type
,
1067 'img_timestamp' => $now,
1068 'img_user' => $wgUser->getID(),
1069 'img_user_text' => $wgUser->getName(),
1070 'img_description' => $desc,
1071 'img_metadata' => $this->exif
,
1072 ), array( /* WHERE */
1073 'img_name' => $this->name
1077 # Invalidate the cache for the description page
1078 $descTitle->invalidateCache();
1079 $purgeURLs[] = $descTitle->getInternalURL();
1082 # Invalidate cache for all pages using this image
1083 $linksTo = $this->getLinksTo();
1085 if ( $wgUseSquid ) {
1086 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1087 array_push( $wgPostCommitUpdateList, $u );
1089 Title
::touchArray( $linksTo );
1091 $log = new LogPage( 'upload' );
1092 $log->addEntry( 'upload', $descTitle, $desc );
1098 * Get an array of Title objects which are articles which use this image
1099 * Also adds their IDs to the link cache
1101 * This is mostly copied from Title::getLinksTo()
1103 function getLinksTo( $options = '' ) {
1104 global $wgLinkCache;
1105 $fname = 'Image::getLinksTo';
1106 wfProfileIn( $fname );
1109 $db =& wfGetDB( DB_MASTER
);
1111 $db =& wfGetDB( DB_SLAVE
);
1114 extract( $db->tableNames( 'page', 'imagelinks' ) );
1115 $encName = $db->addQuotes( $this->name
);
1116 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1117 $res = $db->query( $sql, $fname );
1120 if ( $db->numRows( $res ) ) {
1121 while ( $row = $db->fetchObject( $res ) ) {
1122 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1123 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1124 $retVal[] = $titleObj;
1128 $db->freeResult( $res );
1132 function retrieveExifData () {
1133 global $wgShowEXIF ;
1134 if ( ! $wgShowEXIF ) return array ();
1135 if ( $this->type
!== '2' ) return array ();
1137 $exif = exif_read_data( $this->imagePath
);
1138 $exif = $this->stripExifData( $exif );
1142 function getExifData () {
1143 global $wgRequest, $wgShowEXIF;
1145 if ( ! $wgShowEXIF ) return array ();
1147 $action = $wgRequest->getVal( 'action' ); # Allow forced updates
1149 $ret = unserialize ( $this->exif
);
1151 if ( count( $ret) == 0 ||
$action == 'purge' ) { # No EXIF data was stored for this image
1152 $this->updateExifData() ;
1153 $ret = unserialize ( $this->exif
) ;
1159 function updateExifData () {
1160 global $wgShowEXIF ;
1161 if ( ! $wgShowEXIF ) return ;
1162 if ( false === $this->getImagePath() ) return ; # Not a local image
1164 $fname = "Image:updateExifData" ;
1166 # Get EXIF data from image
1167 $exif = $this->retrieveExifData () ;
1168 $this->exif
= serialize ( $exif ) ;
1170 # Update EXIF data in database
1171 $dbw =& wfGetDB( DB_MASTER
);
1172 $dbw->update( 'image',
1173 array( 'img_metadata' => $this->exif
),
1174 array( 'img_name' => $this->name
),
1180 * Strip out potentially nasty exif data such as raw binaries
1181 * (thumbnails), these values are from version 2.2 of the EXIF
1182 * specification, note that I've commented some of them out, this is
1183 * because their Type is "UNDEFINED", meaning that they potentially
1184 * contain binary data.
1186 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
1187 * @link http://exif.org/specifications.html
1188 * @link http://exif.org/Exif2-2.PDF (see page 22 and 30)
1190 * @param array $exif
1193 function stripExifData( $exif = array() ) {
1196 'Make', # Image input equipment manufacturer
1197 'Model', # Image input equipment model
1198 'Software', # Software used
1199 'Artist', # Person who created the image
1200 'Copyright', # Copyright holder
1202 # Tags relating to image structure
1203 'ImageWidth', # Image width
1204 'ImageLength', # Image height
1205 'Orientation', # Orientation of image
1206 'SamplesPerPixel', # Number of components
1207 'PlanarConfiguration', # Image data arrangement
1208 'YCbCrSubSampling', # Subsampling ratio of Y to C
1209 'YCbCrPositioning', # Y and C positioning
1210 'XResolution', # Image resolution in width direction
1211 'YResolution', # Image resolution in height direction
1212 'ResolutionUnit', # Unit of X and Y resolution
1214 # Tags relating to recording offset
1215 'StripOffsets', # Image data location
1216 'RowsPerStrip', # Number of rows per strip
1217 'StripByteCounts', # Bytes per compressed strip
1218 'JPEGInterchangeFormat', # Offset to JPEG SOI
1219 'JPEGInterchangeFormatLength', # Bytes of JPEG data
1221 # Tags relating to image data characteristics
1222 'TransferFunction', # Transfer function
1223 'WhitePoint', # White point chromaticity
1224 'PrimaryChromaticities', # Chromaticities of primarities
1225 'YCbCrCoefficients', # Color space transformation matrix coefficients
1226 'ReferenceBlackWhite', # Pair of black and white reference values
1228 # Tags relating to version
1229 #'ExifVersion', # Exif version
1230 #'FlashpixVersion', # Supported Flashpix version
1232 # Tags relating to Image Data Characteristics
1233 'ColorSpace', # Color space information
1234 #'ComponentsConfiguration', # Meaning of each component
1235 'CompressedBitsPerPixel', # Image compression mode
1236 'PixelYDimension', # Valid image width
1237 'PixelXDimension', # Valind image height
1239 # Tags relating to User Information
1240 #'MakerNote', # Manufacturer notes
1241 #'UserComment', # User commentss
1243 # Tag relating to related file information
1244 #'RelatedSoundFile', # Related audio file
1247 'ImageUniqueID', # Unique image ID
1249 # Tags relating to picture-taking conditions
1250 'ExposureTime', # Exposure time
1251 'FNumber', # F Number
1252 'ExposureProgram', # Exposure Program
1253 'SpectralSensitivity', # Spectral sensitivity
1254 'ISOSpeedRatings', # ISO speed rating
1255 #'OECF', # Optoelectronic conversion factor
1256 'ShutterSpeedValue', # Shutter speed
1257 'ApertureValue', # Aperture
1258 'BrightnessValue', # Brightness
1259 'ExposureBiasValue', # Exposure bias
1260 'MaxApertureValue', # Maximum land aperture
1261 'SubjectDistance', # Subject distance
1262 'MeteringMode', # Metering mode
1263 'LightSource', # Light source
1265 'FocalLength', # Lens focal length
1266 'SubjectArea', # Subject area
1267 'FlashEnergy', # Flash energy
1268 #'SpartialFrequencyResponse', # Spartial frequency response
1269 'FocalPlaneXRessolution', # Focal plane X resolution
1270 'FocalPlaneYRessolution', # Focal plane Y resolution
1271 'FocalPlaneResolutionUnit', # Focal plane resolution unit
1272 'SubjectLocation', # Subject location
1273 'ExposureIndex', # Exposure index
1274 'SensingMethod', # Sensing method
1275 #'FileSource', # File source
1276 #'SceneType', # Scene type
1277 #'CFAPattern', # CFA pattern
1278 'CustomRendered', # Custom image processing
1279 'ExposureMode', # Exposure mode
1280 'WhiteBalance', # White Balance
1281 'DigitalZoomRatio', # Digital zoom ration
1282 'FocalLengthIn35mmFilm', # Focal length in 35 mm film
1283 'SceneCaptureType', # Scene capture type
1284 'GainControl', # Scene control
1285 'Contrast', # Contrast
1286 'Saturation', # Saturation
1287 'Sharpness', # Sharpness
1288 #'DeviceSettingDescription', # Desice settings description
1289 'SubjectDistanceRange', # Subject distance range
1291 # TODO: GPS attribute information on page 52 of the spec
1295 foreach ($whitelist as $tag) {
1296 if ( array_key_exists($tag, $exif) ) {
1297 $new[$tag] = $exif[$tag];
1309 * Returns the image directory of an image
1310 * If the directory does not exist, it is created.
1311 * The result is an absolute path.
1313 * This function is called from thumb.php before Setup.php is included
1315 * @param string $fname file name of the image file
1318 function wfImageDir( $fname ) {
1319 global $wgUploadDirectory, $wgHashedUploadDirectory;
1321 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1323 $hash = md5( $fname );
1324 $oldumask = umask(0);
1325 $dest = $wgUploadDirectory . '/' . $hash{0};
1326 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1327 $dest .= '/' . substr( $hash, 0, 2 );
1328 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1335 * Returns the image directory of an image's thubnail
1336 * If the directory does not exist, it is created.
1337 * The result is an absolute path.
1339 * This function is called from thumb.php before Setup.php is included
1341 * @param string $fname file name of the original image file
1342 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1343 * @param boolean $shared (optional) use the shared upload directory
1346 function wfImageThumbDir( $fname, $shared = false ) {
1347 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1348 if ( Image
::isHashed( $shared ) ) {
1349 $dir = "$base/$fname";
1351 if ( !is_dir( $base ) ) {
1352 $oldumask = umask(0);
1353 @mkdir
( $base, 0777 );
1357 if ( ! is_dir( $dir ) ) {
1358 $oldumask = umask(0);
1359 @mkdir
( $dir, 0777 );
1370 * Old thumbnail directory, kept for conversion
1372 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1373 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1377 * Returns the image directory of an image's old version
1378 * If the directory does not exist, it is created.
1379 * The result is an absolute path.
1381 * This function is called from thumb.php before Setup.php is included
1383 * @param string $fname file name of the thumbnail file, including file size prefix
1384 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1385 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1388 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1389 global $wgUploadDirectory, $wgHashedUploadDirectory,
1390 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1391 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1392 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1393 if (!$hashdir) { return $dir.'/'.$subdir; }
1394 $hash = md5( $fname );
1395 $oldumask = umask(0);
1397 # Suppress warning messages here; if the file itself can't
1398 # be written we'll worry about it then.
1399 wfSuppressWarnings();
1401 $archive = $dir.'/'.$subdir;
1402 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1403 $archive .= '/' . $hash{0};
1404 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1405 $archive .= '/' . substr( $hash, 0, 2 );
1406 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1408 wfRestoreWarnings();
1415 * Return the hash path component of an image path (URL or filesystem),
1416 * e.g. "/3/3c/", or just "/" if hashing is not used.
1418 * @param $dbkey The filesystem / database name of the file
1419 * @param $fromSharedDirectory Use the shared file repository? It may
1420 * use different hash settings from the local one.
1422 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1423 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1424 global $wgHashedUploadDirectory;
1426 if( Image
::isHashed( $fromSharedDirectory ) ) {
1427 $hash = md5($dbkey);
1428 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1435 * Returns the image URL of an image's old version
1437 * @param string $fname file name of the image file
1438 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1441 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1442 global $wgUploadPath, $wgHashedUploadDirectory;
1444 if ($wgHashedUploadDirectory) {
1445 $hash = md5( substr( $name, 15) );
1446 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1447 substr( $hash, 0, 2 ) . '/'.$name;
1449 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1451 return wfUrlencode($url);
1455 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1456 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1458 * @param string $length
1459 * @return int Length in pixels
1461 function wfScaleSVGUnit( $length ) {
1462 static $unitLength = array(
1469 '' => 1.0, // "User units" pixels by default
1470 '%' => 2.0, // Fake it!
1472 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1473 $length = FloatVal( $matches[1] );
1474 $unit = $matches[2];
1475 return round( $length * $unitLength[$unit] );
1478 return round( FloatVal( $length ) );
1483 * Compatible with PHP getimagesize()
1484 * @todo support gzipped SVGZ
1485 * @todo check XML more carefully
1486 * @todo sensible defaults
1488 * @param string $filename
1491 function wfGetSVGsize( $filename ) {
1495 // Read a chunk of the file
1496 $f = fopen( $filename, "rt" );
1497 if( !$f ) return false;
1498 $chunk = fread( $f, 4096 );
1501 // Uber-crappy hack! Run through a real XML parser.
1502 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1506 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1507 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1509 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1510 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1513 return array( $width, $height, 'SVG',
1514 "width=\"$width\" height=\"$height\"" );
1518 * Determine if an image exists on the 'bad image list'
1520 * @param string $name The image to check
1523 function wfIsBadImage( $name ) {
1525 static $titleList = false;
1526 if ( $titleList === false ) {
1527 $titleList = array();
1529 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1530 foreach ( $lines as $line ) {
1531 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1532 $t = Title
::newFromText( $m[1] );
1533 $titleList[$t->getDBkey()] = 1;
1538 return array_key_exists( $name, $titleList );
1544 * Wrapper class for thumbnail images
1545 * @package MediaWiki
1547 class ThumbnailImage
{
1549 * @param string $path Filesystem path to the thumb
1550 * @param string $url URL path to the thumb
1553 function ThumbnailImage( $url, $width, $height, $path = false ) {
1555 $this->width
= $width;
1556 $this->height
= $height;
1557 $this->path
= $path;
1561 * @return string The thumbnail URL
1568 * Return HTML <img ... /> tag for the thumbnail, will include
1569 * width and height attributes and a blank alt text (as required).
1571 * You can set or override additional attributes by passing an
1572 * associative array of name => data pairs. The data will be escaped
1573 * for HTML output, so should be in plaintext.
1575 * @param array $attribs
1579 function toHtml( $attribs = array() ) {
1580 $attribs['src'] = $this->url
;
1581 $attribs['width'] = $this->width
;
1582 $attribs['height'] = $this->height
;
1583 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1586 foreach( $attribs as $name => $data ) {
1587 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';