7 * Class to represent an image
9 * Provides methods to retrieve paths (physical, logical, URL),
10 * to generate thumbnails or for uploading.
18 var $name, # name of the image (constructor)
19 $imagePath, # Path of the image (loadFromXxx)
20 $url, # Image URL (accessor)
21 $title, # Title object for this image (constructor)
22 $fileExists, # does the image file exist on disk? (loadFromXxx)
23 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
24 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
25 $historyRes, # result of the query for the image's history (nextHistoryLine)
28 $bits, # --- returned by getimagesize (loadFromXxx)
31 $size, # Size in bytes (loadFromXxx)
32 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
38 * Create an Image object from an image name
40 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
43 function newFromName( $name ) {
44 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
45 return new Image( $title );
49 * Obsolete factory function, use constructor
51 function newFromTitle( $title ) {
52 return new Image( $title );
55 function Image( $title ) {
56 $this->title
=& $title;
57 $this->name
= $title->getDBkey();
59 $n = strrpos( $this->name
, '.' );
60 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
61 $this->historyLine
= 0;
63 $this->dataLoaded
= false;
67 * Get the memcached keys
68 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
70 function getCacheKeys( $shared = false ) {
71 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
74 $hashedName = md5($this->name
);
75 $keys = array( "$wgDBname:Image:$hashedName" );
76 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
77 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
83 * Try to load image metadata from memcached. Returns true on success.
85 function loadFromCache() {
86 global $wgUseSharedUploads, $wgMemc;
87 $fname = 'Image::loadFromMemcached';
88 wfProfileIn( $fname );
89 $this->dataLoaded
= false;
90 $keys = $this->getCacheKeys();
91 $cachedValues = $wgMemc->get( $keys[0] );
93 // Check if the key existed and belongs to this version of MediaWiki
94 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
95 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
96 # if this is shared file, we need to check if image
97 # in shared repository has not changed
98 if ( isset( $keys[1] ) ) {
99 $commonsCachedValues = $wgMemc->get( $keys[1] );
100 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
101 $this->name
= $commonsCachedValues['name'];
102 $this->imagePath
= $commonsCachedValues['imagePath'];
103 $this->fileExists
= $commonsCachedValues['fileExists'];
104 $this->width
= $commonsCachedValues['width'];
105 $this->height
= $commonsCachedValues['height'];
106 $this->bits
= $commonsCachedValues['bits'];
107 $this->type
= $commonsCachedValues['type'];
108 $this->size
= $commonsCachedValues['size'];
109 $this->fromSharedDirectory
= true;
110 $this->dataLoaded
= true;
111 $this->imagePath
= $this->getFullPath(true);
116 $this->name
= $cachedValues['name'];
117 $this->imagePath
= $cachedValues['imagePath'];
118 $this->fileExists
= $cachedValues['fileExists'];
119 $this->width
= $cachedValues['width'];
120 $this->height
= $cachedValues['height'];
121 $this->bits
= $cachedValues['bits'];
122 $this->type
= $cachedValues['type'];
123 $this->size
= $cachedValues['size'];
124 $this->fromSharedDirectory
= false;
125 $this->dataLoaded
= true;
126 $this->imagePath
= $this->getFullPath();
130 wfProfileOut( $fname );
131 return $this->dataLoaded
;
135 * Save the image metadata to memcached
137 function saveToCache() {
140 // We can't cache metadata for non-existent files, because if the file later appears
141 // in commons, the local keys won't be purged.
142 if ( $this->fileExists
) {
143 $keys = $this->getCacheKeys();
145 $cachedValues = array('name' => $this->name
,
146 'imagePath' => $this->imagePath
,
147 'fileExists' => $this->fileExists
,
148 'fromShared' => $this->fromSharedDirectory
,
149 'width' => $this->width
,
150 'height' => $this->height
,
151 'bits' => $this->bits
,
152 'type' => $this->type
,
153 'size' => $this->size
);
155 $wgMemc->set( $keys[0], $cachedValues );
160 * Load metadata from the file itself
162 function loadFromFile() {
163 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
164 $fname = 'Image::loadFromFile';
165 wfProfileIn( $fname );
166 $this->imagePath
= $this->getFullPath();
167 $this->fileExists
= file_exists( $this->imagePath
);
168 $this->fromSharedDirectory
= false;
171 # If the file is not found, and a shared upload directory is used, look for it there.
172 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
173 # In case we're on a wgCapitalLinks=false wiki, we
174 # capitalize the first letter of the filename before
175 # looking it up in the shared repository.
176 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
177 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
178 if ( $this->fileExists
) {
179 $this->name
= $sharedImage->name
;
180 $this->imagePath
= $this->getFullPath(true);
181 $this->fromSharedDirectory
= true;
185 if ( $this->fileExists
) {
187 $s = stat( $this->imagePath
);
188 $this->size
= $s['size'];
191 # Don't try to get the width and height of sound and video files, that's bad for performance
192 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
194 } elseif( $this->extension
== 'svg' ) {
195 wfSuppressWarnings();
196 $gis = wfGetSVGsize( $this->imagePath
);
199 wfSuppressWarnings();
200 $gis = getimagesize( $this->imagePath
);
204 if( $gis === false ) {
210 $this->width
= $gis[0];
211 $this->height
= $gis[1];
212 $this->type
= $gis[2];
213 if ( isset( $gis['bits'] ) ) {
214 $this->bits
= $gis['bits'];
219 $this->dataLoaded
= true;
220 wfProfileOut( $fname );
224 * Load image metadata from the DB
226 function loadFromDB() {
227 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
228 $fname = 'Image::loadFromDB';
229 wfProfileIn( $fname );
231 $dbr =& wfGetDB( DB_SLAVE
);
232 $row = $dbr->selectRow( 'image',
233 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
234 array( 'img_name' => $this->name
), $fname );
236 $this->fromSharedDirectory
= false;
237 $this->fileExists
= true;
238 $this->loadFromRow( $row );
239 $this->imagePath
= $this->getFullPath();
240 // Check for rows from a previous schema, quietly upgrade them
241 if ( $this->type
== -1 ) {
244 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
245 # In case we're on a wgCapitalLinks=false wiki, we
246 # capitalize the first letter of the filename before
247 # looking it up in the shared repository.
248 $name = $wgLang->ucfirst($this->name
);
250 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
251 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
252 array( 'img_name' => $name ), $fname );
254 $this->fromSharedDirectory
= true;
255 $this->fileExists
= true;
256 $this->imagePath
= $this->getFullPath(true);
258 $this->loadFromRow( $row );
260 // Check for rows from a previous schema, quietly upgrade them
261 if ( $this->type
== -1 ) {
273 $this->fileExists
= false;
274 $this->fromSharedDirectory
= false;
277 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
278 $this->dataLoaded
= true;
282 * Load image metadata from a DB result row
284 function loadFromRow( &$row ) {
285 $this->size
= $row->img_size
;
286 $this->width
= $row->img_width
;
287 $this->height
= $row->img_height
;
288 $this->bits
= $row->img_bits
;
289 $this->type
= $row->img_type
;
290 $this->dataLoaded
= true;
294 * Load image metadata from cache or DB, unless already loaded
297 global $wgSharedUploadDBname, $wgUseSharedUploads;
298 if ( !$this->dataLoaded
) {
299 if ( !$this->loadFromCache() ) {
301 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
302 $this->loadFromFile();
303 } elseif ( $this->fileExists
) {
304 $this->saveToCache();
307 $this->dataLoaded
= true;
312 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
313 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
315 function upgradeRow() {
316 global $wgDBname, $wgSharedUploadDBname;
317 $fname = 'Image::upgradeRow';
318 $this->loadFromFile();
319 $dbw =& wfGetDB( DB_MASTER
);
321 if ( $this->fromSharedDirectory
) {
322 if ( !$wgSharedUploadDBname ) {
326 // Write to the other DB using selectDB, not database selectors
327 // This avoids breaking replication in MySQL
328 $dbw->selectDB( $wgSharedUploadDBname );
330 $dbw->update( '`image`',
332 'img_width' => $this->width
,
333 'img_height' => $this->height
,
334 'img_bits' => $this->bits
,
335 'img_type' => $this->type
,
336 ), array( 'img_name' => $this->name
), $fname
338 if ( $this->fromSharedDirectory
) {
339 $dbw->selectDB( $wgDBname );
344 * Return the name of this image
352 * Return the associated title object
355 function getTitle() {
360 * Return the URL of the image file
366 if($this->fileExists
) {
367 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
375 function getViewURL() {
376 if( $this->mustRender() ) {
377 return $this->createThumb( $this->getWidth() );
379 return $this->getURL();
384 * Return the image path of the image in the
385 * local file system as an absolute path
388 function getImagePath() {
390 return $this->imagePath
;
394 * Return the width of the image
396 * Returns -1 if the file specified is not a known image type
399 function getWidth() {
405 * Return the height of the image
407 * Returns -1 if the file specified is not a known image type
410 function getHeight() {
412 return $this->height
;
416 * Return the size of the image file, in bytes
425 * Return the type of the image
439 * Return the escapeLocalURL of this image
442 function getEscapeLocalURL() {
444 return $this->title
->escapeLocalURL();
448 * Return the escapeFullURL of this image
451 function getEscapeFullURL() {
453 return $this->title
->escapeFullURL();
457 * Return the URL of an image, provided its name.
459 * @param string $name Name of the image, without the leading "Image:"
460 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
464 function imageUrl( $name, $fromSharedDirectory = false ) {
465 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
466 if($fromSharedDirectory) {
468 $path = $wgSharedUploadPath;
470 $base = $wgUploadBaseUrl;
471 $path = $wgUploadPath;
473 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
474 return wfUrlencode( $url );
478 * Returns true if the image file exists on disk.
484 return $this->fileExists
;
491 function thumbUrl( $width, $subdir='thumb') {
492 global $wgUploadPath, $wgUploadBaseUrl,
493 $wgSharedUploadPath,$wgSharedUploadDirectory,
494 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
496 // Generate thumb.php URL if possible
500 if ( $this->fromSharedDirectory
) {
501 if ( $wgSharedThumbnailScriptPath ) {
502 $script = $wgSharedThumbnailScriptPath;
505 if ( $wgThumbnailScriptPath ) {
506 $script = $wgThumbnailScriptPath;
510 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
512 $name = $this->thumbName( $width );
513 if($this->fromSharedDirectory
) {
515 $path = $wgSharedUploadPath;
517 $base = $wgUploadBaseUrl;
518 $path = $wgUploadPath;
520 $url = "{$base}{$path}/{$subdir}" .
521 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
522 . $this->name
.'/'.$name;
523 $url = wfUrlencode( $url );
525 return array( $script !== false, $url );
529 * Return the file name of a thumbnail of the specified width
531 * @param integer $width Width of the thumbnail image
532 * @param boolean $shared Does the thumbnail come from the shared repository?
535 function thumbName( $width ) {
536 $thumb = $width."px-".$this->name
;
537 if( $this->extension
== 'svg' ) {
538 # Rasterize SVG vector images to PNG
545 * Create a thumbnail of the image having the specified width/height.
546 * The thumbnail will not be created if the width is larger than the
547 * image's width. Let the browser do the scaling in this case.
548 * The thumbnail is stored on disk and is only computed if the thumbnail
549 * file does not exist OR if it is older than the image.
552 * Keeps aspect ratio of original image. If both width and height are
553 * specified, the generated image will be no bigger than width x height,
554 * and will also have correct aspect ratio.
556 * @param integer $width maximum width of the generated thumbnail
557 * @param integer $height maximum height of the image (optional)
560 function createThumb( $width, $height=-1 ) {
561 $thumb = $this->getThumbnail( $width, $height );
562 if( is_null( $thumb ) ) return '';
563 return $thumb->getUrl();
567 * As createThumb, but returns a ThumbnailImage object. This can
568 * provide access to the actual file, the real size of the thumb,
569 * and can produce a convenient <img> tag for you.
571 * @param integer $width maximum width of the generated thumbnail
572 * @param integer $height maximum height of the image (optional)
573 * @return ThumbnailImage
576 function &getThumbnail( $width, $height=-1 ) {
577 if ( $height == -1 ) {
578 return $this->renderThumb( $width );
581 if ( $width < $this->width
) {
582 $thumbheight = $this->height
* $width / $this->width
;
583 $thumbwidth = $width;
585 $thumbheight = $this->height
;
586 $thumbwidth = $this->width
;
588 if ( $thumbheight > $height ) {
589 $thumbwidth = $thumbwidth * $height / $thumbheight;
590 $thumbheight = $height;
592 $thumb = $this->renderThumb( $thumbwidth );
593 if( is_null( $thumb ) ) {
594 $thumb = $this->iconThumb();
600 * @return ThumbnailImage
602 function iconThumb() {
603 global $wgStylePath, $wgStyleDirectory;
605 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
606 foreach( $try as $icon ) {
607 $path = '/common/images/' . $icon;
608 $filepath = $wgStyleDirectory . $path;
609 if( file_exists( $filepath ) ) {
610 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
617 * Create a thumbnail of the image having the specified width.
618 * The thumbnail will not be created if the width is larger than the
619 * image's width. Let the browser do the scaling in this case.
620 * The thumbnail is stored on disk and is only computed if the thumbnail
621 * file does not exist OR if it is older than the image.
622 * Returns an object which can return the pathname, URL, and physical
623 * pixel size of the thumbnail -- or null on failure.
625 * @return ThumbnailImage
628 function /* private */ renderThumb( $width, $useScript = true ) {
629 global $wgUseSquid, $wgInternalServer;
630 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
632 $width = IntVal( $width );
635 if ( ! $this->exists() )
637 # If there is no image, there will be no thumbnail
641 # Sanity check $width
647 if( $width > $this->width
&& !$this->mustRender() ) {
648 # Don't make an image bigger than the source
649 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
652 $height = floor( $this->height
* ( $width/$this->width
) );
654 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
655 if ( $isScriptUrl && $useScript ) {
656 // Use thumb.php to render the image
657 return new ThumbnailImage( $url, $width, $height );
660 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
661 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
663 if ( !file_exists( $thumbPath ) ) {
664 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
667 if ( file_exists( $oldThumbPath ) ) {
668 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
669 rename( $oldThumbPath, $thumbPath );
672 unlink( $oldThumbPath );
676 $this->reallyRenderThumb( $thumbPath, $width, $height );
679 # This has to be done after the image is updated and present for all machines on NFS,
680 # or else the old version might be stored into the squid again
682 if ( substr( $url, 0, 4 ) == 'http' ) {
683 $urlArr = array( $url );
685 $urlArr = array( $wgInternalServer.$url );
687 wfPurgeSquidServers($urlArr);
691 return new ThumbnailImage( $url, $width, $height, $thumbPath );
692 } // END OF function renderThumb
695 * Really render a thumbnail
699 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
700 global $wgSVGConverters, $wgSVGConverter,
701 $wgUseImageMagick, $wgImageMagickConvertCommand;
705 if( $this->extension
== 'svg' ) {
706 global $wgSVGConverters, $wgSVGConverter;
707 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
708 global $wgSVGConverterPath;
710 array( '$path/', '$width', '$input', '$output' ),
711 array( $wgSVGConverterPath,
713 escapeshellarg( $this->imagePath
),
714 escapeshellarg( $thumbPath ) ),
715 $wgSVGConverters[$wgSVGConverter] );
716 $conv = shell_exec( $cmd );
720 } elseif ( $wgUseImageMagick ) {
722 # Specify white background color, will be used for transparent images
723 # in Internet Explorer/Windows instead of default black.
724 $cmd = $wgImageMagickConvertCommand .
725 " -quality 85 -background white -geometry {$width} ".
726 escapeshellarg($this->imagePath
) . " " .
727 escapeshellarg($thumbPath);
728 $conv = shell_exec( $cmd );
730 # Use PHP's builtin GD library functions.
732 # First find out what kind of file this is, and select the correct
733 # input routine for this.
737 switch( $this->type
) {
739 $src_image = imagecreatefromgif( $this->imagePath
);
742 $src_image = imagecreatefromjpeg( $this->imagePath
);
746 $src_image = imagecreatefrompng( $this->imagePath
);
747 $truecolor = ( $this->bits
> 8 );
749 case 15: # WBMP for WML
750 $src_image = imagecreatefromwbmp( $this->imagePath
);
753 $src_image = imagecreatefromxbm( $this->imagePath
);
756 return 'Image type not supported';
760 $dst_image = imagecreatetruecolor( $width, $height );
762 $dst_image = imagecreate( $width, $height );
764 imagecopyresampled( $dst_image, $src_image,
766 $width, $height, $this->width
, $this->height
);
767 switch( $this->type
) {
772 imagepng( $dst_image, $thumbPath );
775 imageinterlace( $dst_image );
776 imagejpeg( $dst_image, $thumbPath, 95 );
781 imagedestroy( $dst_image );
782 imagedestroy( $src_image );
785 # Check for zero-sized thumbnails. Those can be generated when
786 # no disk space is available or some other error occurs
788 if( file_exists( $thumbPath ) ) {
789 $thumbstat = stat( $thumbPath );
790 if( $thumbstat['size'] == 0 ) {
791 unlink( $thumbPath );
797 * Get all thumbnail names previously generated for this image
799 function getThumbnails( $shared = false ) {
802 $dir = wfImageThumbDir( $this->name
, $shared );
804 // This generates an error on failure, hence the @
805 $handle = @opendir
( $dir );
808 while ( false !== ( $file = readdir($handle) ) ) {
809 if ( $file{0} != '.' ) {
820 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
822 function purgeCache( $archiveFiles = array(), $shared = false ) {
823 global $wgInternalServer, $wgUseSquid;
825 // Refresh metadata cache
826 $this->loadFromFile();
827 $this->saveToCache();
830 $files = $this->getThumbnails( $shared );
831 $dir = wfImageThumbDir( $this->name
, $shared );
833 foreach ( $files as $file ) {
834 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
835 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
836 @unlink
( "$dir/$file" );
842 $urls[] = $wgInternalServer . $this->getViewURL();
843 foreach ( $archiveFiles as $file ) {
844 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
846 wfPurgeSquidServers( $urls );
851 * Return the image history of this image, line by line.
852 * starts with current version, then old versions.
853 * uses $this->historyLine to check which line to return:
854 * 0 return line for current version
855 * 1 query for old versions, return first one
856 * 2, ... return next old version from above query
860 function nextHistoryLine() {
861 $fname = 'Image::nextHistoryLine()';
862 $dbr =& wfGetDB( DB_SLAVE
);
863 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
864 $this->historyRes
= $dbr->select( 'image',
865 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
866 array( 'img_name' => $this->title
->getDBkey() ),
869 if ( 0 == wfNumRows( $this->historyRes
) ) {
872 } else if ( $this->historyLine
== 1 ) {
873 $this->historyRes
= $dbr->select( 'oldimage',
874 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
875 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
876 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
879 $this->historyLine ++
;
881 return $dbr->fetchObject( $this->historyRes
);
885 * Reset the history pointer to the first element of the history
888 function resetHistory() {
889 $this->historyLine
= 0;
893 * Return true if the file is of a type that can't be directly
894 * rendered by typical browsers and needs to be re-rasterized.
897 function mustRender() {
899 return ( $this->extension
== 'svg' );
903 * Return the full filesystem path to the file. Note that this does
904 * not mean that a file actually exists under that location.
906 * This path depends on whether directory hashing is active or not,
907 * i.e. whether the images are all found in the same directory,
908 * or in hashed paths like /images/3/3c.
911 * @param boolean $fromSharedDirectory Return the path to the file
912 * in a shared repository (see $wgUseSharedRepository and related
913 * options in DefaultSettings.php) instead of a local one.
916 function getFullPath( $fromSharedRepository = false ) {
917 global $wgUploadDirectory, $wgSharedUploadDirectory;
918 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
920 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
923 // $wgSharedUploadDirectory may be false, if thumb.php is used
925 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
937 function isKnownImageExtension( $ext ) {
938 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
939 return in_array( $ext, $extensions );
943 * Record an image upload in the upload log and the image table
945 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
946 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
947 global $wgUseCopyrightUpload;
949 $fname = 'Image::recordUpload';
950 $dbw =& wfGetDB( DB_MASTER
);
952 # img_name must be unique
953 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
954 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
957 // Delete thumbnails and refresh the cache
960 // Fail now if the image isn't there
961 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
965 if ( $wgUseCopyrightUpload ) {
966 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
967 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
968 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
973 $now = wfTimestampNow();
975 # Test to see if the row exists using INSERT IGNORE
976 # This avoids race conditions by locking the row until the commit, and also
977 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
978 $dbw->insert( 'image',
980 'img_name' => $this->name
,
981 'img_size'=> $this->size
,
982 'img_width' => $this->width
,
983 'img_height' => $this->height
,
984 'img_bits' => $this->bits
,
985 'img_type' => $this->type
,
986 'img_timestamp' => $dbw->timestamp($now),
987 'img_description' => $desc,
988 'img_user' => $wgUser->getID(),
989 'img_user_text' => $wgUser->getName(),
992 $descTitle = $this->getTitle();
994 if ( $dbw->affectedRows() ) {
995 # Successfully inserted, this is a new image
996 $id = $descTitle->getArticleID();
999 $article = new Article( $descTitle );
1000 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1003 # Collision, this is an update of an image
1004 # Insert previous contents into oldimage
1005 $dbw->insertSelect( 'oldimage', 'image',
1007 'oi_name' => 'img_name',
1008 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1009 'oi_size' => 'img_size',
1010 'oi_width' => 'img_width',
1011 'oi_height' => 'img_height',
1012 'oi_bits' => 'img_bits',
1013 'oi_type' => 'img_type',
1014 'oi_timestamp' => 'img_timestamp',
1015 'oi_description' => 'img_description',
1016 'oi_user' => 'img_user',
1017 'oi_user_text' => 'img_user_text',
1018 ), array( 'img_name' => $this->name
), $fname
1021 # Update the current image row
1022 $dbw->update( 'image',
1024 'img_size' => $this->size
,
1025 'img_width' => $this->width
,
1026 'img_height' => $this->height
,
1027 'img_bits' => $this->bits
,
1028 'img_type' => $this->type
,
1029 'img_timestamp' => $dbw->timestamp(),
1030 'img_user' => $wgUser->getID(),
1031 'img_user_text' => $wgUser->getName(),
1032 'img_description' => $desc,
1033 ), array( /* WHERE */
1034 'img_name' => $this->name
1038 # Invalidate the cache for the description page
1039 $descTitle->invalidateCache();
1042 $log = new LogPage( 'upload' );
1043 $log->addEntry( 'upload', $descTitle, $desc );
1052 * Returns the image directory of an image
1053 * If the directory does not exist, it is created.
1054 * The result is an absolute path.
1056 * This function is called from thumb.php before Setup.php is included
1058 * @param string $fname file name of the image file
1061 function wfImageDir( $fname ) {
1062 global $wgUploadDirectory, $wgHashedUploadDirectory;
1064 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1066 $hash = md5( $fname );
1067 $oldumask = umask(0);
1068 $dest = $wgUploadDirectory . '/' . $hash{0};
1069 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1070 $dest .= '/' . substr( $hash, 0, 2 );
1071 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1078 * Returns the image directory of an image's thubnail
1079 * If the directory does not exist, it is created.
1080 * The result is an absolute path.
1082 * This function is called from thumb.php before Setup.php is included
1084 * @param string $fname file name of the original image file
1085 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1086 * @param boolean $shared (optional) use the shared upload directory
1089 function wfImageThumbDir( $fname, $shared = false ) {
1090 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1091 $dir = "$base/$fname";
1093 if ( !is_dir( $base ) ) {
1094 $oldumask = umask(0);
1095 @mkdir
( $base, 0777 );
1099 if ( ! is_dir( $dir ) ) {
1100 $oldumask = umask(0);
1101 @mkdir
( $dir, 0777 );
1109 * Old thumbnail directory, kept for conversion
1111 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1112 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1116 * Returns the image directory of an image's old version
1117 * If the directory does not exist, it is created.
1118 * The result is an absolute path.
1120 * This function is called from thumb.php before Setup.php is included
1122 * @param string $fname file name of the thumbnail file, including file size prefix
1123 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1124 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1127 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1128 global $wgUploadDirectory, $wgHashedUploadDirectory,
1129 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1130 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1131 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1132 if (!$hashdir) { return $dir.'/'.$subdir; }
1133 $hash = md5( $fname );
1134 $oldumask = umask(0);
1136 # Suppress warning messages here; if the file itself can't
1137 # be written we'll worry about it then.
1138 wfSuppressWarnings();
1140 $archive = $dir.'/'.$subdir;
1141 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1142 $archive .= '/' . $hash{0};
1143 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1144 $archive .= '/' . substr( $hash, 0, 2 );
1145 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1147 wfRestoreWarnings();
1154 * Return the hash path component of an image path (URL or filesystem),
1155 * e.g. "/3/3c/", or just "/" if hashing is not used.
1157 * @param $dbkey The filesystem / database name of the file
1158 * @param $fromSharedDirectory Use the shared file repository? It may
1159 * use different hash settings from the local one.
1161 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1162 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1163 global $wgHashedUploadDirectory;
1165 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
1166 $wgHashedUploadDirectory;
1168 $hash = md5($dbkey);
1169 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1176 * Returns the image URL of an image's old version
1178 * @param string $fname file name of the image file
1179 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1182 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1183 global $wgUploadPath, $wgHashedUploadDirectory;
1185 if ($wgHashedUploadDirectory) {
1186 $hash = md5( substr( $name, 15) );
1187 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1188 substr( $hash, 0, 2 ) . '/'.$name;
1190 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1192 return wfUrlencode($url);
1196 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1197 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1199 * @param string $length
1200 * @return int Length in pixels
1202 function wfScaleSVGUnit( $length ) {
1203 static $unitLength = array(
1210 '' => 1.0, // "User units" pixels by default
1211 '%' => 2.0, // Fake it!
1213 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1214 $length = FloatVal( $matches[1] );
1215 $unit = $matches[2];
1216 return round( $length * $unitLength[$unit] );
1219 return round( FloatVal( $length ) );
1224 * Compatible with PHP getimagesize()
1225 * @todo support gzipped SVGZ
1226 * @todo check XML more carefully
1227 * @todo sensible defaults
1229 * @param string $filename
1232 function wfGetSVGsize( $filename ) {
1236 // Read a chunk of the file
1237 $f = fopen( $filename, "rt" );
1238 if( !$f ) return false;
1239 $chunk = fread( $f, 4096 );
1242 // Uber-crappy hack! Run through a real XML parser.
1243 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1247 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1248 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1250 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1251 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1254 return array( $width, $height, 'SVG',
1255 "width=\"$width\" height=\"$height\"" );
1259 * Is an image on the bad image list?
1261 function wfIsBadImage( $name ) {
1264 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1265 foreach ( $lines as $line ) {
1266 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1267 $t = Title
::newFromText( $m[1] );
1268 if ( $t->getDBkey() == $name ) {
1279 * Wrapper class for thumbnail images
1280 * @package MediaWiki
1282 class ThumbnailImage
{
1284 * @param string $path Filesystem path to the thumb
1285 * @param string $url URL path to the thumb
1288 function ThumbnailImage( $url, $width, $height, $path = false ) {
1290 $this->width
= $width;
1291 $this->height
= $height;
1292 $this->path
= $path;
1296 * @return string The thumbnail URL
1303 * Return HTML <img ... /> tag for the thumbnail, will include
1304 * width and height attributes and a blank alt text (as required).
1306 * You can set or override additional attributes by passing an
1307 * associative array of name => data pairs. The data will be escaped
1308 * for HTML output, so should be in plaintext.
1310 * @param array $attribs
1314 function toHtml( $attribs = array() ) {
1315 $attribs['src'] = $this->url
;
1316 $attribs['width'] = $this->width
;
1317 $attribs['height'] = $this->height
;
1318 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1321 foreach( $attribs as $name => $data ) {
1322 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';