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;
115 $this->name
= $cachedValues['name'];
116 $this->imagePath
= $cachedValues['imagePath'];
117 $this->fileExists
= $cachedValues['fileExists'];
118 $this->width
= $cachedValues['width'];
119 $this->height
= $cachedValues['height'];
120 $this->bits
= $cachedValues['bits'];
121 $this->type
= $cachedValues['type'];
122 $this->size
= $cachedValues['size'];
123 $this->fromSharedDirectory
= false;
124 $this->dataLoaded
= true;
128 wfProfileOut( $fname );
129 return $this->dataLoaded
;
133 * Save the image metadata to memcached
135 function saveToCache() {
138 // We can't cache metadata for non-existent files, because if the file later appears
139 // in commons, the local keys won't be purged.
140 if ( $this->fileExists
) {
141 $keys = $this->getCacheKeys();
143 $cachedValues = array('name' => $this->name
,
144 'imagePath' => $this->imagePath
,
145 'fileExists' => $this->fileExists
,
146 'fromShared' => $this->fromSharedDirectory
,
147 'width' => $this->width
,
148 'height' => $this->height
,
149 'bits' => $this->bits
,
150 'type' => $this->type
,
151 'size' => $this->size
);
153 $wgMemc->set( $keys[0], $cachedValues );
158 * Load metadata from the file itself
160 function loadFromFile() {
161 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
162 $fname = 'Image::loadFromFile';
163 wfProfileIn( $fname );
164 $this->imagePath
= $this->getFullPath();
165 $this->fileExists
= file_exists( $this->imagePath
);
168 # If the file is not found, and a shared upload directory is used, look for it there.
169 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
170 # In case we're on a wgCapitalLinks=false wiki, we
171 # capitalize the first letter of the filename before
172 # looking it up in the shared repository.
173 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
174 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
175 if ( $this->fileExists
) {
176 $this->name
= $sharedImage->name
;
177 $this->imagePath
= $this->getFulPath(true);
178 $this->fromSharedDirectory
= true;
182 if ( $this->fileExists
) {
184 $s = stat( $this->imagePath
);
185 $this->size
= $s['size'];
188 # Don't try to get the width and height of sound and video files, that's bad for performance
189 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
191 } elseif( $this->extension
== 'svg' ) {
192 wfSuppressWarnings();
193 $gis = wfGetSVGsize( $this->imagePath
);
196 wfSuppressWarnings();
197 $gis = getimagesize( $this->imagePath
);
201 if( $gis === false ) {
207 $this->width
= $gis[0];
208 $this->height
= $gis[1];
209 $this->type
= $gis[2];
210 if ( isset( $gis['bits'] ) ) {
211 $this->bits
= $gis['bits'];
216 $this->dataLoaded
= true;
217 wfProfileOut( $fname );
221 * Load image metadata from the DB
223 function loadFromDB() {
224 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
225 $fname = 'Image::loadFromDB';
226 wfProfileIn( $fname );
228 $dbr =& wfGetDB( DB_SLAVE
);
229 $row = $dbr->selectRow( 'image',
230 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
231 array( 'img_name' => $this->name
), $fname );
233 $this->fromSharedDirectory
= false;
234 $this->fileExists
= true;
235 $this->loadFromRow( $row );
236 $this->imagePath
= $this->getFullPath();
237 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
238 # In case we're on a wgCapitalLinks=false wiki, we
239 # capitalize the first letter of the filename before
240 # looking it up in the shared repository.
241 $name = $wgLang->ucfirst($this->name
);
243 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
244 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
245 array( 'img_name' => $name ), $fname );
247 $this->fromSharedDirectory
= true;
248 $this->fileExists
= true;
249 $this->imagePath
= '';
251 $this->loadFromRow( $row );
261 $this->fileExists
= false;
262 $this->fromSharedDirectory
= false;
265 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
266 $this->dataLoaded
= true;
270 * Load image metadata from a DB result row
272 function loadFromRow( &$row ) {
273 $this->size
= $row->img_size
;
274 $this->width
= $row->img_width
;
275 $this->height
= $row->img_height
;
276 $this->bits
= $row->img_bits
;
277 $this->type
= $row->img_type
;
278 $this->dataLoaded
= true;
282 * Load image metadata from cache or DB, unless already loaded
285 if ( !$this->dataLoaded
) {
286 if ( !$this->loadFromCache() ) {
288 if ( $this->fileExists
) {
289 $this->saveToCache();
292 $this->dataLoaded
= true;
297 * Return the name of this image
305 * Return the associated title object
308 function getTitle() {
313 * Return the URL of the image file
319 if($this->fileExists
) {
320 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
328 function getViewURL() {
329 if( $this->mustRender() ) {
330 return $this->createThumb( $this->getWidth() );
332 return $this->getURL();
337 * Return the image path of the image in the
338 * local file system as an absolute path
341 function getImagePath() {
343 return $this->imagePath
;
347 * Return the width of the image
349 * Returns -1 if the file specified is not a known image type
352 function getWidth() {
358 * Return the height of the image
360 * Returns -1 if the file specified is not a known image type
363 function getHeight() {
365 return $this->height
;
369 * Return the size of the image file, in bytes
378 * Return the type of the image
392 * Return the escapeLocalURL of this image
395 function getEscapeLocalURL() {
397 return $this->title
->escapeLocalURL();
401 * Return the escapeFullURL of this image
404 function getEscapeFullURL() {
406 return $this->title
->escapeFullURL();
410 * Return the URL of an image, provided its name.
412 * @param string $name Name of the image, without the leading "Image:"
413 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
417 function imageUrl( $name, $fromSharedDirectory = false ) {
418 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
419 if($fromSharedDirectory) {
421 $path = $wgSharedUploadPath;
423 $base = $wgUploadBaseUrl;
424 $path = $wgUploadPath;
426 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
427 return wfUrlencode( $url );
431 * Returns true if the image file exists on disk.
437 return $this->fileExists
;
444 function thumbUrl( $width, $subdir='thumb') {
445 global $wgUploadPath, $wgUploadBaseUrl,
446 $wgSharedUploadPath,$wgSharedUploadDirectory;
447 $name = $this->thumbName( $width );
448 if($this->fromSharedDirectory
) {
450 $path = $wgSharedUploadPath;
452 $base = $wgUploadBaseUrl;
453 $path = $wgUploadPath;
455 $url = "{$base}{$path}/{$subdir}" .
456 wfGetHashPath($name, $this->fromSharedDirectory
)
458 return wfUrlencode($url);
462 * Return the file name of a thumbnail of the specified width
464 * @param integer $width Width of the thumbnail image
465 * @param boolean $shared Does the thumbnail come from the shared repository?
468 function thumbName( $width, $shared=false ) {
469 $thumb = $width."px-".$this->name
;
470 if( $this->extension
== 'svg' ) {
471 # Rasterize SVG vector images to PNG
478 * Create a thumbnail of the image having the specified width/height.
479 * The thumbnail will not be created if the width is larger than the
480 * image's width. Let the browser do the scaling in this case.
481 * The thumbnail is stored on disk and is only computed if the thumbnail
482 * file does not exist OR if it is older than the image.
485 * Keeps aspect ratio of original image. If both width and height are
486 * specified, the generated image will be no bigger than width x height,
487 * and will also have correct aspect ratio.
489 * @param integer $width maximum width of the generated thumbnail
490 * @param integer $height maximum height of the image (optional)
493 function createThumb( $width, $height=-1 ) {
494 $thumb = $this->getThumbnail( $width, $height );
495 if( is_null( $thumb ) ) return '';
496 return $thumb->getUrl();
500 * As createThumb, but returns a ThumbnailImage object. This can
501 * provide access to the actual file, the real size of the thumb,
502 * and can produce a convenient <img> tag for you.
504 * @param integer $width maximum width of the generated thumbnail
505 * @param integer $height maximum height of the image (optional)
506 * @return ThumbnailImage
509 function &getThumbnail( $width, $height=-1 ) {
510 if ( $height == -1 ) {
511 return $this->renderThumb( $width );
514 if ( $width < $this->width
) {
515 $thumbheight = $this->height
* $width / $this->width
;
516 $thumbwidth = $width;
518 $thumbheight = $this->height
;
519 $thumbwidth = $this->width
;
521 if ( $thumbheight > $height ) {
522 $thumbwidth = $thumbwidth * $height / $thumbheight;
523 $thumbheight = $height;
525 $thumb = $this->renderThumb( $thumbwidth );
526 if( is_null( $thumb ) ) {
527 $thumb = $this->iconThumb();
533 * @return ThumbnailImage
535 function iconThumb() {
536 global $wgStylePath, $wgStyleDirectory;
538 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
539 foreach( $try as $icon ) {
540 $path = '/common/images/' . $icon;
541 $filepath = $wgStyleDirectory . $path;
542 if( file_exists( $filepath ) ) {
543 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
550 * Create a thumbnail of the image having the specified width.
551 * The thumbnail will not be created if the width is larger than the
552 * image's width. Let the browser do the scaling in this case.
553 * The thumbnail is stored on disk and is only computed if the thumbnail
554 * file does not exist OR if it is older than the image.
555 * Returns an object which can return the pathname, URL, and physical
556 * pixel size of the thumbnail -- or null on failure.
558 * @return ThumbnailImage
561 function /* private */ renderThumb( $width, $useScript = true ) {
562 global $wgImageMagickConvertCommand;
563 global $wgUseImageMagick;
564 global $wgUseSquid, $wgInternalServer;
565 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
567 $width = IntVal( $width );
570 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
571 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
572 $thumbUrl = $this->thumbUrl( $width );
573 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
574 if ( ! $this->exists() )
576 # If there is no image, there will be no thumbnail
580 # Sanity check $width
586 if( $width > $this->width
&& !$this->mustRender() ) {
587 # Don't make an image bigger than the source
588 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
591 $height = floor( $this->height
* ( $width/$this->width
) );
593 // Generate thumb.php URL if possible
594 $thumbScript = false;
597 if ( $this->fromSharedDirectory
) {
598 if ( $wgSharedThumbnailScriptPath ) {
599 $thumbScript = $wgSharedThumbnailScriptPath;
602 if ( $wgThumbnailScriptPath ) {
603 $thumbScript = $wgThumbnailScriptPath;
606 if ( $thumbScript ) {
607 $scriptUrl = $thumbScript . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
609 // Use thumb.php to render the image
610 return new ThumbnailImage( , $width, $height );
614 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
615 if( $this->extension
== 'svg' ) {
616 global $wgSVGConverters, $wgSVGConverter;
617 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
618 global $wgSVGConverterPath;
620 array( '$path/', '$width', '$input', '$output' ),
621 array( $wgSVGConverterPath,
623 escapeshellarg( $this->imagePath
),
624 escapeshellarg( $thumbPath ) ),
625 $wgSVGConverters[$wgSVGConverter] );
626 $conv = shell_exec( $cmd );
630 } elseif ( $wgUseImageMagick ) {
632 # Specify white background color, will be used for transparent images
633 # in Internet Explorer/Windows instead of default black.
634 $cmd = $wgImageMagickConvertCommand .
635 " -quality 85 -background white -geometry {$width} ".
636 escapeshellarg($this->imagePath
) . " " .
637 escapeshellarg($thumbPath);
638 $conv = shell_exec( $cmd );
640 # Use PHP's builtin GD library functions.
642 # First find out what kind of file this is, and select the correct
643 # input routine for this.
647 switch( $this->type
) {
649 $src_image = imagecreatefromgif( $this->imagePath
);
652 $src_image = imagecreatefromjpeg( $this->imagePath
);
656 $src_image = imagecreatefrompng( $this->imagePath
);
657 $truecolor = ( $this->bits
> 8 );
659 case 15: # WBMP for WML
660 $src_image = imagecreatefromwbmp( $this->imagePath
);
663 $src_image = imagecreatefromxbm( $this->imagePath
);
666 return 'Image type not supported';
670 $dst_image = imagecreatetruecolor( $width, $height );
672 $dst_image = imagecreate( $width, $height );
674 imagecopyresampled( $dst_image, $src_image,
676 $width, $height, $this->width
, $this->height
);
677 switch( $this->type
) {
682 #$thumbUrl .= ".png";
683 #$thumbPath .= ".png";
684 imagepng( $dst_image, $thumbPath );
687 #$thumbUrl .= ".jpg";
688 #$thumbPath .= ".jpg";
689 imageinterlace( $dst_image );
690 imagejpeg( $dst_image, $thumbPath, 95 );
695 imagedestroy( $dst_image );
696 imagedestroy( $src_image );
699 # Check for zero-sized thumbnails. Those can be generated when
700 # no disk space is available or some other error occurs
702 if( file_exists( $thumbPath ) ) {
703 $thumbstat = stat( $thumbPath );
704 if( $thumbstat['size'] == 0 ) {
705 unlink( $thumbPath );
710 # This has to be done after the image is updated and present for all machines on NFS,
711 # or else the old version might be stored into the squid again
714 $wgInternalServer.$thumbUrl
717 $urlArr[] = $scriptUrl;
719 wfPurgeSquidServers($urlArr);
722 return new ThumbnailImage( $thumbUrl, $width, $height );
723 } // END OF function createThumb
726 * Return the image history of this image, line by line.
727 * starts with current version, then old versions.
728 * uses $this->historyLine to check which line to return:
729 * 0 return line for current version
730 * 1 query for old versions, return first one
731 * 2, ... return next old version from above query
735 function nextHistoryLine() {
736 $fname = 'Image::nextHistoryLine()';
737 $dbr =& wfGetDB( DB_SLAVE
);
738 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
739 $this->historyRes
= $dbr->select( 'image',
740 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
741 array( 'img_name' => $this->title
->getDBkey() ),
744 if ( 0 == wfNumRows( $this->historyRes
) ) {
747 } else if ( $this->historyLine
== 1 ) {
748 $this->historyRes
= $dbr->select( 'oldimage',
749 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
750 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
751 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
754 $this->historyLine ++
;
756 return $dbr->fetchObject( $this->historyRes
);
760 * Reset the history pointer to the first element of the history
763 function resetHistory() {
764 $this->historyLine
= 0;
768 * Return true if the file is of a type that can't be directly
769 * rendered by typical browsers and needs to be re-rasterized.
772 function mustRender() {
774 return ( $this->extension
== 'svg' );
778 * Return the full filesystem path to the file. Note that this does
779 * not mean that a file actually exists under that location.
781 * This path depends on whether directory hashing is active or not,
782 * i.e. whether the images are all found in the same directory,
783 * or in hashed paths like /images/3/3c.
786 * @param boolean $fromSharedDirectory Return the path to the file
787 * in a shared repository (see $wgUseSharedRepository and related
788 * options in DefaultSettings.php) instead of a local one.
791 function getFullPath( $fromSharedRepository = false ) {
792 global $wgUploadDirectory, $wgSharedUploadDirectory;
793 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
795 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
798 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
806 function isKnownImageExtension( $ext ) {
807 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
808 return in_array( $ext, $extensions );
812 * Record an image upload in the upload log and the image table
814 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
815 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
816 global $wgUseCopyrightUpload;
818 $fname = 'Image::recordUpload';
819 $dbw =& wfGetDB( DB_MASTER
);
821 # img_name must be unique
822 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
823 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
826 // Fill metadata fields by querying the file
827 $this->loadFromFile();
828 $this->saveToCache();
830 // Fail now if the image isn't there
831 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
835 if ( $wgUseCopyrightUpload ) {
836 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
837 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
838 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
843 $now = wfTimestampNow();
845 # Test to see if the row exists using INSERT IGNORE
846 # This avoids race conditions by locking the row until the commit, and also
847 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
848 $dbw->insert( 'image',
850 'img_name' => $this->name
,
851 'img_size'=> $this->size
,
852 'img_width' => $this->width
,
853 'img_height' => $this->height
,
854 'img_bits' => $this->bits
,
855 'img_type' => $this->type
,
856 'img_timestamp' => $dbw->timestamp($now),
857 'img_description' => $desc,
858 'img_user' => $wgUser->getID(),
859 'img_user_text' => $wgUser->getName(),
862 $descTitle = $this->getTitle();
864 if ( $dbw->affectedRows() ) {
865 # Successfully inserted, this is a new image
866 $id = $descTitle->getArticleID();
869 $article = new Article( $descTitle );
870 $article->insertNewArticle( $textdesc, $desc, false, false, true );
873 # Collision, this is an update of an image
874 # Insert previous contents into oldimage
875 $dbw->insertSelect( 'oldimage', 'image',
877 'oi_name' => 'img_name',
878 'oi_archive_name' => $dbw->addQuotes( $oldver ),
879 'oi_size' => 'img_size',
880 'oi_width' => 'img_width',
881 'oi_height' => 'img_height',
882 'oi_bits' => 'img_bits',
883 'oi_type' => 'img_type',
884 'oi_timestamp' => 'img_timestamp',
885 'oi_description' => 'img_description',
886 'oi_user' => 'img_user',
887 'oi_user_text' => 'img_user_text',
888 ), array( 'img_name' => $this->name
), $fname
891 # Update the current image row
892 $dbw->update( 'image',
894 'img_size' => $this->size
,
895 'img_width' => $this->width
,
896 'img_height' => $this->height
,
897 'img_bits' => $this->bits
,
898 'img_type' => $this->type
,
899 'img_timestamp' => $dbw->timestamp(),
900 'img_user' => $wgUser->getID(),
901 'img_user_text' => $wgUser->getName(),
902 'img_description' => $desc,
903 ), array( /* WHERE */
904 'img_name' => $this->name
908 # Invalidate the cache for the description page
909 $descTitle->invalidateCache();
912 $log = new LogPage( 'upload' );
913 $log->addEntry( 'upload', $descTitle, $desc );
922 * Returns the image directory of an image
923 * If the directory does not exist, it is created.
924 * The result is an absolute path.
926 * This function is called from thumb.php before Setup.php is included
928 * @param string $fname file name of the image file
931 function wfImageDir( $fname ) {
932 global $wgUploadDirectory, $wgHashedUploadDirectory;
934 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
936 $hash = md5( $fname );
937 $oldumask = umask(0);
938 $dest = $wgUploadDirectory . '/' . $hash{0};
939 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
940 $dest .= '/' . substr( $hash, 0, 2 );
941 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
948 * Returns the image directory of an image's thubnail
949 * If the directory does not exist, it is created.
950 * The result is an absolute path.
952 * This function is called from thumb.php before Setup.php is included
954 * @param string $fname file name of the thumbnail file, including file size prefix
955 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
956 * @param boolean $shared (optional) use the shared upload directory
959 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
960 return wfImageArchiveDir( $fname, $subdir, $shared );
964 * Returns the image directory of an image's old version
965 * If the directory does not exist, it is created.
966 * The result is an absolute path.
968 * This function is called from thumb.php before Setup.php is included
970 * @param string $fname file name of the thumbnail file, including file size prefix
971 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
972 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
975 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
976 global $wgUploadDirectory, $wgHashedUploadDirectory,
977 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
978 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
979 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
980 if (!$hashdir) { return $dir.'/'.$subdir; }
981 $hash = md5( $fname );
982 $oldumask = umask(0);
983 # Suppress warning messages here; if the file itself can't
984 # be written we'll worry about it then.
985 $archive = $dir.'/'.$subdir;
986 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
987 $archive .= '/' . $hash{0};
988 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
989 $archive .= '/' . substr( $hash, 0, 2 );
990 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
998 * Return the hash path component of an image path (URL or filesystem),
999 * e.g. "/3/3c/", or just "/" if hashing is not used.
1001 * @param $dbkey The filesystem / database name of the file
1002 * @param $fromSharedDirectory Use the shared file repository? It may
1003 * use different hash settings from the local one.
1005 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1006 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1007 global $wgHashedUploadDirectory;
1009 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
1010 $wgHashedUploadDirectory;
1012 $hash = md5($dbkey);
1013 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1020 * Returns the image URL of an image's old version
1022 * @param string $fname file name of the image file
1023 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1026 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1027 global $wgUploadPath, $wgHashedUploadDirectory;
1029 if ($wgHashedUploadDirectory) {
1030 $hash = md5( substr( $name, 15) );
1031 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1032 substr( $hash, 0, 2 ) . '/'.$name;
1034 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1036 return wfUrlencode($url);
1040 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1041 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1043 * @param string $length
1044 * @return int Length in pixels
1046 function wfScaleSVGUnit( $length ) {
1047 static $unitLength = array(
1054 '' => 1.0, // "User units" pixels by default
1055 '%' => 2.0, // Fake it!
1057 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1058 $length = FloatVal( $matches[1] );
1059 $unit = $matches[2];
1060 return round( $length * $unitLength[$unit] );
1063 return round( FloatVal( $length ) );
1068 * Compatible with PHP getimagesize()
1069 * @todo support gzipped SVGZ
1070 * @todo check XML more carefully
1071 * @todo sensible defaults
1073 * @param string $filename
1076 function wfGetSVGsize( $filename ) {
1080 // Read a chunk of the file
1081 $f = fopen( $filename, "rt" );
1082 if( !$f ) return false;
1083 $chunk = fread( $f, 4096 );
1086 // Uber-crappy hack! Run through a real XML parser.
1087 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1091 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1092 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1094 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1095 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1098 return array( $width, $height, 'SVG',
1099 "width=\"$width\" height=\"$height\"" );
1103 * Is an image on the bad image list?
1105 function wfIsBadImage( $name ) {
1108 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1109 foreach ( $lines as $line ) {
1110 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1111 $t = Title
::newFromText( $m[1] );
1112 if ( $t->getDBkey() == $name ) {
1123 * Wrapper class for thumbnail images
1124 * @package MediaWiki
1126 class ThumbnailImage
{
1128 * @param string $path Filesystem path to the thumb
1129 * @param string $url URL path to the thumb
1132 function ThumbnailImage( $url, $width, $height ) {
1134 $this->width
= $width;
1135 $this->height
= $height;
1139 * @return string The thumbnail URL
1146 * Return HTML <img ... /> tag for the thumbnail, will include
1147 * width and height attributes and a blank alt text (as required).
1149 * You can set or override additional attributes by passing an
1150 * associative array of name => data pairs. The data will be escaped
1151 * for HTML output, so should be in plaintext.
1153 * @param array $attribs
1157 function toHtml( $attribs = array() ) {
1158 $attribs['src'] = $this->url
;
1159 $attribs['width'] = $this->width
;
1160 $attribs['height'] = $this->height
;
1161 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1164 foreach( $attribs as $name => $data ) {
1165 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';