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 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
50 * Create an Image object from an image name
52 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
55 function newFromName( $name ) {
56 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
57 return new Image( $title );
61 * Obsolete factory function, use constructor
63 function newFromTitle( $title ) {
64 return new Image( $title );
67 function Image( $title ) {
68 $this->title
=& $title;
69 $this->name
= $title->getDBkey();
70 $this->exif
= serialize ( array() ) ;
72 $n = strrpos( $this->name
, '.' );
73 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
74 $this->historyLine
= 0;
76 $this->dataLoaded
= false;
80 * Get the memcached keys
81 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
83 function getCacheKeys( $shared = false ) {
84 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
87 $hashedName = md5($this->name
);
88 $keys = array( "$wgDBname:Image:$hashedName" );
89 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
90 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
96 * Try to load image metadata from memcached. Returns true on success.
98 function loadFromCache() {
99 global $wgUseSharedUploads, $wgMemc;
100 $fname = 'Image::loadFromMemcached';
101 wfProfileIn( $fname );
102 $this->dataLoaded
= false;
103 $keys = $this->getCacheKeys();
104 $cachedValues = $wgMemc->get( $keys[0] );
106 // Check if the key existed and belongs to this version of MediaWiki
107 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
108 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
109 # if this is shared file, we need to check if image
110 # in shared repository has not changed
111 if ( isset( $keys[1] ) ) {
112 $commonsCachedValues = $wgMemc->get( $keys[1] );
113 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
114 $this->name
= $commonsCachedValues['name'];
115 $this->imagePath
= $commonsCachedValues['imagePath'];
116 $this->fileExists
= $commonsCachedValues['fileExists'];
117 $this->width
= $commonsCachedValues['width'];
118 $this->height
= $commonsCachedValues['height'];
119 $this->bits
= $commonsCachedValues['bits'];
120 $this->type
= $commonsCachedValues['type'];
121 $this->exif
= $commonsCachedValues['exif'];
122 $this->size
= $commonsCachedValues['size'];
123 $this->fromSharedDirectory
= true;
124 $this->dataLoaded
= true;
125 $this->imagePath
= $this->getFullPath(true);
130 $this->name
= $cachedValues['name'];
131 $this->imagePath
= $cachedValues['imagePath'];
132 $this->fileExists
= $cachedValues['fileExists'];
133 $this->width
= $cachedValues['width'];
134 $this->height
= $cachedValues['height'];
135 $this->bits
= $cachedValues['bits'];
136 $this->type
= $cachedValues['type'];
137 $this->exif
= $cachedValues['exif'];
138 $this->size
= $cachedValues['size'];
139 $this->fromSharedDirectory
= false;
140 $this->dataLoaded
= true;
141 $this->imagePath
= $this->getFullPath();
145 wfProfileOut( $fname );
146 return $this->dataLoaded
;
150 * Save the image metadata to memcached
152 function saveToCache() {
155 // We can't cache metadata for non-existent files, because if the file later appears
156 // in commons, the local keys won't be purged.
157 if ( $this->fileExists
) {
158 $keys = $this->getCacheKeys();
160 $cachedValues = array('name' => $this->name
,
161 'imagePath' => $this->imagePath
,
162 'fileExists' => $this->fileExists
,
163 'fromShared' => $this->fromSharedDirectory
,
164 'width' => $this->width
,
165 'height' => $this->height
,
166 'bits' => $this->bits
,
167 'type' => $this->type
,
168 'exif' => $this->exif
,
169 'size' => $this->size
);
171 $wgMemc->set( $keys[0], $cachedValues );
176 * Load metadata from the file itself
178 function loadFromFile() {
179 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
180 $fname = 'Image::loadFromFile';
181 wfProfileIn( $fname );
182 $this->imagePath
= $this->getFullPath();
183 $this->fileExists
= file_exists( $this->imagePath
);
184 $this->fromSharedDirectory
= false;
187 # If the file is not found, and a shared upload directory is used, look for it there.
188 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
189 # In case we're on a wgCapitalLinks=false wiki, we
190 # capitalize the first letter of the filename before
191 # looking it up in the shared repository.
192 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
193 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
194 if ( $this->fileExists
) {
195 $this->name
= $sharedImage->name
;
196 $this->imagePath
= $this->getFullPath(true);
197 $this->fromSharedDirectory
= true;
201 if ( $this->fileExists
) {
203 $this->size
= filesize( $this->imagePath
);
206 # Don't try to get the width and height of sound and video files, that's bad for performance
207 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
209 } elseif( $this->extension
== 'svg' ) {
210 wfSuppressWarnings();
211 $gis = wfGetSVGsize( $this->imagePath
);
214 wfSuppressWarnings();
215 $gis = getimagesize( $this->imagePath
);
219 if( $gis === false ) {
224 $this->exif
= serialize ( array() ) ;
226 $this->width
= $gis[0];
227 $this->height
= $gis[1];
228 $this->type
= $gis[2];
229 $this->exif
= serialize ( $this->retrieveExifData() ) ;
230 if ( isset( $gis['bits'] ) ) {
231 $this->bits
= $gis['bits'];
236 $this->dataLoaded
= true;
237 wfProfileOut( $fname );
241 * Load image metadata from the DB
243 function loadFromDB() {
244 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
245 $fname = 'Image::loadFromDB';
246 wfProfileIn( $fname );
248 $dbr =& wfGetDB( DB_SLAVE
);
249 $row = $dbr->selectRow( 'image',
250 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
251 array( 'img_name' => $this->name
), $fname );
253 $this->fromSharedDirectory
= false;
254 $this->fileExists
= true;
255 $this->loadFromRow( $row );
256 $this->imagePath
= $this->getFullPath();
257 // Check for rows from a previous schema, quietly upgrade them
258 if ( $this->type
== -1 ) {
261 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
262 # In case we're on a wgCapitalLinks=false wiki, we
263 # capitalize the first letter of the filename before
264 # looking it up in the shared repository.
265 $name = $wgLang->ucfirst($this->name
);
267 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
268 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
269 array( 'img_name' => $name ), $fname );
271 $this->fromSharedDirectory
= true;
272 $this->fileExists
= true;
273 $this->imagePath
= $this->getFullPath(true);
275 $this->loadFromRow( $row );
277 // Check for rows from a previous schema, quietly upgrade them
278 if ( $this->type
== -1 ) {
290 $this->fileExists
= false;
291 $this->fromSharedDirectory
= false;
292 $this->exif
= serialize ( array() ) ;
295 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
296 $this->dataLoaded
= true;
300 * Load image metadata from a DB result row
302 function loadFromRow( &$row ) {
303 $this->size
= $row->img_size
;
304 $this->width
= $row->img_width
;
305 $this->height
= $row->img_height
;
306 $this->bits
= $row->img_bits
;
307 $this->type
= $row->img_type
;
308 $this->exif
= $row->img_metadata
;
309 if ( $this->exif
== "" ) $this->exif
= serialize ( array() ) ;
310 $this->dataLoaded
= true;
314 * Load image metadata from cache or DB, unless already loaded
317 global $wgSharedUploadDBname, $wgUseSharedUploads;
318 if ( !$this->dataLoaded
) {
319 if ( !$this->loadFromCache() ) {
321 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
322 $this->loadFromFile();
323 } elseif ( $this->fileExists
) {
324 $this->saveToCache();
327 $this->dataLoaded
= true;
332 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
333 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
335 function upgradeRow() {
336 global $wgDBname, $wgSharedUploadDBname;
337 $fname = 'Image::upgradeRow';
338 $this->loadFromFile();
339 $dbw =& wfGetDB( DB_MASTER
);
341 if ( $this->fromSharedDirectory
) {
342 if ( !$wgSharedUploadDBname ) {
346 // Write to the other DB using selectDB, not database selectors
347 // This avoids breaking replication in MySQL
348 $dbw->selectDB( $wgSharedUploadDBname );
350 $dbw->update( 'image',
352 'img_width' => $this->width
,
353 'img_height' => $this->height
,
354 'img_bits' => $this->bits
,
355 'img_type' => $this->type
,
356 'img_metadata' => $this->exif
,
357 ), array( 'img_name' => $this->name
), $fname
359 if ( $this->fromSharedDirectory
) {
360 $dbw->selectDB( $wgDBname );
365 * Return the name of this image
373 * Return the associated title object
376 function getTitle() {
381 * Return the URL of the image file
387 if($this->fileExists
) {
388 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
396 function getViewURL() {
397 if( $this->mustRender() ) {
398 return $this->createThumb( $this->getWidth() );
400 return $this->getURL();
405 * Return the image path of the image in the
406 * local file system as an absolute path
409 function getImagePath() {
411 return $this->imagePath
;
415 * Return the width of the image
417 * Returns -1 if the file specified is not a known image type
420 function getWidth() {
426 * Return the height of the image
428 * Returns -1 if the file specified is not a known image type
431 function getHeight() {
433 return $this->height
;
437 * Return the size of the image file, in bytes
446 * Return the type of the image
460 * Return the escapeLocalURL of this image
463 function getEscapeLocalURL() {
465 return $this->title
->escapeLocalURL();
469 * Return the escapeFullURL of this image
472 function getEscapeFullURL() {
474 return $this->title
->escapeFullURL();
478 * Return the URL of an image, provided its name.
480 * @param string $name Name of the image, without the leading "Image:"
481 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
485 function imageUrl( $name, $fromSharedDirectory = false ) {
486 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
487 if($fromSharedDirectory) {
489 $path = $wgSharedUploadPath;
491 $base = $wgUploadBaseUrl;
492 $path = $wgUploadPath;
494 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
495 return wfUrlencode( $url );
499 * Returns true if the image file exists on disk.
505 return $this->fileExists
;
512 function thumbUrl( $width, $subdir='thumb') {
513 global $wgUploadPath, $wgUploadBaseUrl,
514 $wgSharedUploadPath,$wgSharedUploadDirectory,
515 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
517 // Generate thumb.php URL if possible
521 if ( $this->fromSharedDirectory
) {
522 if ( $wgSharedThumbnailScriptPath ) {
523 $script = $wgSharedThumbnailScriptPath;
526 if ( $wgThumbnailScriptPath ) {
527 $script = $wgThumbnailScriptPath;
531 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
533 $name = $this->thumbName( $width );
534 if($this->fromSharedDirectory
) {
536 $path = $wgSharedUploadPath;
538 $base = $wgUploadBaseUrl;
539 $path = $wgUploadPath;
541 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
542 $url = "{$base}{$path}/{$subdir}" .
543 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
544 . $this->name
.'/'.$name;
545 $url = wfUrlencode( $url );
547 $url = "{$base}{$path}/{$subdir}/{$name}";
550 return array( $script !== false, $url );
554 * Return the file name of a thumbnail of the specified width
556 * @param integer $width Width of the thumbnail image
557 * @param boolean $shared Does the thumbnail come from the shared repository?
560 function thumbName( $width ) {
561 $thumb = $width."px-".$this->name
;
562 if( $this->extension
== 'svg' ) {
563 # Rasterize SVG vector images to PNG
570 * Create a thumbnail of the image having the specified width/height.
571 * The thumbnail will not be created if the width is larger than the
572 * image's width. Let the browser do the scaling in this case.
573 * The thumbnail is stored on disk and is only computed if the thumbnail
574 * file does not exist OR if it is older than the image.
577 * Keeps aspect ratio of original image. If both width and height are
578 * specified, the generated image will be no bigger than width x height,
579 * and will also have correct aspect ratio.
581 * @param integer $width maximum width of the generated thumbnail
582 * @param integer $height maximum height of the image (optional)
585 function createThumb( $width, $height=-1 ) {
586 $thumb = $this->getThumbnail( $width, $height );
587 if( is_null( $thumb ) ) return '';
588 return $thumb->getUrl();
592 * As createThumb, but returns a ThumbnailImage object. This can
593 * provide access to the actual file, the real size of the thumb,
594 * and can produce a convenient <img> tag for you.
596 * @param integer $width maximum width of the generated thumbnail
597 * @param integer $height maximum height of the image (optional)
598 * @return ThumbnailImage
601 function &getThumbnail( $width, $height=-1 ) {
602 if ( $height == -1 ) {
603 return $this->renderThumb( $width );
606 if ( $width < $this->width
) {
607 $thumbheight = $this->height
* $width / $this->width
;
608 $thumbwidth = $width;
610 $thumbheight = $this->height
;
611 $thumbwidth = $this->width
;
613 if ( $thumbheight > $height ) {
614 $thumbwidth = $thumbwidth * $height / $thumbheight;
615 $thumbheight = $height;
617 $thumb = $this->renderThumb( $thumbwidth );
618 if( is_null( $thumb ) ) {
619 $thumb = $this->iconThumb();
625 * @return ThumbnailImage
627 function iconThumb() {
628 global $wgStylePath, $wgStyleDirectory;
630 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
631 foreach( $try as $icon ) {
632 $path = '/common/images/' . $icon;
633 $filepath = $wgStyleDirectory . $path;
634 if( file_exists( $filepath ) ) {
635 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
642 * Create a thumbnail of the image having the specified width.
643 * The thumbnail will not be created if the width is larger than the
644 * image's width. Let the browser do the scaling in this case.
645 * The thumbnail is stored on disk and is only computed if the thumbnail
646 * file does not exist OR if it is older than the image.
647 * Returns an object which can return the pathname, URL, and physical
648 * pixel size of the thumbnail -- or null on failure.
650 * @return ThumbnailImage
653 function renderThumb( $width, $useScript = true ) {
654 global $wgUseSquid, $wgInternalServer;
655 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
657 $width = IntVal( $width );
660 if ( ! $this->exists() )
662 # If there is no image, there will be no thumbnail
666 # Sanity check $width
672 if( $width > $this->width
&& !$this->mustRender() ) {
673 # Don't make an image bigger than the source
674 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
677 $height = floor( $this->height
* ( $width/$this->width
) );
679 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
680 if ( $isScriptUrl && $useScript ) {
681 // Use thumb.php to render the image
682 return new ThumbnailImage( $url, $width, $height );
685 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
686 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
688 if ( !file_exists( $thumbPath ) ) {
689 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
692 if ( file_exists( $oldThumbPath ) ) {
693 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
694 rename( $oldThumbPath, $thumbPath );
697 unlink( $oldThumbPath );
701 $this->reallyRenderThumb( $thumbPath, $width, $height );
704 # This has to be done after the image is updated and present for all machines on NFS,
705 # or else the old version might be stored into the squid again
707 if ( substr( $url, 0, 4 ) == 'http' ) {
708 $urlArr = array( $url );
710 $urlArr = array( $wgInternalServer.$url );
712 wfPurgeSquidServers($urlArr);
716 return new ThumbnailImage( $url, $width, $height, $thumbPath );
717 } // END OF function renderThumb
720 * Really render a thumbnail
724 function reallyRenderThumb( $thumbPath, $width, $height ) {
725 global $wgSVGConverters, $wgSVGConverter,
726 $wgUseImageMagick, $wgImageMagickConvertCommand;
730 if( $this->extension
== 'svg' ) {
731 global $wgSVGConverters, $wgSVGConverter;
732 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
733 global $wgSVGConverterPath;
735 array( '$path/', '$width', '$input', '$output' ),
736 array( $wgSVGConverterPath,
738 escapeshellarg( $this->imagePath
),
739 escapeshellarg( $thumbPath ) ),
740 $wgSVGConverters[$wgSVGConverter] );
741 $conv = shell_exec( $cmd );
745 } elseif ( $wgUseImageMagick ) {
747 # Specify white background color, will be used for transparent images
748 # in Internet Explorer/Windows instead of default black.
749 $cmd = $wgImageMagickConvertCommand .
750 " -quality 85 -background white -geometry {$width} ".
751 escapeshellarg($this->imagePath
) . " " .
752 escapeshellarg($thumbPath);
753 $conv = shell_exec( $cmd );
755 # Use PHP's builtin GD library functions.
757 # First find out what kind of file this is, and select the correct
758 # input routine for this.
762 switch( $this->type
) {
764 $src_image = imagecreatefromgif( $this->imagePath
);
767 $src_image = imagecreatefromjpeg( $this->imagePath
);
771 $src_image = imagecreatefrompng( $this->imagePath
);
772 $truecolor = ( $this->bits
> 8 );
774 case 15: # WBMP for WML
775 $src_image = imagecreatefromwbmp( $this->imagePath
);
778 $src_image = imagecreatefromxbm( $this->imagePath
);
781 return 'Image type not supported';
785 $dst_image = imagecreatetruecolor( $width, $height );
787 $dst_image = imagecreate( $width, $height );
789 imagecopyresampled( $dst_image, $src_image,
791 $width, $height, $this->width
, $this->height
);
792 switch( $this->type
) {
797 imagepng( $dst_image, $thumbPath );
800 imageinterlace( $dst_image );
801 imagejpeg( $dst_image, $thumbPath, 95 );
806 imagedestroy( $dst_image );
807 imagedestroy( $src_image );
810 # Check for zero-sized thumbnails. Those can be generated when
811 # no disk space is available or some other error occurs
813 if( file_exists( $thumbPath ) ) {
814 $thumbstat = stat( $thumbPath );
815 if( $thumbstat['size'] == 0 ) {
816 unlink( $thumbPath );
822 * Get all thumbnail names previously generated for this image
824 function getThumbnails( $shared = false ) {
825 if ( Image
::isHashed( $shared ) ) {
828 $dir = wfImageThumbDir( $this->name
, $shared );
830 // This generates an error on failure, hence the @
831 $handle = @opendir
( $dir );
834 while ( false !== ( $file = readdir($handle) ) ) {
835 if ( $file{0} != '.' ) {
849 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
851 function purgeCache( $archiveFiles = array(), $shared = false ) {
852 global $wgInternalServer, $wgUseSquid;
854 // Refresh metadata cache
856 $this->loadFromFile();
857 $this->saveToCache();
860 $files = $this->getThumbnails( $shared );
861 $dir = wfImageThumbDir( $this->name
, $shared );
863 foreach ( $files as $file ) {
864 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
865 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
866 @unlink
( "$dir/$file" );
872 $urls[] = $wgInternalServer . $this->getViewURL();
873 foreach ( $archiveFiles as $file ) {
874 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
876 wfPurgeSquidServers( $urls );
881 * Return the image history of this image, line by line.
882 * starts with current version, then old versions.
883 * uses $this->historyLine to check which line to return:
884 * 0 return line for current version
885 * 1 query for old versions, return first one
886 * 2, ... return next old version from above query
890 function nextHistoryLine() {
891 $fname = 'Image::nextHistoryLine()';
892 $dbr =& wfGetDB( DB_SLAVE
);
893 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
894 $this->historyRes
= $dbr->select( 'image',
895 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
896 array( 'img_name' => $this->title
->getDBkey() ),
899 if ( 0 == wfNumRows( $this->historyRes
) ) {
902 } else if ( $this->historyLine
== 1 ) {
903 $this->historyRes
= $dbr->select( 'oldimage',
904 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
905 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
906 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
909 $this->historyLine ++
;
911 return $dbr->fetchObject( $this->historyRes
);
915 * Reset the history pointer to the first element of the history
918 function resetHistory() {
919 $this->historyLine
= 0;
923 * Return true if the file is of a type that can't be directly
924 * rendered by typical browsers and needs to be re-rasterized.
927 function mustRender() {
929 return ( $this->extension
== 'svg' );
933 * Return the full filesystem path to the file. Note that this does
934 * not mean that a file actually exists under that location.
936 * This path depends on whether directory hashing is active or not,
937 * i.e. whether the images are all found in the same directory,
938 * or in hashed paths like /images/3/3c.
941 * @param boolean $fromSharedDirectory Return the path to the file
942 * in a shared repository (see $wgUseSharedRepository and related
943 * options in DefaultSettings.php) instead of a local one.
946 function getFullPath( $fromSharedRepository = false ) {
947 global $wgUploadDirectory, $wgSharedUploadDirectory;
948 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
950 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
953 // $wgSharedUploadDirectory may be false, if thumb.php is used
955 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
967 function isHashed( $shared ) {
968 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
969 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
976 function isKnownImageExtension( $ext ) {
977 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
978 return in_array( $ext, $extensions );
982 * Record an image upload in the upload log and the image table
984 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
985 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
986 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
988 $fname = 'Image::recordUpload';
989 $dbw =& wfGetDB( DB_MASTER
);
991 # img_name must be unique
992 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
993 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
996 // Delete thumbnails and refresh the metadata cache
999 // Fail now if the image isn't there
1000 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1004 if ( $wgUseCopyrightUpload ) {
1005 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1006 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1007 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1012 $now = $dbw->timestamp();
1014 # Test to see if the row exists using INSERT IGNORE
1015 # This avoids race conditions by locking the row until the commit, and also
1016 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1017 $dbw->insert( 'image',
1019 'img_name' => $this->name
,
1020 'img_size'=> $this->size
,
1021 'img_width' => $this->width
,
1022 'img_height' => $this->height
,
1023 'img_bits' => $this->bits
,
1024 'img_type' => $this->type
,
1025 'img_timestamp' => $now,
1026 'img_description' => $desc,
1027 'img_user' => $wgUser->getID(),
1028 'img_user_text' => $wgUser->getName(),
1029 'img_metadata' => $this->exif
,
1032 $descTitle = $this->getTitle();
1033 $purgeURLs = array();
1035 if ( $dbw->affectedRows() ) {
1036 # Successfully inserted, this is a new image
1037 $id = $descTitle->getArticleID();
1040 $article = new Article( $descTitle );
1041 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1044 # Collision, this is an update of an image
1045 # Insert previous contents into oldimage
1046 $dbw->insertSelect( 'oldimage', 'image',
1048 'oi_name' => 'img_name',
1049 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1050 'oi_size' => 'img_size',
1051 'oi_width' => 'img_width',
1052 'oi_height' => 'img_height',
1053 'oi_bits' => 'img_bits',
1054 'oi_type' => 'img_type',
1055 'oi_timestamp' => 'img_timestamp',
1056 'oi_description' => 'img_description',
1057 'oi_user' => 'img_user',
1058 'oi_user_text' => 'img_user_text',
1059 ), array( 'img_name' => $this->name
), $fname
1062 # Update the current image row
1063 $dbw->update( 'image',
1065 'img_size' => $this->size
,
1066 'img_width' => $this->width
,
1067 'img_height' => $this->height
,
1068 'img_bits' => $this->bits
,
1069 'img_type' => $this->type
,
1070 'img_timestamp' => $now,
1071 'img_user' => $wgUser->getID(),
1072 'img_user_text' => $wgUser->getName(),
1073 'img_description' => $desc,
1074 'img_metadata' => $this->exif
,
1075 ), array( /* WHERE */
1076 'img_name' => $this->name
1080 # Invalidate the cache for the description page
1081 $descTitle->invalidateCache();
1082 $purgeURLs[] = $descTitle->getInternalURL();
1085 # Invalidate cache for all pages using this image
1086 $linksTo = $this->getLinksTo();
1088 if ( $wgUseSquid ) {
1089 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1090 array_push( $wgPostCommitUpdateList, $u );
1092 Title
::touchArray( $linksTo );
1094 $log = new LogPage( 'upload' );
1095 $log->addEntry( 'upload', $descTitle, $desc );
1101 * Get an array of Title objects which are articles which use this image
1102 * Also adds their IDs to the link cache
1104 * This is mostly copied from Title::getLinksTo()
1106 function getLinksTo( $options = '' ) {
1107 global $wgLinkCache;
1108 $fname = 'Image::getLinksTo';
1109 wfProfileIn( $fname );
1112 $db =& wfGetDB( DB_MASTER
);
1114 $db =& wfGetDB( DB_SLAVE
);
1117 extract( $db->tableNames( 'page', 'imagelinks' ) );
1118 $encName = $db->addQuotes( $this->name
);
1119 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1120 $res = $db->query( $sql, $fname );
1123 if ( $db->numRows( $res ) ) {
1124 while ( $row = $db->fetchObject( $res ) ) {
1125 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1126 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1127 $retVal[] = $titleObj;
1131 $db->freeResult( $res );
1135 function retrieveExifData () {
1136 global $wgShowEXIF ;
1137 if ( ! $wgShowEXIF ) return array ();
1138 if ( $this->type
!== '2' ) return array ();
1140 $exif = exif_read_data( $this->imagePath
);
1143 $valid = $obj->mValidExif
;
1144 foreach($exif as $k => $v) {
1145 if ( !in_array($k, $valid) ||
!$obj->validate($k, $v) )
1151 function getExifData () {
1154 $ret = unserialize ( $this->exif
);
1156 if ( count( $ret) == 0 ||
$wgRequest->getVal( 'action' ) == 'purge' ) { # No EXIF data was stored for this image
1157 $this->updateExifData() ;
1158 $ret = unserialize ( $this->exif
) ;
1164 function updateExifData () {
1165 global $wgShowEXIF ;
1166 if ( ! $wgShowEXIF ) return ;
1167 if ( false === $this->getImagePath() ) return ; # Not a local image
1169 $fname = "Image:updateExifData" ;
1171 # Get EXIF data from image
1172 $exif = $this->retrieveExifData () ;
1173 $this->exif
= serialize ( $exif ) ;
1175 # Update EXIF data in database
1176 $dbw =& wfGetDB( DB_MASTER
);
1177 $dbw->update( 'image',
1178 array( 'img_metadata' => $this->exif
),
1179 array( 'img_name' => $this->name
),
1188 * Returns the image directory of an image
1189 * If the directory does not exist, it is created.
1190 * The result is an absolute path.
1192 * This function is called from thumb.php before Setup.php is included
1194 * @param string $fname file name of the image file
1197 function wfImageDir( $fname ) {
1198 global $wgUploadDirectory, $wgHashedUploadDirectory;
1200 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1202 $hash = md5( $fname );
1203 $oldumask = umask(0);
1204 $dest = $wgUploadDirectory . '/' . $hash{0};
1205 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1206 $dest .= '/' . substr( $hash, 0, 2 );
1207 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1214 * Returns the image directory of an image's thubnail
1215 * If the directory does not exist, it is created.
1216 * The result is an absolute path.
1218 * This function is called from thumb.php before Setup.php is included
1220 * @param string $fname file name of the original image file
1221 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1222 * @param boolean $shared (optional) use the shared upload directory
1225 function wfImageThumbDir( $fname, $shared = false ) {
1226 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1227 if ( Image
::isHashed( $shared ) ) {
1228 $dir = "$base/$fname";
1230 if ( !is_dir( $base ) ) {
1231 $oldumask = umask(0);
1232 @mkdir
( $base, 0777 );
1236 if ( ! is_dir( $dir ) ) {
1237 $oldumask = umask(0);
1238 @mkdir
( $dir, 0777 );
1249 * Old thumbnail directory, kept for conversion
1251 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1252 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1256 * Returns the image directory of an image's old version
1257 * If the directory does not exist, it is created.
1258 * The result is an absolute path.
1260 * This function is called from thumb.php before Setup.php is included
1262 * @param string $fname file name of the thumbnail file, including file size prefix
1263 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1264 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1267 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1268 global $wgUploadDirectory, $wgHashedUploadDirectory,
1269 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1270 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1271 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1272 if (!$hashdir) { return $dir.'/'.$subdir; }
1273 $hash = md5( $fname );
1274 $oldumask = umask(0);
1276 # Suppress warning messages here; if the file itself can't
1277 # be written we'll worry about it then.
1278 wfSuppressWarnings();
1280 $archive = $dir.'/'.$subdir;
1281 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1282 $archive .= '/' . $hash{0};
1283 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1284 $archive .= '/' . substr( $hash, 0, 2 );
1285 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1287 wfRestoreWarnings();
1294 * Return the hash path component of an image path (URL or filesystem),
1295 * e.g. "/3/3c/", or just "/" if hashing is not used.
1297 * @param $dbkey The filesystem / database name of the file
1298 * @param $fromSharedDirectory Use the shared file repository? It may
1299 * use different hash settings from the local one.
1301 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1302 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1303 global $wgHashedUploadDirectory;
1305 if( Image
::isHashed( $fromSharedDirectory ) ) {
1306 $hash = md5($dbkey);
1307 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1314 * Returns the image URL of an image's old version
1316 * @param string $fname file name of the image file
1317 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1320 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1321 global $wgUploadPath, $wgHashedUploadDirectory;
1323 if ($wgHashedUploadDirectory) {
1324 $hash = md5( substr( $name, 15) );
1325 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1326 substr( $hash, 0, 2 ) . '/'.$name;
1328 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1330 return wfUrlencode($url);
1334 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1335 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1337 * @param string $length
1338 * @return int Length in pixels
1340 function wfScaleSVGUnit( $length ) {
1341 static $unitLength = array(
1348 '' => 1.0, // "User units" pixels by default
1349 '%' => 2.0, // Fake it!
1351 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1352 $length = FloatVal( $matches[1] );
1353 $unit = $matches[2];
1354 return round( $length * $unitLength[$unit] );
1357 return round( FloatVal( $length ) );
1362 * Compatible with PHP getimagesize()
1363 * @todo support gzipped SVGZ
1364 * @todo check XML more carefully
1365 * @todo sensible defaults
1367 * @param string $filename
1370 function wfGetSVGsize( $filename ) {
1374 // Read a chunk of the file
1375 $f = fopen( $filename, "rt" );
1376 if( !$f ) return false;
1377 $chunk = fread( $f, 4096 );
1380 // Uber-crappy hack! Run through a real XML parser.
1381 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1385 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1386 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1388 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1389 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1392 return array( $width, $height, 'SVG',
1393 "width=\"$width\" height=\"$height\"" );
1397 * Determine if an image exists on the 'bad image list'
1399 * @param string $name The image to check
1402 function wfIsBadImage( $name ) {
1404 static $titleList = false;
1405 if ( $titleList === false ) {
1406 $titleList = array();
1408 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1409 foreach ( $lines as $line ) {
1410 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1411 $t = Title
::newFromText( $m[1] );
1412 $titleList[$t->getDBkey()] = 1;
1417 return array_key_exists( $name, $titleList );
1423 * Wrapper class for thumbnail images
1424 * @package MediaWiki
1426 class ThumbnailImage
{
1428 * @param string $path Filesystem path to the thumb
1429 * @param string $url URL path to the thumb
1432 function ThumbnailImage( $url, $width, $height, $path = false ) {
1434 $this->width
= $width;
1435 $this->height
= $height;
1436 $this->path
= $path;
1440 * @return string The thumbnail URL
1447 * Return HTML <img ... /> tag for the thumbnail, will include
1448 * width and height attributes and a blank alt text (as required).
1450 * You can set or override additional attributes by passing an
1451 * associative array of name => data pairs. The data will be escaped
1452 * for HTML output, so should be in plaintext.
1454 * @param array $attribs
1458 function toHtml( $attribs = array() ) {
1459 $attribs['src'] = $this->url
;
1460 $attribs['width'] = $this->width
;
1461 $attribs['height'] = $this->height
;
1462 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1465 foreach( $attribs as $name => $data ) {
1466 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';