7 require_once ( 'exifReader.inc' ) ;
11 * Class to represent an image
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate thumbnails or for uploading.
22 var $name, # name of the image (constructor)
23 $imagePath, # Path of the image (loadFromXxx)
24 $url, # Image URL (accessor)
25 $title, # Title object for this image (constructor)
26 $fileExists, # does the image file exist on disk? (loadFromXxx)
27 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
28 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
29 $historyRes, # result of the query for the image's history (nextHistoryLine)
32 $bits, # --- returned by getimagesize (loadFromXxx)
35 $size, # Size in bytes (loadFromXxx)
37 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
43 * Create an Image object from an image name
45 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
48 function newFromName( $name ) {
49 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
50 return new Image( $title );
54 * Obsolete factory function, use constructor
56 function newFromTitle( $title ) {
57 return new Image( $title );
60 function Image( $title ) {
61 $this->title
=& $title;
62 $this->name
= $title->getDBkey();
63 $this->exif
= serialize ( array() ) ;
65 $n = strrpos( $this->name
, '.' );
66 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
67 $this->historyLine
= 0;
69 $this->dataLoaded
= false;
73 * Get the memcached keys
74 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
76 function getCacheKeys( $shared = false ) {
77 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
80 $hashedName = md5($this->name
);
81 $keys = array( "$wgDBname:Image:$hashedName" );
82 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
83 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
89 * Try to load image metadata from memcached. Returns true on success.
91 function loadFromCache() {
92 global $wgUseSharedUploads, $wgMemc;
93 $fname = 'Image::loadFromMemcached';
94 wfProfileIn( $fname );
95 $this->dataLoaded
= false;
96 $keys = $this->getCacheKeys();
97 $cachedValues = $wgMemc->get( $keys[0] );
99 // Check if the key existed and belongs to this version of MediaWiki
100 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
101 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
102 # if this is shared file, we need to check if image
103 # in shared repository has not changed
104 if ( isset( $keys[1] ) ) {
105 $commonsCachedValues = $wgMemc->get( $keys[1] );
106 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
107 $this->name
= $commonsCachedValues['name'];
108 $this->imagePath
= $commonsCachedValues['imagePath'];
109 $this->fileExists
= $commonsCachedValues['fileExists'];
110 $this->width
= $commonsCachedValues['width'];
111 $this->height
= $commonsCachedValues['height'];
112 $this->bits
= $commonsCachedValues['bits'];
113 $this->type
= $commonsCachedValues['type'];
114 $this->exif
= $commonsCachedValues['exif'];
115 $this->size
= $commonsCachedValues['size'];
116 $this->fromSharedDirectory
= true;
117 $this->dataLoaded
= true;
118 $this->imagePath
= $this->getFullPath(true);
123 $this->name
= $cachedValues['name'];
124 $this->imagePath
= $cachedValues['imagePath'];
125 $this->fileExists
= $cachedValues['fileExists'];
126 $this->width
= $cachedValues['width'];
127 $this->height
= $cachedValues['height'];
128 $this->bits
= $cachedValues['bits'];
129 $this->type
= $cachedValues['type'];
130 $this->exif
= $cachedValues['exif'];
131 $this->size
= $cachedValues['size'];
132 $this->fromSharedDirectory
= false;
133 $this->dataLoaded
= true;
134 $this->imagePath
= $this->getFullPath();
138 wfProfileOut( $fname );
139 return $this->dataLoaded
;
143 * Save the image metadata to memcached
145 function saveToCache() {
148 // We can't cache metadata for non-existent files, because if the file later appears
149 // in commons, the local keys won't be purged.
150 if ( $this->fileExists
) {
151 $keys = $this->getCacheKeys();
153 $cachedValues = array('name' => $this->name
,
154 'imagePath' => $this->imagePath
,
155 'fileExists' => $this->fileExists
,
156 'fromShared' => $this->fromSharedDirectory
,
157 'width' => $this->width
,
158 'height' => $this->height
,
159 'bits' => $this->bits
,
160 'type' => $this->type
,
161 'exif' => $this->exif
,
162 'size' => $this->size
);
164 $wgMemc->set( $keys[0], $cachedValues );
169 * Load metadata from the file itself
171 function loadFromFile() {
172 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
173 $fname = 'Image::loadFromFile';
174 wfProfileIn( $fname );
175 $this->imagePath
= $this->getFullPath();
176 $this->fileExists
= file_exists( $this->imagePath
);
177 $this->fromSharedDirectory
= false;
180 # If the file is not found, and a shared upload directory is used, look for it there.
181 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
182 # In case we're on a wgCapitalLinks=false wiki, we
183 # capitalize the first letter of the filename before
184 # looking it up in the shared repository.
185 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
186 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
187 if ( $this->fileExists
) {
188 $this->name
= $sharedImage->name
;
189 $this->imagePath
= $this->getFullPath(true);
190 $this->fromSharedDirectory
= true;
194 if ( $this->fileExists
) {
196 $this->size
= filesize( $this->imagePath
);
199 # Don't try to get the width and height of sound and video files, that's bad for performance
200 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
202 } elseif( $this->extension
== 'svg' ) {
203 wfSuppressWarnings();
204 $gis = wfGetSVGsize( $this->imagePath
);
207 wfSuppressWarnings();
208 $gis = getimagesize( $this->imagePath
);
212 if( $gis === false ) {
217 $this->exif
= serialize ( array() ) ;
219 $this->width
= $gis[0];
220 $this->height
= $gis[1];
221 $this->type
= $gis[2];
222 $this->exif
= serialize ( $this->retrieveExifData() ) ;
223 if ( isset( $gis['bits'] ) ) {
224 $this->bits
= $gis['bits'];
229 $this->dataLoaded
= true;
230 wfProfileOut( $fname );
234 * Load image metadata from the DB
236 function loadFromDB() {
237 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
238 $fname = 'Image::loadFromDB';
239 wfProfileIn( $fname );
241 $dbr =& wfGetDB( DB_SLAVE
);
242 $row = $dbr->selectRow( 'image',
243 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_exif' ),
244 array( 'img_name' => $this->name
), $fname );
246 $this->fromSharedDirectory
= false;
247 $this->fileExists
= true;
248 $this->loadFromRow( $row );
249 $this->imagePath
= $this->getFullPath();
250 // Check for rows from a previous schema, quietly upgrade them
251 if ( $this->type
== -1 ) {
254 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
255 # In case we're on a wgCapitalLinks=false wiki, we
256 # capitalize the first letter of the filename before
257 # looking it up in the shared repository.
258 $name = $wgLang->ucfirst($this->name
);
260 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
261 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
262 array( 'img_name' => $name ), $fname );
264 $this->fromSharedDirectory
= true;
265 $this->fileExists
= true;
266 $this->imagePath
= $this->getFullPath(true);
268 $this->loadFromRow( $row );
270 // Check for rows from a previous schema, quietly upgrade them
271 if ( $this->type
== -1 ) {
283 $this->fileExists
= false;
284 $this->fromSharedDirectory
= false;
285 $this->exif
= serialize ( array() ) ;
288 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
289 $this->dataLoaded
= true;
293 * Load image metadata from a DB result row
295 function loadFromRow( &$row ) {
296 $this->size
= $row->img_size
;
297 $this->width
= $row->img_width
;
298 $this->height
= $row->img_height
;
299 $this->bits
= $row->img_bits
;
300 $this->type
= $row->img_type
;
301 $this->exif
= $row->img_exif
;
302 if ( $this->exif
== "" ) $this->exif
= serialize ( array() ) ;
303 $this->dataLoaded
= true;
307 * Load image metadata from cache or DB, unless already loaded
310 global $wgSharedUploadDBname, $wgUseSharedUploads;
311 if ( !$this->dataLoaded
) {
312 if ( !$this->loadFromCache() ) {
314 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
315 $this->loadFromFile();
316 } elseif ( $this->fileExists
) {
317 $this->saveToCache();
320 $this->dataLoaded
= true;
325 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
326 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
328 function upgradeRow() {
329 global $wgDBname, $wgSharedUploadDBname;
330 $fname = 'Image::upgradeRow';
331 $this->loadFromFile();
332 $dbw =& wfGetDB( DB_MASTER
);
334 if ( $this->fromSharedDirectory
) {
335 if ( !$wgSharedUploadDBname ) {
339 // Write to the other DB using selectDB, not database selectors
340 // This avoids breaking replication in MySQL
341 $dbw->selectDB( $wgSharedUploadDBname );
343 $dbw->update( '`image`',
345 'img_width' => $this->width
,
346 'img_height' => $this->height
,
347 'img_bits' => $this->bits
,
348 'img_type' => $this->type
,
349 'img_exif' => $this->exif
,
350 ), array( 'img_name' => $this->name
), $fname
352 if ( $this->fromSharedDirectory
) {
353 $dbw->selectDB( $wgDBname );
358 * Return the name of this image
366 * Return the associated title object
369 function getTitle() {
374 * Return the URL of the image file
380 if($this->fileExists
) {
381 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
389 function getViewURL() {
390 if( $this->mustRender() ) {
391 return $this->createThumb( $this->getWidth() );
393 return $this->getURL();
398 * Return the image path of the image in the
399 * local file system as an absolute path
402 function getImagePath() {
404 return $this->imagePath
;
408 * Return the width of the image
410 * Returns -1 if the file specified is not a known image type
413 function getWidth() {
419 * Return the height of the image
421 * Returns -1 if the file specified is not a known image type
424 function getHeight() {
426 return $this->height
;
430 * Return the size of the image file, in bytes
439 * Return the type of the image
453 * Return the escapeLocalURL of this image
456 function getEscapeLocalURL() {
458 return $this->title
->escapeLocalURL();
462 * Return the escapeFullURL of this image
465 function getEscapeFullURL() {
467 return $this->title
->escapeFullURL();
471 * Return the URL of an image, provided its name.
473 * @param string $name Name of the image, without the leading "Image:"
474 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
478 function imageUrl( $name, $fromSharedDirectory = false ) {
479 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
480 if($fromSharedDirectory) {
482 $path = $wgSharedUploadPath;
484 $base = $wgUploadBaseUrl;
485 $path = $wgUploadPath;
487 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
488 return wfUrlencode( $url );
492 * Returns true if the image file exists on disk.
498 return $this->fileExists
;
505 function thumbUrl( $width, $subdir='thumb') {
506 global $wgUploadPath, $wgUploadBaseUrl,
507 $wgSharedUploadPath,$wgSharedUploadDirectory,
508 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
510 // Generate thumb.php URL if possible
514 if ( $this->fromSharedDirectory
) {
515 if ( $wgSharedThumbnailScriptPath ) {
516 $script = $wgSharedThumbnailScriptPath;
519 if ( $wgThumbnailScriptPath ) {
520 $script = $wgThumbnailScriptPath;
524 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
526 $name = $this->thumbName( $width );
527 if($this->fromSharedDirectory
) {
529 $path = $wgSharedUploadPath;
531 $base = $wgUploadBaseUrl;
532 $path = $wgUploadPath;
534 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
535 $url = "{$base}{$path}/{$subdir}" .
536 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
537 . $this->name
.'/'.$name;
538 $url = wfUrlencode( $url );
540 $url = "{$base}{$path}/{$subdir}/{$name}";
543 return array( $script !== false, $url );
547 * Return the file name of a thumbnail of the specified width
549 * @param integer $width Width of the thumbnail image
550 * @param boolean $shared Does the thumbnail come from the shared repository?
553 function thumbName( $width ) {
554 $thumb = $width."px-".$this->name
;
555 if( $this->extension
== 'svg' ) {
556 # Rasterize SVG vector images to PNG
563 * Create a thumbnail of the image having the specified width/height.
564 * The thumbnail will not be created if the width is larger than the
565 * image's width. Let the browser do the scaling in this case.
566 * The thumbnail is stored on disk and is only computed if the thumbnail
567 * file does not exist OR if it is older than the image.
570 * Keeps aspect ratio of original image. If both width and height are
571 * specified, the generated image will be no bigger than width x height,
572 * and will also have correct aspect ratio.
574 * @param integer $width maximum width of the generated thumbnail
575 * @param integer $height maximum height of the image (optional)
578 function createThumb( $width, $height=-1 ) {
579 $thumb = $this->getThumbnail( $width, $height );
580 if( is_null( $thumb ) ) return '';
581 return $thumb->getUrl();
585 * As createThumb, but returns a ThumbnailImage object. This can
586 * provide access to the actual file, the real size of the thumb,
587 * and can produce a convenient <img> tag for you.
589 * @param integer $width maximum width of the generated thumbnail
590 * @param integer $height maximum height of the image (optional)
591 * @return ThumbnailImage
594 function &getThumbnail( $width, $height=-1 ) {
595 if ( $height == -1 ) {
596 return $this->renderThumb( $width );
599 if ( $width < $this->width
) {
600 $thumbheight = $this->height
* $width / $this->width
;
601 $thumbwidth = $width;
603 $thumbheight = $this->height
;
604 $thumbwidth = $this->width
;
606 if ( $thumbheight > $height ) {
607 $thumbwidth = $thumbwidth * $height / $thumbheight;
608 $thumbheight = $height;
610 $thumb = $this->renderThumb( $thumbwidth );
611 if( is_null( $thumb ) ) {
612 $thumb = $this->iconThumb();
618 * @return ThumbnailImage
620 function iconThumb() {
621 global $wgStylePath, $wgStyleDirectory;
623 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
624 foreach( $try as $icon ) {
625 $path = '/common/images/' . $icon;
626 $filepath = $wgStyleDirectory . $path;
627 if( file_exists( $filepath ) ) {
628 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
635 * Create a thumbnail of the image having the specified width.
636 * The thumbnail will not be created if the width is larger than the
637 * image's width. Let the browser do the scaling in this case.
638 * The thumbnail is stored on disk and is only computed if the thumbnail
639 * file does not exist OR if it is older than the image.
640 * Returns an object which can return the pathname, URL, and physical
641 * pixel size of the thumbnail -- or null on failure.
643 * @return ThumbnailImage
646 function /* private */ renderThumb( $width, $useScript = true ) {
647 global $wgUseSquid, $wgInternalServer;
648 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
650 $width = IntVal( $width );
653 if ( ! $this->exists() )
655 # If there is no image, there will be no thumbnail
659 # Sanity check $width
665 if( $width > $this->width
&& !$this->mustRender() ) {
666 # Don't make an image bigger than the source
667 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
670 $height = floor( $this->height
* ( $width/$this->width
) );
672 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
673 if ( $isScriptUrl && $useScript ) {
674 // Use thumb.php to render the image
675 return new ThumbnailImage( $url, $width, $height );
678 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
679 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
681 if ( !file_exists( $thumbPath ) ) {
682 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
685 if ( file_exists( $oldThumbPath ) ) {
686 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
687 rename( $oldThumbPath, $thumbPath );
690 unlink( $oldThumbPath );
694 $this->reallyRenderThumb( $thumbPath, $width, $height );
697 # This has to be done after the image is updated and present for all machines on NFS,
698 # or else the old version might be stored into the squid again
700 if ( substr( $url, 0, 4 ) == 'http' ) {
701 $urlArr = array( $url );
703 $urlArr = array( $wgInternalServer.$url );
705 wfPurgeSquidServers($urlArr);
709 return new ThumbnailImage( $url, $width, $height, $thumbPath );
710 } // END OF function renderThumb
713 * Really render a thumbnail
717 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
718 global $wgSVGConverters, $wgSVGConverter,
719 $wgUseImageMagick, $wgImageMagickConvertCommand;
723 if( $this->extension
== 'svg' ) {
724 global $wgSVGConverters, $wgSVGConverter;
725 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
726 global $wgSVGConverterPath;
728 array( '$path/', '$width', '$input', '$output' ),
729 array( $wgSVGConverterPath,
731 escapeshellarg( $this->imagePath
),
732 escapeshellarg( $thumbPath ) ),
733 $wgSVGConverters[$wgSVGConverter] );
734 $conv = shell_exec( $cmd );
738 } elseif ( $wgUseImageMagick ) {
740 # Specify white background color, will be used for transparent images
741 # in Internet Explorer/Windows instead of default black.
742 $cmd = $wgImageMagickConvertCommand .
743 " -quality 85 -background white -geometry {$width} ".
744 escapeshellarg($this->imagePath
) . " " .
745 escapeshellarg($thumbPath);
746 $conv = shell_exec( $cmd );
748 # Use PHP's builtin GD library functions.
750 # First find out what kind of file this is, and select the correct
751 # input routine for this.
755 switch( $this->type
) {
757 $src_image = imagecreatefromgif( $this->imagePath
);
760 $src_image = imagecreatefromjpeg( $this->imagePath
);
764 $src_image = imagecreatefrompng( $this->imagePath
);
765 $truecolor = ( $this->bits
> 8 );
767 case 15: # WBMP for WML
768 $src_image = imagecreatefromwbmp( $this->imagePath
);
771 $src_image = imagecreatefromxbm( $this->imagePath
);
774 return 'Image type not supported';
778 $dst_image = imagecreatetruecolor( $width, $height );
780 $dst_image = imagecreate( $width, $height );
782 imagecopyresampled( $dst_image, $src_image,
784 $width, $height, $this->width
, $this->height
);
785 switch( $this->type
) {
790 imagepng( $dst_image, $thumbPath );
793 imageinterlace( $dst_image );
794 imagejpeg( $dst_image, $thumbPath, 95 );
799 imagedestroy( $dst_image );
800 imagedestroy( $src_image );
803 # Check for zero-sized thumbnails. Those can be generated when
804 # no disk space is available or some other error occurs
806 if( file_exists( $thumbPath ) ) {
807 $thumbstat = stat( $thumbPath );
808 if( $thumbstat['size'] == 0 ) {
809 unlink( $thumbPath );
815 * Get all thumbnail names previously generated for this image
817 function getThumbnails( $shared = false ) {
818 if ( Image
::isHashed( $shared ) ) {
821 $dir = wfImageThumbDir( $this->name
, $shared );
823 // This generates an error on failure, hence the @
824 $handle = @opendir
( $dir );
827 while ( false !== ( $file = readdir($handle) ) ) {
828 if ( $file{0} != '.' ) {
842 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
844 function purgeCache( $archiveFiles = array(), $shared = false ) {
845 global $wgInternalServer, $wgUseSquid;
847 // Refresh metadata cache
849 $this->loadFromFile();
850 $this->saveToCache();
853 $files = $this->getThumbnails( $shared );
854 $dir = wfImageThumbDir( $this->name
, $shared );
856 foreach ( $files as $file ) {
857 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
858 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
859 @unlink
( "$dir/$file" );
865 $urls[] = $wgInternalServer . $this->getViewURL();
866 foreach ( $archiveFiles as $file ) {
867 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
869 wfPurgeSquidServers( $urls );
874 * Return the image history of this image, line by line.
875 * starts with current version, then old versions.
876 * uses $this->historyLine to check which line to return:
877 * 0 return line for current version
878 * 1 query for old versions, return first one
879 * 2, ... return next old version from above query
883 function nextHistoryLine() {
884 $fname = 'Image::nextHistoryLine()';
885 $dbr =& wfGetDB( DB_SLAVE
);
886 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
887 $this->historyRes
= $dbr->select( 'image',
888 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
889 array( 'img_name' => $this->title
->getDBkey() ),
892 if ( 0 == wfNumRows( $this->historyRes
) ) {
895 } else if ( $this->historyLine
== 1 ) {
896 $this->historyRes
= $dbr->select( 'oldimage',
897 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
898 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
899 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
902 $this->historyLine ++
;
904 return $dbr->fetchObject( $this->historyRes
);
908 * Reset the history pointer to the first element of the history
911 function resetHistory() {
912 $this->historyLine
= 0;
916 * Return true if the file is of a type that can't be directly
917 * rendered by typical browsers and needs to be re-rasterized.
920 function mustRender() {
922 return ( $this->extension
== 'svg' );
926 * Return the full filesystem path to the file. Note that this does
927 * not mean that a file actually exists under that location.
929 * This path depends on whether directory hashing is active or not,
930 * i.e. whether the images are all found in the same directory,
931 * or in hashed paths like /images/3/3c.
934 * @param boolean $fromSharedDirectory Return the path to the file
935 * in a shared repository (see $wgUseSharedRepository and related
936 * options in DefaultSettings.php) instead of a local one.
939 function getFullPath( $fromSharedRepository = false ) {
940 global $wgUploadDirectory, $wgSharedUploadDirectory;
941 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
943 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
946 // $wgSharedUploadDirectory may be false, if thumb.php is used
948 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
960 function isHashed( $shared ) {
961 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
962 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
969 function isKnownImageExtension( $ext ) {
970 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
971 return in_array( $ext, $extensions );
975 * Record an image upload in the upload log and the image table
977 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
978 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
979 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
981 $fname = 'Image::recordUpload';
982 $dbw =& wfGetDB( DB_MASTER
);
984 # img_name must be unique
985 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
986 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
989 // Delete thumbnails and refresh the metadata cache
992 // Fail now if the image isn't there
993 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
997 if ( $wgUseCopyrightUpload ) {
998 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
999 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1000 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1005 $now = $dbw->timestamp();
1007 # Test to see if the row exists using INSERT IGNORE
1008 # This avoids race conditions by locking the row until the commit, and also
1009 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1010 $dbw->insert( 'image',
1012 'img_name' => $this->name
,
1013 'img_size'=> $this->size
,
1014 'img_width' => $this->width
,
1015 'img_height' => $this->height
,
1016 'img_bits' => $this->bits
,
1017 'img_type' => $this->type
,
1018 'img_timestamp' => $now,
1019 'img_description' => $desc,
1020 'img_user' => $wgUser->getID(),
1021 'img_user_text' => $wgUser->getName(),
1022 'img_exif' => $this->exif
,
1025 $descTitle = $this->getTitle();
1026 $purgeURLs = array();
1028 if ( $dbw->affectedRows() ) {
1029 # Successfully inserted, this is a new image
1030 $id = $descTitle->getArticleID();
1033 $article = new Article( $descTitle );
1034 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1037 # Collision, this is an update of an image
1038 # Insert previous contents into oldimage
1039 $dbw->insertSelect( 'oldimage', 'image',
1041 'oi_name' => 'img_name',
1042 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1043 'oi_size' => 'img_size',
1044 'oi_width' => 'img_width',
1045 'oi_height' => 'img_height',
1046 'oi_bits' => 'img_bits',
1047 'oi_type' => 'img_type',
1048 'oi_timestamp' => 'img_timestamp',
1049 'oi_description' => 'img_description',
1050 'oi_user' => 'img_user',
1051 'oi_user_text' => 'img_user_text',
1052 ), array( 'img_name' => $this->name
), $fname
1055 # Update the current image row
1056 $dbw->update( 'image',
1058 'img_size' => $this->size
,
1059 'img_width' => $this->width
,
1060 'img_height' => $this->height
,
1061 'img_bits' => $this->bits
,
1062 'img_type' => $this->type
,
1063 'img_timestamp' => $now,
1064 'img_user' => $wgUser->getID(),
1065 'img_user_text' => $wgUser->getName(),
1066 'img_description' => $desc,
1067 'img_exif' => $this->exif
,
1068 ), array( /* WHERE */
1069 'img_name' => $this->name
1073 # Invalidate the cache for the description page
1074 $descTitle->invalidateCache();
1075 $purgeURLs[] = $descTitle->getInternalURL();
1078 # Invalidate cache for all pages using this image
1079 $linksTo = $this->getLinksTo();
1081 if ( $wgUseSquid ) {
1082 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1083 array_push( $wgPostCommitUpdateList, $u );
1085 Title
::touchArray( $linksTo );
1087 $log = new LogPage( 'upload' );
1088 $log->addEntry( 'upload', $descTitle, $desc );
1094 * Get an array of Title objects which are articles which use this image
1095 * Also adds their IDs to the link cache
1097 * This is mostly copied from Title::getLinksTo()
1099 function getLinksTo( $options = '' ) {
1100 global $wgLinkCache;
1101 $fname = 'Image::getLinksTo';
1102 wfProfileIn( $fname );
1105 $db =& wfGetDB( DB_MASTER
);
1107 $db =& wfGetDB( DB_SLAVE
);
1110 extract( $db->tableNames( 'page', 'imagelinks' ) );
1111 $encName = $db->addQuotes( $this->name
);
1112 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1113 $res = $db->query( $sql, $fname );
1116 if ( $db->numRows( $res ) ) {
1117 while ( $row = $db->fetchObject( $res ) ) {
1118 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1119 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1120 $retVal[] = $titleObj;
1124 $db->freeResult( $res );
1128 function retrieveExifData () {
1129 global $wgShowEXIF ;
1130 if ( ! $wgShowEXIF ) return array () ;
1132 $file = $this->imagePath
;
1133 $per = new phpExifReader ( $file ) ;
1134 $per->processFile () ;
1135 $a = $per->getImageInfo() ;
1136 unset ( $a["FileName"] ) ;
1137 unset ( $a["Thumbnail"] ) ;
1141 function getExifData () {
1142 global $wgShowEXIF ;
1143 if ( ! $wgShowEXIF ) return array () ;
1145 $ret = unserialize ( $this->exif
) ;
1146 if ( count ( $ret ) == 0 ) { # No EXIF data was stored for this image
1147 $this->updateExifData() ;
1148 $ret = unserialize ( $this->exif
) ;
1154 function updateExifData () {
1155 global $wgShowEXIF ;
1156 if ( ! $wgShowEXIF ) return ;
1157 if ( false === $this->getImagePath() ) return ; # Not a local image
1159 $fname = "Image:updateExifData" ;
1161 # Get EXIF data from image
1162 $exif = $this->retrieveExifData () ;
1163 $this->exif
= serialize ( $exif ) ;
1165 # Update EXIF data in database
1166 $dbw =& wfGetDB( DB_MASTER
);
1167 $dbw->update( '`image`',
1168 array( 'img_exif' => $this->exif
),
1169 array( 'img_name' => $this->name
),
1179 * Returns the image directory of an image
1180 * If the directory does not exist, it is created.
1181 * The result is an absolute path.
1183 * This function is called from thumb.php before Setup.php is included
1185 * @param string $fname file name of the image file
1188 function wfImageDir( $fname ) {
1189 global $wgUploadDirectory, $wgHashedUploadDirectory;
1191 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1193 $hash = md5( $fname );
1194 $oldumask = umask(0);
1195 $dest = $wgUploadDirectory . '/' . $hash{0};
1196 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1197 $dest .= '/' . substr( $hash, 0, 2 );
1198 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1205 * Returns the image directory of an image's thubnail
1206 * If the directory does not exist, it is created.
1207 * The result is an absolute path.
1209 * This function is called from thumb.php before Setup.php is included
1211 * @param string $fname file name of the original image file
1212 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1213 * @param boolean $shared (optional) use the shared upload directory
1216 function wfImageThumbDir( $fname, $shared = false ) {
1217 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1218 if ( Image
::isHashed( $shared ) ) {
1219 $dir = "$base/$fname";
1221 if ( !is_dir( $base ) ) {
1222 $oldumask = umask(0);
1223 @mkdir
( $base, 0777 );
1227 if ( ! is_dir( $dir ) ) {
1228 $oldumask = umask(0);
1229 @mkdir
( $dir, 0777 );
1240 * Old thumbnail directory, kept for conversion
1242 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1243 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1247 * Returns the image directory of an image's old version
1248 * If the directory does not exist, it is created.
1249 * The result is an absolute path.
1251 * This function is called from thumb.php before Setup.php is included
1253 * @param string $fname file name of the thumbnail file, including file size prefix
1254 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1255 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1258 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1259 global $wgUploadDirectory, $wgHashedUploadDirectory,
1260 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1261 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1262 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1263 if (!$hashdir) { return $dir.'/'.$subdir; }
1264 $hash = md5( $fname );
1265 $oldumask = umask(0);
1267 # Suppress warning messages here; if the file itself can't
1268 # be written we'll worry about it then.
1269 wfSuppressWarnings();
1271 $archive = $dir.'/'.$subdir;
1272 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1273 $archive .= '/' . $hash{0};
1274 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1275 $archive .= '/' . substr( $hash, 0, 2 );
1276 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1278 wfRestoreWarnings();
1285 * Return the hash path component of an image path (URL or filesystem),
1286 * e.g. "/3/3c/", or just "/" if hashing is not used.
1288 * @param $dbkey The filesystem / database name of the file
1289 * @param $fromSharedDirectory Use the shared file repository? It may
1290 * use different hash settings from the local one.
1292 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1293 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1294 global $wgHashedUploadDirectory;
1296 if( Image
::isHashed( $fromSharedDirectory ) ) {
1297 $hash = md5($dbkey);
1298 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1305 * Returns the image URL of an image's old version
1307 * @param string $fname file name of the image file
1308 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1311 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1312 global $wgUploadPath, $wgHashedUploadDirectory;
1314 if ($wgHashedUploadDirectory) {
1315 $hash = md5( substr( $name, 15) );
1316 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1317 substr( $hash, 0, 2 ) . '/'.$name;
1319 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1321 return wfUrlencode($url);
1325 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1326 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1328 * @param string $length
1329 * @return int Length in pixels
1331 function wfScaleSVGUnit( $length ) {
1332 static $unitLength = array(
1339 '' => 1.0, // "User units" pixels by default
1340 '%' => 2.0, // Fake it!
1342 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1343 $length = FloatVal( $matches[1] );
1344 $unit = $matches[2];
1345 return round( $length * $unitLength[$unit] );
1348 return round( FloatVal( $length ) );
1353 * Compatible with PHP getimagesize()
1354 * @todo support gzipped SVGZ
1355 * @todo check XML more carefully
1356 * @todo sensible defaults
1358 * @param string $filename
1361 function wfGetSVGsize( $filename ) {
1365 // Read a chunk of the file
1366 $f = fopen( $filename, "rt" );
1367 if( !$f ) return false;
1368 $chunk = fread( $f, 4096 );
1371 // Uber-crappy hack! Run through a real XML parser.
1372 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1376 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1377 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1379 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1380 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1383 return array( $width, $height, 'SVG',
1384 "width=\"$width\" height=\"$height\"" );
1388 * Is an image on the bad image list?
1390 function wfIsBadImage( $name ) {
1393 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1394 foreach ( $lines as $line ) {
1395 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1396 $t = Title
::newFromText( $m[1] );
1397 if ( $t->getDBkey() == $name ) {
1408 * Wrapper class for thumbnail images
1409 * @package MediaWiki
1411 class ThumbnailImage
{
1413 * @param string $path Filesystem path to the thumb
1414 * @param string $url URL path to the thumb
1417 function ThumbnailImage( $url, $width, $height, $path = false ) {
1419 $this->width
= $width;
1420 $this->height
= $height;
1421 $this->path
= $path;
1425 * @return string The thumbnail URL
1432 * Return HTML <img ... /> tag for the thumbnail, will include
1433 * width and height attributes and a blank alt text (as required).
1435 * You can set or override additional attributes by passing an
1436 * associative array of name => data pairs. The data will be escaped
1437 * for HTML output, so should be in plaintext.
1439 * @param array $attribs
1443 function toHtml( $attribs = array() ) {
1444 $attribs['src'] = $this->url
;
1445 $attribs['width'] = $this->width
;
1446 $attribs['height'] = $this->height
;
1447 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1450 foreach( $attribs as $name => $data ) {
1451 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';