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)
36 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
42 * Create an Image object from an image name
44 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
47 function newFromName( $name ) {
48 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
49 return new Image( $title );
53 * Obsolete factory function, use constructor
55 function newFromTitle( $title ) {
56 return new Image( $title );
59 function Image( $title ) {
60 $this->title
=& $title;
61 $this->name
= $title->getDBkey();
63 $n = strrpos( $this->name
, '.' );
64 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
65 $this->historyLine
= 0;
67 $this->dataLoaded
= false;
71 * Get the memcached keys
72 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
74 function getCacheKeys( $shared = false ) {
75 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
78 $hashedName = md5($this->name
);
79 $keys = array( "$wgDBname:Image:$hashedName" );
80 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
81 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
87 * Try to load image metadata from memcached. Returns true on success.
89 function loadFromCache() {
90 global $wgUseSharedUploads, $wgMemc;
91 $fname = 'Image::loadFromMemcached';
92 wfProfileIn( $fname );
93 $this->dataLoaded
= false;
94 $keys = $this->getCacheKeys();
95 $cachedValues = $wgMemc->get( $keys[0] );
97 // Check if the key existed and belongs to this version of MediaWiki
98 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
99 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
100 # if this is shared file, we need to check if image
101 # in shared repository has not changed
102 if ( isset( $keys[1] ) ) {
103 $commonsCachedValues = $wgMemc->get( $keys[1] );
104 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
105 $this->name
= $commonsCachedValues['name'];
106 $this->imagePath
= $commonsCachedValues['imagePath'];
107 $this->fileExists
= $commonsCachedValues['fileExists'];
108 $this->width
= $commonsCachedValues['width'];
109 $this->height
= $commonsCachedValues['height'];
110 $this->bits
= $commonsCachedValues['bits'];
111 $this->type
= $commonsCachedValues['type'];
112 $this->size
= $commonsCachedValues['size'];
113 $this->fromSharedDirectory
= true;
114 $this->dataLoaded
= true;
115 $this->imagePath
= $this->getFullPath(true);
120 $this->name
= $cachedValues['name'];
121 $this->imagePath
= $cachedValues['imagePath'];
122 $this->fileExists
= $cachedValues['fileExists'];
123 $this->width
= $cachedValues['width'];
124 $this->height
= $cachedValues['height'];
125 $this->bits
= $cachedValues['bits'];
126 $this->type
= $cachedValues['type'];
127 $this->size
= $cachedValues['size'];
128 $this->fromSharedDirectory
= false;
129 $this->dataLoaded
= true;
130 $this->imagePath
= $this->getFullPath();
134 wfProfileOut( $fname );
135 return $this->dataLoaded
;
139 * Save the image metadata to memcached
141 function saveToCache() {
144 // We can't cache metadata for non-existent files, because if the file later appears
145 // in commons, the local keys won't be purged.
146 if ( $this->fileExists
) {
147 $keys = $this->getCacheKeys();
149 $cachedValues = array('name' => $this->name
,
150 'imagePath' => $this->imagePath
,
151 'fileExists' => $this->fileExists
,
152 'fromShared' => $this->fromSharedDirectory
,
153 'width' => $this->width
,
154 'height' => $this->height
,
155 'bits' => $this->bits
,
156 'type' => $this->type
,
157 'size' => $this->size
);
159 $wgMemc->set( $keys[0], $cachedValues );
164 * Load metadata from the file itself
166 function loadFromFile() {
167 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
168 $fname = 'Image::loadFromFile';
169 wfProfileIn( $fname );
170 $this->imagePath
= $this->getFullPath();
171 $this->fileExists
= file_exists( $this->imagePath
);
172 $this->fromSharedDirectory
= false;
175 # If the file is not found, and a shared upload directory is used, look for it there.
176 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
177 # In case we're on a wgCapitalLinks=false wiki, we
178 # capitalize the first letter of the filename before
179 # looking it up in the shared repository.
180 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
181 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
182 if ( $this->fileExists
) {
183 $this->name
= $sharedImage->name
;
184 $this->imagePath
= $this->getFullPath(true);
185 $this->fromSharedDirectory
= true;
189 if ( $this->fileExists
) {
191 $this->size
= filesize( $this->imagePath
);
194 # Don't try to get the width and height of sound and video files, that's bad for performance
195 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
197 } elseif( $this->extension
== 'svg' ) {
198 wfSuppressWarnings();
199 $gis = wfGetSVGsize( $this->imagePath
);
202 wfSuppressWarnings();
203 $gis = getimagesize( $this->imagePath
);
207 if( $gis === false ) {
213 $this->width
= $gis[0];
214 $this->height
= $gis[1];
215 $this->type
= $gis[2];
216 if ( isset( $gis['bits'] ) ) {
217 $this->bits
= $gis['bits'];
222 $this->dataLoaded
= true;
223 wfProfileOut( $fname );
227 * Load image metadata from the DB
229 function loadFromDB() {
230 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
231 $fname = 'Image::loadFromDB';
232 wfProfileIn( $fname );
234 $dbr =& wfGetDB( DB_SLAVE
);
235 $row = $dbr->selectRow( 'image',
236 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
237 array( 'img_name' => $this->name
), $fname );
239 $this->fromSharedDirectory
= false;
240 $this->fileExists
= true;
241 $this->loadFromRow( $row );
242 $this->imagePath
= $this->getFullPath();
243 // Check for rows from a previous schema, quietly upgrade them
244 if ( $this->type
== -1 ) {
247 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
248 # In case we're on a wgCapitalLinks=false wiki, we
249 # capitalize the first letter of the filename before
250 # looking it up in the shared repository.
251 $name = $wgLang->ucfirst($this->name
);
253 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
254 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
255 array( 'img_name' => $name ), $fname );
257 $this->fromSharedDirectory
= true;
258 $this->fileExists
= true;
259 $this->imagePath
= $this->getFullPath(true);
261 $this->loadFromRow( $row );
263 // Check for rows from a previous schema, quietly upgrade them
264 if ( $this->type
== -1 ) {
276 $this->fileExists
= false;
277 $this->fromSharedDirectory
= false;
280 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
281 $this->dataLoaded
= true;
285 * Load image metadata from a DB result row
287 function loadFromRow( &$row ) {
288 $this->size
= $row->img_size
;
289 $this->width
= $row->img_width
;
290 $this->height
= $row->img_height
;
291 $this->bits
= $row->img_bits
;
292 $this->type
= $row->img_type
;
293 $this->dataLoaded
= true;
297 * Load image metadata from cache or DB, unless already loaded
300 global $wgSharedUploadDBname, $wgUseSharedUploads;
301 if ( !$this->dataLoaded
) {
302 if ( !$this->loadFromCache() ) {
304 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
305 $this->loadFromFile();
306 } elseif ( $this->fileExists
) {
307 $this->saveToCache();
310 $this->dataLoaded
= true;
315 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
316 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
318 function upgradeRow() {
319 global $wgDBname, $wgSharedUploadDBname;
320 $fname = 'Image::upgradeRow';
321 $this->loadFromFile();
322 $dbw =& wfGetDB( DB_MASTER
);
324 if ( $this->fromSharedDirectory
) {
325 if ( !$wgSharedUploadDBname ) {
329 // Write to the other DB using selectDB, not database selectors
330 // This avoids breaking replication in MySQL
331 $dbw->selectDB( $wgSharedUploadDBname );
333 $dbw->update( '`image`',
335 'img_width' => $this->width
,
336 'img_height' => $this->height
,
337 'img_bits' => $this->bits
,
338 'img_type' => $this->type
,
339 ), array( 'img_name' => $this->name
), $fname
341 if ( $this->fromSharedDirectory
) {
342 $dbw->selectDB( $wgDBname );
347 * Return the name of this image
355 * Return the associated title object
358 function getTitle() {
363 * Return the URL of the image file
369 if($this->fileExists
) {
370 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
378 function getViewURL() {
379 if( $this->mustRender() ) {
380 return $this->createThumb( $this->getWidth() );
382 return $this->getURL();
387 * Return the image path of the image in the
388 * local file system as an absolute path
391 function getImagePath() {
393 return $this->imagePath
;
397 * Return the width of the image
399 * Returns -1 if the file specified is not a known image type
402 function getWidth() {
408 * Return the height of the image
410 * Returns -1 if the file specified is not a known image type
413 function getHeight() {
415 return $this->height
;
419 * Return the size of the image file, in bytes
428 * Return the type of the image
442 * Return the escapeLocalURL of this image
445 function getEscapeLocalURL() {
447 return $this->title
->escapeLocalURL();
451 * Return the escapeFullURL of this image
454 function getEscapeFullURL() {
456 return $this->title
->escapeFullURL();
460 * Return the URL of an image, provided its name.
462 * @param string $name Name of the image, without the leading "Image:"
463 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
467 function imageUrl( $name, $fromSharedDirectory = false ) {
468 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
469 if($fromSharedDirectory) {
471 $path = $wgSharedUploadPath;
473 $base = $wgUploadBaseUrl;
474 $path = $wgUploadPath;
476 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
477 return wfUrlencode( $url );
481 * Returns true if the image file exists on disk.
487 return $this->fileExists
;
494 function thumbUrl( $width, $subdir='thumb') {
495 global $wgUploadPath, $wgUploadBaseUrl,
496 $wgSharedUploadPath,$wgSharedUploadDirectory,
497 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
499 // Generate thumb.php URL if possible
503 if ( $this->fromSharedDirectory
) {
504 if ( $wgSharedThumbnailScriptPath ) {
505 $script = $wgSharedThumbnailScriptPath;
508 if ( $wgThumbnailScriptPath ) {
509 $script = $wgThumbnailScriptPath;
513 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
515 $name = $this->thumbName( $width );
516 if($this->fromSharedDirectory
) {
518 $path = $wgSharedUploadPath;
520 $base = $wgUploadBaseUrl;
521 $path = $wgUploadPath;
523 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
524 $url = "{$base}{$path}/{$subdir}" .
525 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
526 . $this->name
.'/'.$name;
527 $url = wfUrlencode( $url );
529 $url = "{$base}{$path}/{$subdir}/{$name}";
532 return array( $script !== false, $url );
536 * Return the file name of a thumbnail of the specified width
538 * @param integer $width Width of the thumbnail image
539 * @param boolean $shared Does the thumbnail come from the shared repository?
542 function thumbName( $width ) {
543 $thumb = $width."px-".$this->name
;
544 if( $this->extension
== 'svg' ) {
545 # Rasterize SVG vector images to PNG
552 * Create a thumbnail of the image having the specified width/height.
553 * The thumbnail will not be created if the width is larger than the
554 * image's width. Let the browser do the scaling in this case.
555 * The thumbnail is stored on disk and is only computed if the thumbnail
556 * file does not exist OR if it is older than the image.
559 * Keeps aspect ratio of original image. If both width and height are
560 * specified, the generated image will be no bigger than width x height,
561 * and will also have correct aspect ratio.
563 * @param integer $width maximum width of the generated thumbnail
564 * @param integer $height maximum height of the image (optional)
567 function createThumb( $width, $height=-1 ) {
568 $thumb = $this->getThumbnail( $width, $height );
569 if( is_null( $thumb ) ) return '';
570 return $thumb->getUrl();
574 * As createThumb, but returns a ThumbnailImage object. This can
575 * provide access to the actual file, the real size of the thumb,
576 * and can produce a convenient <img> tag for you.
578 * @param integer $width maximum width of the generated thumbnail
579 * @param integer $height maximum height of the image (optional)
580 * @return ThumbnailImage
583 function &getThumbnail( $width, $height=-1 ) {
584 if ( $height == -1 ) {
585 return $this->renderThumb( $width );
588 if ( $width < $this->width
) {
589 $thumbheight = $this->height
* $width / $this->width
;
590 $thumbwidth = $width;
592 $thumbheight = $this->height
;
593 $thumbwidth = $this->width
;
595 if ( $thumbheight > $height ) {
596 $thumbwidth = $thumbwidth * $height / $thumbheight;
597 $thumbheight = $height;
599 $thumb = $this->renderThumb( $thumbwidth );
600 if( is_null( $thumb ) ) {
601 $thumb = $this->iconThumb();
607 * @return ThumbnailImage
609 function iconThumb() {
610 global $wgStylePath, $wgStyleDirectory;
612 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
613 foreach( $try as $icon ) {
614 $path = '/common/images/' . $icon;
615 $filepath = $wgStyleDirectory . $path;
616 if( file_exists( $filepath ) ) {
617 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
624 * Create a thumbnail of the image having the specified width.
625 * The thumbnail will not be created if the width is larger than the
626 * image's width. Let the browser do the scaling in this case.
627 * The thumbnail is stored on disk and is only computed if the thumbnail
628 * file does not exist OR if it is older than the image.
629 * Returns an object which can return the pathname, URL, and physical
630 * pixel size of the thumbnail -- or null on failure.
632 * @return ThumbnailImage
635 function /* private */ renderThumb( $width, $useScript = true ) {
636 global $wgUseSquid, $wgInternalServer;
637 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
639 $width = IntVal( $width );
642 if ( ! $this->exists() )
644 # If there is no image, there will be no thumbnail
648 # Sanity check $width
654 if( $width > $this->width
&& !$this->mustRender() ) {
655 # Don't make an image bigger than the source
656 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
659 $height = floor( $this->height
* ( $width/$this->width
) );
661 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
662 if ( $isScriptUrl && $useScript ) {
663 // Use thumb.php to render the image
664 return new ThumbnailImage( $url, $width, $height );
667 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
668 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
670 if ( !file_exists( $thumbPath ) ) {
671 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
674 if ( file_exists( $oldThumbPath ) ) {
675 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
676 rename( $oldThumbPath, $thumbPath );
679 unlink( $oldThumbPath );
683 $this->reallyRenderThumb( $thumbPath, $width, $height );
686 # This has to be done after the image is updated and present for all machines on NFS,
687 # or else the old version might be stored into the squid again
689 if ( substr( $url, 0, 4 ) == 'http' ) {
690 $urlArr = array( $url );
692 $urlArr = array( $wgInternalServer.$url );
694 wfPurgeSquidServers($urlArr);
698 return new ThumbnailImage( $url, $width, $height, $thumbPath );
699 } // END OF function renderThumb
702 * Really render a thumbnail
706 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
707 global $wgSVGConverters, $wgSVGConverter,
708 $wgUseImageMagick, $wgImageMagickConvertCommand;
712 if( $this->extension
== 'svg' ) {
713 global $wgSVGConverters, $wgSVGConverter;
714 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
715 global $wgSVGConverterPath;
717 array( '$path/', '$width', '$input', '$output' ),
718 array( $wgSVGConverterPath,
720 escapeshellarg( $this->imagePath
),
721 escapeshellarg( $thumbPath ) ),
722 $wgSVGConverters[$wgSVGConverter] );
723 $conv = shell_exec( $cmd );
727 } elseif ( $wgUseImageMagick ) {
729 # Specify white background color, will be used for transparent images
730 # in Internet Explorer/Windows instead of default black.
731 $cmd = $wgImageMagickConvertCommand .
732 " -quality 85 -background white -geometry {$width} ".
733 escapeshellarg($this->imagePath
) . " " .
734 escapeshellarg($thumbPath);
735 $conv = shell_exec( $cmd );
737 # Use PHP's builtin GD library functions.
739 # First find out what kind of file this is, and select the correct
740 # input routine for this.
744 switch( $this->type
) {
746 $src_image = imagecreatefromgif( $this->imagePath
);
749 $src_image = imagecreatefromjpeg( $this->imagePath
);
753 $src_image = imagecreatefrompng( $this->imagePath
);
754 $truecolor = ( $this->bits
> 8 );
756 case 15: # WBMP for WML
757 $src_image = imagecreatefromwbmp( $this->imagePath
);
760 $src_image = imagecreatefromxbm( $this->imagePath
);
763 return 'Image type not supported';
767 $dst_image = imagecreatetruecolor( $width, $height );
769 $dst_image = imagecreate( $width, $height );
771 imagecopyresampled( $dst_image, $src_image,
773 $width, $height, $this->width
, $this->height
);
774 switch( $this->type
) {
779 imagepng( $dst_image, $thumbPath );
782 imageinterlace( $dst_image );
783 imagejpeg( $dst_image, $thumbPath, 95 );
788 imagedestroy( $dst_image );
789 imagedestroy( $src_image );
792 # Check for zero-sized thumbnails. Those can be generated when
793 # no disk space is available or some other error occurs
795 if( file_exists( $thumbPath ) ) {
796 $thumbstat = stat( $thumbPath );
797 if( $thumbstat['size'] == 0 ) {
798 unlink( $thumbPath );
804 * Get all thumbnail names previously generated for this image
806 function getThumbnails( $shared = false ) {
807 if ( Image
::isHashed( $shared ) ) {
810 $dir = wfImageThumbDir( $this->name
, $shared );
812 // This generates an error on failure, hence the @
813 $handle = @opendir
( $dir );
816 while ( false !== ( $file = readdir($handle) ) ) {
817 if ( $file{0} != '.' ) {
831 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
833 function purgeCache( $archiveFiles = array(), $shared = false ) {
834 global $wgInternalServer, $wgUseSquid;
836 // Refresh metadata cache
838 $this->loadFromFile();
839 $this->saveToCache();
842 $files = $this->getThumbnails( $shared );
843 $dir = wfImageThumbDir( $this->name
, $shared );
845 foreach ( $files as $file ) {
846 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
847 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
848 @unlink
( "$dir/$file" );
854 $urls[] = $wgInternalServer . $this->getViewURL();
855 foreach ( $archiveFiles as $file ) {
856 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
858 wfPurgeSquidServers( $urls );
863 * Return the image history of this image, line by line.
864 * starts with current version, then old versions.
865 * uses $this->historyLine to check which line to return:
866 * 0 return line for current version
867 * 1 query for old versions, return first one
868 * 2, ... return next old version from above query
872 function nextHistoryLine() {
873 $fname = 'Image::nextHistoryLine()';
874 $dbr =& wfGetDB( DB_SLAVE
);
875 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
876 $this->historyRes
= $dbr->select( 'image',
877 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
878 array( 'img_name' => $this->title
->getDBkey() ),
881 if ( 0 == wfNumRows( $this->historyRes
) ) {
884 } else if ( $this->historyLine
== 1 ) {
885 $this->historyRes
= $dbr->select( 'oldimage',
886 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
887 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
888 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
891 $this->historyLine ++
;
893 return $dbr->fetchObject( $this->historyRes
);
897 * Reset the history pointer to the first element of the history
900 function resetHistory() {
901 $this->historyLine
= 0;
905 * Return true if the file is of a type that can't be directly
906 * rendered by typical browsers and needs to be re-rasterized.
909 function mustRender() {
911 return ( $this->extension
== 'svg' );
915 * Return the full filesystem path to the file. Note that this does
916 * not mean that a file actually exists under that location.
918 * This path depends on whether directory hashing is active or not,
919 * i.e. whether the images are all found in the same directory,
920 * or in hashed paths like /images/3/3c.
923 * @param boolean $fromSharedDirectory Return the path to the file
924 * in a shared repository (see $wgUseSharedRepository and related
925 * options in DefaultSettings.php) instead of a local one.
928 function getFullPath( $fromSharedRepository = false ) {
929 global $wgUploadDirectory, $wgSharedUploadDirectory;
930 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
932 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
935 // $wgSharedUploadDirectory may be false, if thumb.php is used
937 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
949 function isHashed( $shared ) {
950 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
951 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
958 function isKnownImageExtension( $ext ) {
959 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
960 return in_array( $ext, $extensions );
964 * Record an image upload in the upload log and the image table
966 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
967 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
968 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
970 $fname = 'Image::recordUpload';
971 $dbw =& wfGetDB( DB_MASTER
);
973 # img_name must be unique
974 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
975 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
978 // Delete thumbnails and refresh the metadata cache
981 // Fail now if the image isn't there
982 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
986 if ( $wgUseCopyrightUpload ) {
987 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
988 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
989 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
994 $now = $dbw->timestamp();
996 # Test to see if the row exists using INSERT IGNORE
997 # This avoids race conditions by locking the row until the commit, and also
998 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
999 $dbw->insert( 'image',
1001 'img_name' => $this->name
,
1002 'img_size'=> $this->size
,
1003 'img_width' => $this->width
,
1004 'img_height' => $this->height
,
1005 'img_bits' => $this->bits
,
1006 'img_type' => $this->type
,
1007 'img_timestamp' => $now,
1008 'img_description' => $desc,
1009 'img_user' => $wgUser->getID(),
1010 'img_user_text' => $wgUser->getName(),
1013 $descTitle = $this->getTitle();
1014 $purgeURLs = array();
1016 if ( $dbw->affectedRows() ) {
1017 # Successfully inserted, this is a new image
1018 $id = $descTitle->getArticleID();
1021 $article = new Article( $descTitle );
1022 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1025 # Collision, this is an update of an image
1026 # Insert previous contents into oldimage
1027 $dbw->insertSelect( 'oldimage', 'image',
1029 'oi_name' => 'img_name',
1030 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1031 'oi_size' => 'img_size',
1032 'oi_width' => 'img_width',
1033 'oi_height' => 'img_height',
1034 'oi_bits' => 'img_bits',
1035 'oi_type' => 'img_type',
1036 'oi_timestamp' => 'img_timestamp',
1037 'oi_description' => 'img_description',
1038 'oi_user' => 'img_user',
1039 'oi_user_text' => 'img_user_text',
1040 ), array( 'img_name' => $this->name
), $fname
1043 # Update the current image row
1044 $dbw->update( 'image',
1046 'img_size' => $this->size
,
1047 'img_width' => $this->width
,
1048 'img_height' => $this->height
,
1049 'img_bits' => $this->bits
,
1050 'img_type' => $this->type
,
1051 'img_timestamp' => $now,
1052 'img_user' => $wgUser->getID(),
1053 'img_user_text' => $wgUser->getName(),
1054 'img_description' => $desc,
1055 ), array( /* WHERE */
1056 'img_name' => $this->name
1060 # Invalidate the cache for the description page
1061 $descTitle->invalidateCache();
1062 $purgeURLs[] = $descTitle->getInternalURL();
1065 # Invalidate cache for all pages using this image
1066 $linksTo = $this->getLinksTo();
1068 if ( $wgUseSquid ) {
1069 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1070 array_push( $wgPostCommitUpdateList, $u );
1072 Title
::touchArray( $linksTo );
1074 $log = new LogPage( 'upload' );
1075 $log->addEntry( 'upload', $descTitle, $desc );
1081 * Get an array of Title objects which are articles which use this image
1082 * Also adds their IDs to the link cache
1084 * This is mostly copied from Title::getLinksTo()
1086 function getLinksTo( $options = '' ) {
1087 global $wgLinkCache;
1088 $fname = 'Image::getLinksTo';
1089 wfProfileIn( $fname );
1092 $db =& wfGetDB( DB_MASTER
);
1094 $db =& wfGetDB( DB_SLAVE
);
1097 extract( $db->tableNames( 'page', 'imagelinks' ) );
1098 $encName = $db->addQuotes( $this->name
);
1099 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1100 $res = $db->query( $sql, $fname );
1103 if ( $db->numRows( $res ) ) {
1104 while ( $row = $db->fetchObject( $res ) ) {
1105 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1106 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1107 $retVal[] = $titleObj;
1111 $db->freeResult( $res );
1115 function retrieveExifData () {
1116 global $wgShowEXIF ;
1117 if ( ! $wgShowEXIF ) return array () ;
1119 $file = $this->getImagePath () ;
1120 $per = new phpExifReader ( $file ) ;
1121 $per->processFile () ;
1122 $a = $per->getImageInfo() ;
1123 unset ( $a["FileName"] ) ;
1124 unset ( $a["Thumbnail"] ) ;
1128 function getExifData () {
1129 return $this->retrieveExifData () ;
1132 function storeExifData () {
1139 * Returns the image directory of an image
1140 * If the directory does not exist, it is created.
1141 * The result is an absolute path.
1143 * This function is called from thumb.php before Setup.php is included
1145 * @param string $fname file name of the image file
1148 function wfImageDir( $fname ) {
1149 global $wgUploadDirectory, $wgHashedUploadDirectory;
1151 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1153 $hash = md5( $fname );
1154 $oldumask = umask(0);
1155 $dest = $wgUploadDirectory . '/' . $hash{0};
1156 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1157 $dest .= '/' . substr( $hash, 0, 2 );
1158 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1165 * Returns the image directory of an image's thubnail
1166 * If the directory does not exist, it is created.
1167 * The result is an absolute path.
1169 * This function is called from thumb.php before Setup.php is included
1171 * @param string $fname file name of the original image file
1172 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1173 * @param boolean $shared (optional) use the shared upload directory
1176 function wfImageThumbDir( $fname, $shared = false ) {
1177 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1178 if ( Image
::isHashed( $shared ) ) {
1179 $dir = "$base/$fname";
1181 if ( !is_dir( $base ) ) {
1182 $oldumask = umask(0);
1183 @mkdir
( $base, 0777 );
1187 if ( ! is_dir( $dir ) ) {
1188 $oldumask = umask(0);
1189 @mkdir
( $dir, 0777 );
1200 * Old thumbnail directory, kept for conversion
1202 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1203 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1207 * Returns the image directory of an image's old version
1208 * If the directory does not exist, it is created.
1209 * The result is an absolute path.
1211 * This function is called from thumb.php before Setup.php is included
1213 * @param string $fname file name of the thumbnail file, including file size prefix
1214 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1215 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1218 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1219 global $wgUploadDirectory, $wgHashedUploadDirectory,
1220 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1221 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1222 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1223 if (!$hashdir) { return $dir.'/'.$subdir; }
1224 $hash = md5( $fname );
1225 $oldumask = umask(0);
1227 # Suppress warning messages here; if the file itself can't
1228 # be written we'll worry about it then.
1229 wfSuppressWarnings();
1231 $archive = $dir.'/'.$subdir;
1232 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1233 $archive .= '/' . $hash{0};
1234 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1235 $archive .= '/' . substr( $hash, 0, 2 );
1236 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1238 wfRestoreWarnings();
1245 * Return the hash path component of an image path (URL or filesystem),
1246 * e.g. "/3/3c/", or just "/" if hashing is not used.
1248 * @param $dbkey The filesystem / database name of the file
1249 * @param $fromSharedDirectory Use the shared file repository? It may
1250 * use different hash settings from the local one.
1252 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1253 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1254 global $wgHashedUploadDirectory;
1256 if( Image
::isHashed( $fromSharedDirectory ) ) {
1257 $hash = md5($dbkey);
1258 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1265 * Returns the image URL of an image's old version
1267 * @param string $fname file name of the image file
1268 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1271 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1272 global $wgUploadPath, $wgHashedUploadDirectory;
1274 if ($wgHashedUploadDirectory) {
1275 $hash = md5( substr( $name, 15) );
1276 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1277 substr( $hash, 0, 2 ) . '/'.$name;
1279 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1281 return wfUrlencode($url);
1285 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1286 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1288 * @param string $length
1289 * @return int Length in pixels
1291 function wfScaleSVGUnit( $length ) {
1292 static $unitLength = array(
1299 '' => 1.0, // "User units" pixels by default
1300 '%' => 2.0, // Fake it!
1302 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1303 $length = FloatVal( $matches[1] );
1304 $unit = $matches[2];
1305 return round( $length * $unitLength[$unit] );
1308 return round( FloatVal( $length ) );
1313 * Compatible with PHP getimagesize()
1314 * @todo support gzipped SVGZ
1315 * @todo check XML more carefully
1316 * @todo sensible defaults
1318 * @param string $filename
1321 function wfGetSVGsize( $filename ) {
1325 // Read a chunk of the file
1326 $f = fopen( $filename, "rt" );
1327 if( !$f ) return false;
1328 $chunk = fread( $f, 4096 );
1331 // Uber-crappy hack! Run through a real XML parser.
1332 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1336 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1337 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1339 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1340 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1343 return array( $width, $height, 'SVG',
1344 "width=\"$width\" height=\"$height\"" );
1348 * Is an image on the bad image list?
1350 function wfIsBadImage( $name ) {
1353 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1354 foreach ( $lines as $line ) {
1355 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1356 $t = Title
::newFromText( $m[1] );
1357 if ( $t->getDBkey() == $name ) {
1368 * Wrapper class for thumbnail images
1369 * @package MediaWiki
1371 class ThumbnailImage
{
1373 * @param string $path Filesystem path to the thumb
1374 * @param string $url URL path to the thumb
1377 function ThumbnailImage( $url, $width, $height, $path = false ) {
1379 $this->width
= $width;
1380 $this->height
= $height;
1381 $this->path
= $path;
1385 * @return string The thumbnail URL
1392 * Return HTML <img ... /> tag for the thumbnail, will include
1393 * width and height attributes and a blank alt text (as required).
1395 * You can set or override additional attributes by passing an
1396 * associative array of name => data pairs. The data will be escaped
1397 * for HTML output, so should be in plaintext.
1399 * @param array $attribs
1403 function toHtml( $attribs = array() ) {
1404 $attribs['src'] = $this->url
;
1405 $attribs['width'] = $this->width
;
1406 $attribs['height'] = $this->height
;
1407 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1410 foreach( $attribs as $name => $data ) {
1411 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';