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->fromSharedDirectory
= true;
109 $this->dataLoaded
= true;
114 $this->name
= $cachedValues['name'];
115 $this->imagePath
= $cachedValues['imagePath'];
116 $this->fileExists
= $cachedValues['fileExists'];
117 $this->width
= $cachedValues['width'];
118 $this->height
= $cachedValues['height'];
119 $this->bits
= $cachedValues['bits'];
120 $this->type
= $cachedValues['type'];
121 $this->fromSharedDirectory
= false;
122 $this->dataLoaded
= true;
126 wfProfileOut( $fname );
127 return $this->dataLoaded
;
131 * Save the image metadata to memcached
133 function saveToCache() {
136 // We can't cache metadata for non-existent files, because if the file later appears
137 // in commons, the local keys won't be purged.
138 if ( $this->fileExists
) {
139 $keys = $this->getCacheKeys();
141 $cachedValues = array('name' => $this->name
,
142 'imagePath' => $this->imagePath
,
143 'fileExists' => $this->fileExists
,
144 'fromShared' => $this->fromSharedDirectory
,
145 'width' => $this->width
,
146 'height' => $this->height
,
147 'bits' => $this->bits
,
148 'type' => $this->type
);
150 $wgMemc->set( $keys[0], $cachedValues );
155 * Load metadata from the file itself
157 function loadFromFile() {
158 global $wgUseSharedUploads, $wgSharedUploadDirectory;
159 $fname = 'Image::loadFromFile';
160 wfProfileIn( $fname );
161 $this->imagePath
= $this->getFullPath();
162 $this->fileExists
= file_exists( $this->imagePath
);
165 # If the file is not found, and a non-wiki shared upload directory is used, look for it there.
166 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
167 # In case we're on a wgCapitalLinks=false wiki, we
168 # capitalize the first letter of the filename before
169 # looking it up in the shared repository.
170 $this->name
= $wgLang->ucfirst($name);
172 $this->imagePath
= $this->getFullPath(true);
173 $this->fileExists
= file_exists( $this->imagePath
);
174 $this->fromSharedDirectory
= true;
177 if ( $this->fileExists
) {
179 $s = stat( $this->imagePath
);
180 $this->size
= $s['size'];
183 # Don't try to get the width and height of sound and video files, that's bad for performance
184 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
186 } elseif( $this->extension
== 'svg' ) {
187 wfSuppressWarnings();
188 $gis = wfGetSVGsize( $this->imagePath
);
191 wfSuppressWarnings();
192 $gis = getimagesize( $this->imagePath
);
196 if( $gis === false ) {
202 $this->width
= $gis[0];
203 $this->height
= $gis[1];
204 $this->type
= $gis[2];
205 if ( isset( $gis['bits'] ) ) {
206 $this->bits
= $gis['bits'];
211 $this->dataLoaded
= true;
212 wfProfileOut( $fname );
216 * Load image metadata from the DB
218 function loadFromDB() {
219 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
220 $fname = 'Image::loadFromDB';
221 wfProfileIn( $fname );
223 $dbr =& wfGetDB( DB_SLAVE
);
224 $row = $dbr->selectRow( 'image',
225 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
226 array( 'img_name' => $this->name
), $fname );
228 $this->fromSharedDirectory
= false;
229 $this->fileExists
= true;
230 $this->loadFromRow( $row );
231 $this->imagePath
= $this->getFullPath();
232 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
233 # In case we're on a wgCapitalLinks=false wiki, we
234 # capitalize the first letter of the filename before
235 # looking it up in the shared repository.
236 $name = $wgLang->ucfirst($this->name
);
238 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
239 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
240 array( 'img_name' => $name ), $fname );
242 $this->fromSharedDirectory
= true;
243 $this->fileExists
= true;
244 $this->imagePath
= '';
246 $this->loadFromRow( $row );
256 $this->fileExists
= false;
257 $this->fromSharedDirectory
= false;
260 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
261 $this->dataLoaded
= true;
265 * Load image metadata from a DB result row
267 function loadFromRow( &$row ) {
268 $this->size
= $row->img_size
;
269 $this->width
= $row->img_width
;
270 $this->height
= $row->img_height
;
271 $this->bits
= $row->img_bits
;
272 $this->type
= $row->img_type
;
273 $this->dataLoaded
= true;
277 * Load image metadata from cache or DB, unless already loaded
280 if ( !$this->dataLoaded
) {
281 if ( !$this->loadFromCache() ) {
283 if ( $this->fileExists
) {
284 $this->saveToCache();
287 $this->dataLoaded
= true;
292 * Return the name of this image
300 * Return the associated title object
303 function getTitle() {
308 * Return the URL of the image file
314 if($this->fileExists
) {
315 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
323 function getViewURL() {
324 if( $this->mustRender() ) {
325 return $this->createThumb( $this->getWidth() );
327 return $this->getURL();
332 * Return the image path of the image in the
333 * local file system as an absolute path
336 function getImagePath() {
338 return $this->imagePath
;
342 * Return the width of the image
344 * Returns -1 if the file specified is not a known image type
347 function getWidth() {
353 * Return the height of the image
355 * Returns -1 if the file specified is not a known image type
358 function getHeight() {
360 return $this->height
;
364 * Return the size of the image file, in bytes
373 * Return the type of the image
387 * Return the escapeLocalURL of this image
390 function getEscapeLocalURL() {
392 return $this->title
->escapeLocalURL();
396 * Return the escapeFullURL of this image
399 function getEscapeFullURL() {
401 return $this->title
->escapeFullURL();
405 * Return the URL of an image, provided its name.
407 * @param string $name Name of the image, without the leading "Image:"
408 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
412 function imageUrl( $name, $fromSharedDirectory = false ) {
413 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
414 if($fromSharedDirectory) {
416 $path = $wgSharedUploadPath;
418 $base = $wgUploadBaseUrl;
419 $path = $wgUploadPath;
421 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
422 return wfUrlencode( $url );
426 * Returns true if the image file exists on disk.
432 return $this->fileExists
;
439 function thumbUrl( $width, $subdir='thumb') {
440 global $wgUploadPath, $wgUploadBaseUrl,
441 $wgSharedUploadPath,$wgSharedUploadDirectory;
442 $name = $this->thumbName( $width );
443 if($this->fromSharedDirectory
) {
445 $path = $wgSharedUploadPath;
447 $base = $wgUploadBaseUrl;
448 $path = $wgUploadPath;
450 $url = "{$base}{$path}/{$subdir}" .
451 wfGetHashPath($name, $this->fromSharedDirectory
)
453 return wfUrlencode($url);
457 * Return the file name of a thumbnail of the specified width
459 * @param integer $width Width of the thumbnail image
460 * @param boolean $shared Does the thumbnail come from the shared repository?
463 function thumbName( $width, $shared=false ) {
464 $thumb = $width."px-".$this->name
;
465 if( $this->extension
== 'svg' ) {
466 # Rasterize SVG vector images to PNG
473 * Create a thumbnail of the image having the specified width/height.
474 * The thumbnail will not be created if the width is larger than the
475 * image's width. Let the browser do the scaling in this case.
476 * The thumbnail is stored on disk and is only computed if the thumbnail
477 * file does not exist OR if it is older than the image.
480 * Keeps aspect ratio of original image. If both width and height are
481 * specified, the generated image will be no bigger than width x height,
482 * and will also have correct aspect ratio.
484 * @param integer $width maximum width of the generated thumbnail
485 * @param integer $height maximum height of the image (optional)
488 function createThumb( $width, $height=-1 ) {
489 $thumb = $this->getThumbnail( $width, $height );
490 if( is_null( $thumb ) ) return '';
491 return $thumb->getUrl();
495 * As createThumb, but returns a ThumbnailImage object. This can
496 * provide access to the actual file, the real size of the thumb,
497 * and can produce a convenient <img> tag for you.
499 * @param integer $width maximum width of the generated thumbnail
500 * @param integer $height maximum height of the image (optional)
501 * @return ThumbnailImage
504 function &getThumbnail( $width, $height=-1 ) {
505 if ( $height == -1 ) {
506 return $this->renderThumb( $width );
508 if ( $width < $this->width
) {
509 $thumbheight = $this->height
* $width / $this->width
;
510 $thumbwidth = $width;
512 $thumbheight = $this->height
;
513 $thumbwidth = $this->width
;
515 if ( $thumbheight > $height ) {
516 $thumbwidth = $thumbwidth * $height / $thumbheight;
517 $thumbheight = $height;
519 $thumb = $this->renderThumb( $thumbwidth );
520 if( is_null( $thumb ) ) {
521 $thumb = $this->iconThumb();
527 * @return ThumbnailImage
529 function iconThumb() {
530 global $wgStylePath, $wgStyleDirectory;
532 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
533 foreach( $try as $icon ) {
534 $path = '/common/images/' . $icon;
535 $filepath = $wgStyleDirectory . $path;
536 if( file_exists( $filepath ) ) {
537 return new ThumbnailImage( $filepath, $wgStylePath . $path );
544 * Create a thumbnail of the image having the specified width.
545 * The thumbnail will not be created if the width is larger than the
546 * image's width. Let the browser do the scaling in this case.
547 * The thumbnail is stored on disk and is only computed if the thumbnail
548 * file does not exist OR if it is older than the image.
549 * Returns an object which can return the pathname, URL, and physical
550 * pixel size of the thumbnail -- or null on failure.
552 * @return ThumbnailImage
555 function /* private */ renderThumb( $width ) {
556 global $wgImageMagickConvertCommand;
557 global $wgUseImageMagick;
558 global $wgUseSquid, $wgInternalServer;
560 $width = IntVal( $width );
562 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
563 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
564 $thumbUrl = $this->thumbUrl( $width );
565 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
566 if ( ! $this->exists() )
568 # If there is no image, there will be no thumbnail
572 # Sanity check $width
578 if( $width > $this->width
&& !$this->mustRender() ) {
579 # Don't make an image bigger than the source
580 return new ThumbnailImage( $this->getImagePath(), $this->getViewURL() );
583 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
584 if( $this->extension
== 'svg' ) {
585 global $wgSVGConverters, $wgSVGConverter;
586 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
587 global $wgSVGConverterPath;
589 array( '$path/', '$width', '$input', '$output' ),
590 array( $wgSVGConverterPath,
592 escapeshellarg( $this->imagePath
),
593 escapeshellarg( $thumbPath ) ),
594 $wgSVGConverters[$wgSVGConverter] );
595 $conv = shell_exec( $cmd );
599 } elseif ( $wgUseImageMagick ) {
601 # Specify white background color, will be used for transparent images
602 # in Internet Explorer/Windows instead of default black.
603 $cmd = $wgImageMagickConvertCommand .
604 " -quality 85 -background white -geometry {$width} ".
605 escapeshellarg($this->imagePath
) . " " .
606 escapeshellarg($thumbPath);
607 $conv = shell_exec( $cmd );
609 # Use PHP's builtin GD library functions.
611 # First find out what kind of file this is, and select the correct
612 # input routine for this.
616 switch( $this->type
) {
618 $src_image = imagecreatefromgif( $this->imagePath
);
621 $src_image = imagecreatefromjpeg( $this->imagePath
);
625 $src_image = imagecreatefrompng( $this->imagePath
);
626 $truecolor = ( $this->bits
> 8 );
628 case 15: # WBMP for WML
629 $src_image = imagecreatefromwbmp( $this->imagePath
);
632 $src_image = imagecreatefromxbm( $this->imagePath
);
635 return 'Image type not supported';
638 $height = floor( $this->height
* ( $width/$this->width
) );
640 $dst_image = imagecreatetruecolor( $width, $height );
642 $dst_image = imagecreate( $width, $height );
644 imagecopyresampled( $dst_image, $src_image,
646 $width, $height, $this->width
, $this->height
);
647 switch( $this->type
) {
652 #$thumbUrl .= ".png";
653 #$thumbPath .= ".png";
654 imagepng( $dst_image, $thumbPath );
657 #$thumbUrl .= ".jpg";
658 #$thumbPath .= ".jpg";
659 imageinterlace( $dst_image );
660 imagejpeg( $dst_image, $thumbPath, 95 );
665 imagedestroy( $dst_image );
666 imagedestroy( $src_image );
669 # Check for zero-sized thumbnails. Those can be generated when
670 # no disk space is available or some other error occurs
672 if( file_exists( $thumbPath ) ) {
673 $thumbstat = stat( $thumbPath );
674 if( $thumbstat['size'] == 0 ) {
675 unlink( $thumbPath );
680 # This has to be done after the image is updated and present for all machines on NFS,
681 # or else the old version might be stored into the squid again
684 $wgInternalServer.$thumbUrl
686 wfPurgeSquidServers($urlArr);
689 return new ThumbnailImage( $thumbPath, $thumbUrl );
690 } // END OF function createThumb
693 * Return the image history of this image, line by line.
694 * starts with current version, then old versions.
695 * uses $this->historyLine to check which line to return:
696 * 0 return line for current version
697 * 1 query for old versions, return first one
698 * 2, ... return next old version from above query
702 function nextHistoryLine() {
703 $fname = 'Image::nextHistoryLine()';
704 $dbr =& wfGetDB( DB_SLAVE
);
705 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
706 $this->historyRes
= $dbr->select( 'image',
707 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
708 array( 'img_name' => $this->title
->getDBkey() ),
711 if ( 0 == wfNumRows( $this->historyRes
) ) {
714 } else if ( $this->historyLine
== 1 ) {
715 $this->historyRes
= $dbr->select( 'oldimage',
716 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
717 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
718 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
721 $this->historyLine ++
;
723 return $dbr->fetchObject( $this->historyRes
);
727 * Reset the history pointer to the first element of the history
730 function resetHistory() {
731 $this->historyLine
= 0;
735 * Return true if the file is of a type that can't be directly
736 * rendered by typical browsers and needs to be re-rasterized.
739 function mustRender() {
741 return ( $this->extension
== 'svg' );
745 * Return the full filesystem path to the file. Note that this does
746 * not mean that a file actually exists under that location.
748 * This path depends on whether directory hashing is active or not,
749 * i.e. whether the images are all found in the same directory,
750 * or in hashed paths like /images/3/3c.
753 * @param boolean $fromSharedDirectory Return the path to the file
754 * in a shared repository (see $wgUseSharedRepository and related
755 * options in DefaultSettings.php) instead of a local one.
758 function getFullPath( $fromSharedRepository = false ) {
759 global $wgUploadDirectory, $wgSharedUploadDirectory;
760 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
762 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
765 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
773 function isKnownImageExtension( $ext ) {
774 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
775 return in_array( $ext, $extensions );
779 * Record an image upload in the upload log and the image table
781 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
782 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
783 global $wgUseCopyrightUpload;
785 $fname = 'Image::recordUpload';
786 $dbw =& wfGetDB( DB_MASTER
);
788 # img_name must be unique
789 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
790 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
793 // Fill metadata fields by querying the file
794 $this->loadFromFile();
795 $this->saveToCache();
797 // Fail now if the image isn't there
798 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
802 if ( $wgUseCopyrightUpload ) {
803 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
804 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
805 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
810 $now = wfTimestampNow();
812 # Test to see if the row exists using INSERT IGNORE
813 # This avoids race conditions by locking the row until the commit, and also
814 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
815 $dbw->insert( 'image',
817 'img_name' => $this->name
,
818 'img_size'=> $this->size
,
819 'img_width' => $this->width
,
820 'img_height' => $this->height
,
821 'img_bits' => $this->bits
,
822 'img_type' => $this->type
,
823 'img_timestamp' => $dbw->timestamp($now),
824 'img_description' => $desc,
825 'img_user' => $wgUser->getID(),
826 'img_user_text' => $wgUser->getName(),
829 $descTitle = $this->getTitle();
831 if ( $dbw->affectedRows() ) {
832 # Successfully inserted, this is a new image
833 $id = $descTitle->getArticleID();
836 $article = new Article( $descTitle );
837 $article->insertNewArticle( $textdesc, $desc, false, false, true );
840 # Collision, this is an update of an image
841 # Insert previous contents into oldimage
842 $dbw->insertSelect( 'oldimage', 'image',
844 'oi_name' => 'img_name',
845 'oi_archive_name' => $dbw->addQuotes( $oldver ),
846 'oi_size' => 'img_size',
847 'oi_width' => 'img_width',
848 'oi_height' => 'img_height',
849 'oi_bits' => 'img_bits',
850 'oi_type' => 'img_type',
851 'oi_timestamp' => 'img_timestamp',
852 'oi_description' => 'img_description',
853 'oi_user' => 'img_user',
854 'oi_user_text' => 'img_user_text',
855 ), array( 'img_name' => $this->name
), $fname
858 # Update the current image row
859 $dbw->update( 'image',
861 'img_size' => $this->size
,
862 'img_width' => $this->width
,
863 'img_height' => $this->height
,
864 'img_bits' => $this->bits
,
865 'img_type' => $this->type
,
866 'img_timestamp' => $dbw->timestamp(),
867 'img_user' => $wgUser->getID(),
868 'img_user_text' => $wgUser->getName(),
869 'img_description' => $desc,
870 ), array( /* WHERE */
871 'img_name' => $this->name
875 # Invalidate the cache for the description page
876 $descTitle->invalidateCache();
879 $log = new LogPage( 'upload' );
880 $log->addEntry( 'upload', $descTitle, $desc );
889 * Returns the image directory of an image
890 * If the directory does not exist, it is created.
891 * The result is an absolute path.
893 * @param string $fname file name of the image file
896 function wfImageDir( $fname ) {
897 global $wgUploadDirectory, $wgHashedUploadDirectory;
899 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
901 $hash = md5( $fname );
902 $oldumask = umask(0);
903 $dest = $wgUploadDirectory . '/' . $hash{0};
904 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
905 $dest .= '/' . substr( $hash, 0, 2 );
906 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
913 * Returns the image directory of an image's thubnail
914 * If the directory does not exist, it is created.
915 * The result is an absolute path.
917 * @param string $fname file name of the thumbnail file, including file size prefix
918 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
919 * @param boolean $shared (optional) use the shared upload directory
922 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
923 return wfImageArchiveDir( $fname, $subdir, $shared );
927 * Returns the image directory of an image's old version
928 * If the directory does not exist, it is created.
929 * The result is an absolute path.
931 * @param string $fname file name of the thumbnail file, including file size prefix
932 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
933 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
936 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
937 global $wgUploadDirectory, $wgHashedUploadDirectory,
938 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
939 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
940 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
941 if (!$hashdir) { return $dir.'/'.$subdir; }
942 $hash = md5( $fname );
943 $oldumask = umask(0);
944 # Suppress warning messages here; if the file itself can't
945 # be written we'll worry about it then.
946 $archive = $dir.'/'.$subdir;
947 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
948 $archive .= '/' . $hash{0};
949 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
950 $archive .= '/' . substr( $hash, 0, 2 );
951 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
959 * Return the hash path component of an image path (URL or filesystem),
960 * e.g. "/3/3c/", or just "/" if hashing is not used.
962 * @param $dbkey The filesystem / database name of the file
963 * @param $fromSharedDirectory Use the shared file repository? It may
964 * use different hash settings from the local one.
966 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
967 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
968 global $wgHashedUploadDirectory;
970 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
971 $wgHashedUploadDirectory;
974 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
981 * Returns the image URL of an image's old version
983 * @param string $fname file name of the image file
984 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
987 function wfImageArchiveUrl( $name, $subdir='archive' ) {
988 global $wgUploadPath, $wgHashedUploadDirectory;
990 if ($wgHashedUploadDirectory) {
991 $hash = md5( substr( $name, 15) );
992 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
993 substr( $hash, 0, 2 ) . '/'.$name;
995 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
997 return wfUrlencode($url);
1001 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1002 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1004 * @param string $length
1005 * @return int Length in pixels
1007 function wfScaleSVGUnit( $length ) {
1008 static $unitLength = array(
1015 '' => 1.0, // "User units" pixels by default
1016 '%' => 2.0, // Fake it!
1018 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1019 $length = FloatVal( $matches[1] );
1020 $unit = $matches[2];
1021 return round( $length * $unitLength[$unit] );
1024 return round( FloatVal( $length ) );
1029 * Compatible with PHP getimagesize()
1030 * @todo support gzipped SVGZ
1031 * @todo check XML more carefully
1032 * @todo sensible defaults
1034 * @param string $filename
1037 function wfGetSVGsize( $filename ) {
1041 // Read a chunk of the file
1042 $f = fopen( $filename, "rt" );
1043 if( !$f ) return false;
1044 $chunk = fread( $f, 4096 );
1047 // Uber-crappy hack! Run through a real XML parser.
1048 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1052 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1053 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1055 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1056 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1059 return array( $width, $height, 'SVG',
1060 "width=\"$width\" height=\"$height\"" );
1064 * Is an image on the bad image list?
1066 function wfIsBadImage( $name ) {
1069 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1070 foreach ( $lines as $line ) {
1071 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1072 $t = Title
::newFromText( $m[1] );
1073 if ( $t->getDBkey() == $name ) {
1084 * Wrapper class for thumbnail images
1085 * @package MediaWiki
1087 class ThumbnailImage
{
1089 * @param string $path Filesystem path to the thumb
1090 * @param string $url URL path to the thumb
1093 function ThumbnailImage( $path, $url ) {
1095 $this->path
= $path;
1096 $size = @getimagesize
( $this->path
);
1098 $this->width
= $size[0];
1099 $this->height
= $size[1];
1107 * @return string The thumbnail URL
1114 * Return HTML <img ... /> tag for the thumbnail, will include
1115 * width and height attributes and a blank alt text (as required).
1117 * You can set or override additional attributes by passing an
1118 * associative array of name => data pairs. The data will be escaped
1119 * for HTML output, so should be in plaintext.
1121 * @param array $attribs
1125 function toHtml( $attribs = array() ) {
1126 $attribs['src'] = $this->url
;
1127 $attribs['width'] = $this->width
;
1128 $attribs['height'] = $this->height
;
1129 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1132 foreach( $attribs as $name => $data ) {
1133 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1140 * Return the size of the thumbnail file, in bytes or false if the file
1144 function getSize() {
1145 $st = stat( $this->path
);