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 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
241 # In case we're on a wgCapitalLinks=false wiki, we
242 # capitalize the first letter of the filename before
243 # looking it up in the shared repository.
244 $name = $wgLang->ucfirst($this->name
);
246 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
247 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
248 array( 'img_name' => $name ), $fname );
250 $this->fromSharedDirectory
= true;
251 $this->fileExists
= true;
252 $this->imagePath
= $this->getFullPath(true);
254 $this->loadFromRow( $row );
264 $this->fileExists
= false;
265 $this->fromSharedDirectory
= false;
268 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
269 $this->dataLoaded
= true;
273 * Load image metadata from a DB result row
275 function loadFromRow( &$row ) {
276 $this->size
= $row->img_size
;
277 $this->width
= $row->img_width
;
278 $this->height
= $row->img_height
;
279 $this->bits
= $row->img_bits
;
280 $this->type
= $row->img_type
;
281 $this->dataLoaded
= true;
285 * Load image metadata from cache or DB, unless already loaded
288 if ( !$this->dataLoaded
) {
289 if ( !$this->loadFromCache() ) {
291 if ( $this->fileExists
) {
292 $this->saveToCache();
295 $this->dataLoaded
= true;
300 * Return the name of this image
308 * Return the associated title object
311 function getTitle() {
316 * Return the URL of the image file
322 if($this->fileExists
) {
323 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
331 function getViewURL() {
332 if( $this->mustRender() ) {
333 return $this->createThumb( $this->getWidth() );
335 return $this->getURL();
340 * Return the image path of the image in the
341 * local file system as an absolute path
344 function getImagePath() {
346 return $this->imagePath
;
350 * Return the width of the image
352 * Returns -1 if the file specified is not a known image type
355 function getWidth() {
361 * Return the height of the image
363 * Returns -1 if the file specified is not a known image type
366 function getHeight() {
368 return $this->height
;
372 * Return the size of the image file, in bytes
381 * Return the type of the image
395 * Return the escapeLocalURL of this image
398 function getEscapeLocalURL() {
400 return $this->title
->escapeLocalURL();
404 * Return the escapeFullURL of this image
407 function getEscapeFullURL() {
409 return $this->title
->escapeFullURL();
413 * Return the URL of an image, provided its name.
415 * @param string $name Name of the image, without the leading "Image:"
416 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
420 function imageUrl( $name, $fromSharedDirectory = false ) {
421 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
422 if($fromSharedDirectory) {
424 $path = $wgSharedUploadPath;
426 $base = $wgUploadBaseUrl;
427 $path = $wgUploadPath;
429 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
430 return wfUrlencode( $url );
434 * Returns true if the image file exists on disk.
440 return $this->fileExists
;
447 function thumbUrl( $width, $subdir='thumb') {
448 global $wgUploadPath, $wgUploadBaseUrl,
449 $wgSharedUploadPath,$wgSharedUploadDirectory,
450 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
452 // Generate thumb.php URL if possible
456 if ( $this->fromSharedDirectory
) {
457 if ( $wgSharedThumbnailScriptPath ) {
458 $script = $wgSharedThumbnailScriptPath;
461 if ( $wgThumbnailScriptPath ) {
462 $script = $wgThumbnailScriptPath;
466 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
468 $name = $this->thumbName( $width );
469 if($this->fromSharedDirectory
) {
471 $path = $wgSharedUploadPath;
473 $base = $wgUploadBaseUrl;
474 $path = $wgUploadPath;
476 $url = "{$base}{$path}/{$subdir}" .
477 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
478 . $this->name
.'/'.$name;
479 $url = wfUrlencode( $url );
481 return array( $script !== false, $url );
485 * Return the file name of a thumbnail of the specified width
487 * @param integer $width Width of the thumbnail image
488 * @param boolean $shared Does the thumbnail come from the shared repository?
491 function thumbName( $width ) {
492 $thumb = $width."px-".$this->name
;
493 if( $this->extension
== 'svg' ) {
494 # Rasterize SVG vector images to PNG
501 * Create a thumbnail of the image having the specified width/height.
502 * The thumbnail will not be created if the width is larger than the
503 * image's width. Let the browser do the scaling in this case.
504 * The thumbnail is stored on disk and is only computed if the thumbnail
505 * file does not exist OR if it is older than the image.
508 * Keeps aspect ratio of original image. If both width and height are
509 * specified, the generated image will be no bigger than width x height,
510 * and will also have correct aspect ratio.
512 * @param integer $width maximum width of the generated thumbnail
513 * @param integer $height maximum height of the image (optional)
516 function createThumb( $width, $height=-1 ) {
517 $thumb = $this->getThumbnail( $width, $height );
518 if( is_null( $thumb ) ) return '';
519 return $thumb->getUrl();
523 * As createThumb, but returns a ThumbnailImage object. This can
524 * provide access to the actual file, the real size of the thumb,
525 * and can produce a convenient <img> tag for you.
527 * @param integer $width maximum width of the generated thumbnail
528 * @param integer $height maximum height of the image (optional)
529 * @return ThumbnailImage
532 function &getThumbnail( $width, $height=-1 ) {
533 if ( $height == -1 ) {
534 return $this->renderThumb( $width );
537 if ( $width < $this->width
) {
538 $thumbheight = $this->height
* $width / $this->width
;
539 $thumbwidth = $width;
541 $thumbheight = $this->height
;
542 $thumbwidth = $this->width
;
544 if ( $thumbheight > $height ) {
545 $thumbwidth = $thumbwidth * $height / $thumbheight;
546 $thumbheight = $height;
548 $thumb = $this->renderThumb( $thumbwidth );
549 if( is_null( $thumb ) ) {
550 $thumb = $this->iconThumb();
556 * @return ThumbnailImage
558 function iconThumb() {
559 global $wgStylePath, $wgStyleDirectory;
561 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
562 foreach( $try as $icon ) {
563 $path = '/common/images/' . $icon;
564 $filepath = $wgStyleDirectory . $path;
565 if( file_exists( $filepath ) ) {
566 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
573 * Create a thumbnail of the image having the specified width.
574 * The thumbnail will not be created if the width is larger than the
575 * image's width. Let the browser do the scaling in this case.
576 * The thumbnail is stored on disk and is only computed if the thumbnail
577 * file does not exist OR if it is older than the image.
578 * Returns an object which can return the pathname, URL, and physical
579 * pixel size of the thumbnail -- or null on failure.
581 * @return ThumbnailImage
584 function /* private */ renderThumb( $width, $useScript = true ) {
585 global $wgUseSquid, $wgInternalServer;
586 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
588 $width = IntVal( $width );
591 if ( ! $this->exists() )
593 # If there is no image, there will be no thumbnail
597 # Sanity check $width
603 if( $width > $this->width
&& !$this->mustRender() ) {
604 # Don't make an image bigger than the source
605 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
608 $height = floor( $this->height
* ( $width/$this->width
) );
610 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
611 if ( $isScriptUrl && $useScript ) {
612 // Use thumb.php to render the image
613 return new ThumbnailImage( $url, $width, $height );
616 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
617 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
619 if ( !file_exists( $thumbPath ) ) {
620 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
623 if ( file_exists( $oldThumbPath ) ) {
624 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
625 rename( $oldThumbPath, $thumbPath );
628 unlink( $oldThumbPath );
632 $this->reallyRenderThumb( $thumbPath, $width, $height );
635 # This has to be done after the image is updated and present for all machines on NFS,
636 # or else the old version might be stored into the squid again
638 if ( substr( $url, 0, 4 ) == 'http' ) {
639 $urlArr = array( $url );
641 $urlArr = array( $wgInternalServer.$url );
643 wfPurgeSquidServers($urlArr);
647 return new ThumbnailImage( $url, $width, $height, $thumbPath );
648 } // END OF function renderThumb
651 * Really render a thumbnail
655 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
656 global $wgSVGConverters, $wgSVGConverter,
657 $wgUseImageMagick, $wgImageMagickConvertCommand;
661 if( $this->extension
== 'svg' ) {
662 global $wgSVGConverters, $wgSVGConverter;
663 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
664 global $wgSVGConverterPath;
666 array( '$path/', '$width', '$input', '$output' ),
667 array( $wgSVGConverterPath,
669 escapeshellarg( $this->imagePath
),
670 escapeshellarg( $thumbPath ) ),
671 $wgSVGConverters[$wgSVGConverter] );
672 $conv = shell_exec( $cmd );
676 } elseif ( $wgUseImageMagick ) {
678 # Specify white background color, will be used for transparent images
679 # in Internet Explorer/Windows instead of default black.
680 $cmd = $wgImageMagickConvertCommand .
681 " -quality 85 -background white -geometry {$width} ".
682 escapeshellarg($this->imagePath
) . " " .
683 escapeshellarg($thumbPath);
684 $conv = shell_exec( $cmd );
686 # Use PHP's builtin GD library functions.
688 # First find out what kind of file this is, and select the correct
689 # input routine for this.
693 switch( $this->type
) {
695 $src_image = imagecreatefromgif( $this->imagePath
);
698 $src_image = imagecreatefromjpeg( $this->imagePath
);
702 $src_image = imagecreatefrompng( $this->imagePath
);
703 $truecolor = ( $this->bits
> 8 );
705 case 15: # WBMP for WML
706 $src_image = imagecreatefromwbmp( $this->imagePath
);
709 $src_image = imagecreatefromxbm( $this->imagePath
);
712 return 'Image type not supported';
716 $dst_image = imagecreatetruecolor( $width, $height );
718 $dst_image = imagecreate( $width, $height );
720 imagecopyresampled( $dst_image, $src_image,
722 $width, $height, $this->width
, $this->height
);
723 switch( $this->type
) {
728 imagepng( $dst_image, $thumbPath );
731 imageinterlace( $dst_image );
732 imagejpeg( $dst_image, $thumbPath, 95 );
737 imagedestroy( $dst_image );
738 imagedestroy( $src_image );
741 # Check for zero-sized thumbnails. Those can be generated when
742 # no disk space is available or some other error occurs
744 if( file_exists( $thumbPath ) ) {
745 $thumbstat = stat( $thumbPath );
746 if( $thumbstat['size'] == 0 ) {
747 unlink( $thumbPath );
753 * Get all thumbnail names previously generated for this image
755 function getThumbnails( $shared = false ) {
758 $dir = wfImageThumbDir( $this->name
, $shared );
760 // This generates an error on failure, hence the @
761 $handle = @opendir
( $dir );
764 while ( false !== ( $file = readdir($handle) ) ) {
765 if ( $file{0} != '.' ) {
776 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
778 function purgeCache( $archiveFiles = array(), $shared = false ) {
779 global $wgInternalServer, $wgUseSquid;
781 // Refresh metadata cache
782 $this->loadFromFile();
783 $this->saveToCache();
786 $files = $this->getThumbnails( $shared );
787 $dir = wfImageThumbDir( $this->name
, $shared );
789 foreach ( $files as $file ) {
790 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
791 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
792 @unlink
( "$dir/$file" );
798 $urls[] = $wgInternalServer . $this->getViewURL();
799 foreach ( $archiveFiles as $file ) {
800 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
802 wfPurgeSquidServers( $urls );
807 * Return the image history of this image, line by line.
808 * starts with current version, then old versions.
809 * uses $this->historyLine to check which line to return:
810 * 0 return line for current version
811 * 1 query for old versions, return first one
812 * 2, ... return next old version from above query
816 function nextHistoryLine() {
817 $fname = 'Image::nextHistoryLine()';
818 $dbr =& wfGetDB( DB_SLAVE
);
819 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
820 $this->historyRes
= $dbr->select( 'image',
821 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
822 array( 'img_name' => $this->title
->getDBkey() ),
825 if ( 0 == wfNumRows( $this->historyRes
) ) {
828 } else if ( $this->historyLine
== 1 ) {
829 $this->historyRes
= $dbr->select( 'oldimage',
830 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
831 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
832 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
835 $this->historyLine ++
;
837 return $dbr->fetchObject( $this->historyRes
);
841 * Reset the history pointer to the first element of the history
844 function resetHistory() {
845 $this->historyLine
= 0;
849 * Return true if the file is of a type that can't be directly
850 * rendered by typical browsers and needs to be re-rasterized.
853 function mustRender() {
855 return ( $this->extension
== 'svg' );
859 * Return the full filesystem path to the file. Note that this does
860 * not mean that a file actually exists under that location.
862 * This path depends on whether directory hashing is active or not,
863 * i.e. whether the images are all found in the same directory,
864 * or in hashed paths like /images/3/3c.
867 * @param boolean $fromSharedDirectory Return the path to the file
868 * in a shared repository (see $wgUseSharedRepository and related
869 * options in DefaultSettings.php) instead of a local one.
872 function getFullPath( $fromSharedRepository = false ) {
873 global $wgUploadDirectory, $wgSharedUploadDirectory;
874 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
876 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
879 // $wgSharedUploadDirectory may be false, if thumb.php is used
881 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
893 function isKnownImageExtension( $ext ) {
894 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
895 return in_array( $ext, $extensions );
899 * Record an image upload in the upload log and the image table
901 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
902 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
903 global $wgUseCopyrightUpload;
905 $fname = 'Image::recordUpload';
906 $dbw =& wfGetDB( DB_MASTER
);
908 # img_name must be unique
909 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
910 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
913 // Delete thumbnails and refresh the cache
916 // Fail now if the image isn't there
917 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
921 if ( $wgUseCopyrightUpload ) {
922 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
923 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
924 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
929 $now = wfTimestampNow();
931 # Test to see if the row exists using INSERT IGNORE
932 # This avoids race conditions by locking the row until the commit, and also
933 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
934 $dbw->insert( 'image',
936 'img_name' => $this->name
,
937 'img_size'=> $this->size
,
938 'img_width' => $this->width
,
939 'img_height' => $this->height
,
940 'img_bits' => $this->bits
,
941 'img_type' => $this->type
,
942 'img_timestamp' => $dbw->timestamp($now),
943 'img_description' => $desc,
944 'img_user' => $wgUser->getID(),
945 'img_user_text' => $wgUser->getName(),
948 $descTitle = $this->getTitle();
950 if ( $dbw->affectedRows() ) {
951 # Successfully inserted, this is a new image
952 $id = $descTitle->getArticleID();
955 $article = new Article( $descTitle );
956 $article->insertNewArticle( $textdesc, $desc, false, false, true );
959 # Collision, this is an update of an image
960 # Insert previous contents into oldimage
961 $dbw->insertSelect( 'oldimage', 'image',
963 'oi_name' => 'img_name',
964 'oi_archive_name' => $dbw->addQuotes( $oldver ),
965 'oi_size' => 'img_size',
966 'oi_width' => 'img_width',
967 'oi_height' => 'img_height',
968 'oi_bits' => 'img_bits',
969 'oi_type' => 'img_type',
970 'oi_timestamp' => 'img_timestamp',
971 'oi_description' => 'img_description',
972 'oi_user' => 'img_user',
973 'oi_user_text' => 'img_user_text',
974 ), array( 'img_name' => $this->name
), $fname
977 # Update the current image row
978 $dbw->update( 'image',
980 'img_size' => $this->size
,
981 'img_width' => $this->width
,
982 'img_height' => $this->height
,
983 'img_bits' => $this->bits
,
984 'img_type' => $this->type
,
985 'img_timestamp' => $dbw->timestamp(),
986 'img_user' => $wgUser->getID(),
987 'img_user_text' => $wgUser->getName(),
988 'img_description' => $desc,
989 ), array( /* WHERE */
990 'img_name' => $this->name
994 # Invalidate the cache for the description page
995 $descTitle->invalidateCache();
998 $log = new LogPage( 'upload' );
999 $log->addEntry( 'upload', $descTitle, $desc );
1008 * Returns the image directory of an image
1009 * If the directory does not exist, it is created.
1010 * The result is an absolute path.
1012 * This function is called from thumb.php before Setup.php is included
1014 * @param string $fname file name of the image file
1017 function wfImageDir( $fname ) {
1018 global $wgUploadDirectory, $wgHashedUploadDirectory;
1020 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1022 $hash = md5( $fname );
1023 $oldumask = umask(0);
1024 $dest = $wgUploadDirectory . '/' . $hash{0};
1025 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1026 $dest .= '/' . substr( $hash, 0, 2 );
1027 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1034 * Returns the image directory of an image's thubnail
1035 * If the directory does not exist, it is created.
1036 * The result is an absolute path.
1038 * This function is called from thumb.php before Setup.php is included
1040 * @param string $fname file name of the original image file
1041 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1042 * @param boolean $shared (optional) use the shared upload directory
1045 function wfImageThumbDir( $fname, $shared = false ) {
1046 $dir = wfImageArchiveDir( $fname, 'thumb', $shared ) . "/$fname";
1047 if ( ! is_dir( $dir ) ) {
1048 $oldumask = umask(0);
1049 @mkdir
( $dir, 0777 );
1056 * Old thumbnail directory, kept for conversion
1058 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1059 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1063 * Returns the image directory of an image's old version
1064 * If the directory does not exist, it is created.
1065 * The result is an absolute path.
1067 * This function is called from thumb.php before Setup.php is included
1069 * @param string $fname file name of the thumbnail file, including file size prefix
1070 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1071 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1074 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1075 global $wgUploadDirectory, $wgHashedUploadDirectory,
1076 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1077 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1078 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1079 if (!$hashdir) { return $dir.'/'.$subdir; }
1080 $hash = md5( $fname );
1081 $oldumask = umask(0);
1083 # Suppress warning messages here; if the file itself can't
1084 # be written we'll worry about it then.
1085 wfSuppressWarnings();
1087 $archive = $dir.'/'.$subdir;
1088 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1089 $archive .= '/' . $hash{0};
1090 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1091 $archive .= '/' . substr( $hash, 0, 2 );
1092 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1094 wfRestoreWarnings();
1101 * Return the hash path component of an image path (URL or filesystem),
1102 * e.g. "/3/3c/", or just "/" if hashing is not used.
1104 * @param $dbkey The filesystem / database name of the file
1105 * @param $fromSharedDirectory Use the shared file repository? It may
1106 * use different hash settings from the local one.
1108 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1109 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1110 global $wgHashedUploadDirectory;
1112 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
1113 $wgHashedUploadDirectory;
1115 $hash = md5($dbkey);
1116 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1123 * Returns the image URL of an image's old version
1125 * @param string $fname file name of the image file
1126 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1129 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1130 global $wgUploadPath, $wgHashedUploadDirectory;
1132 if ($wgHashedUploadDirectory) {
1133 $hash = md5( substr( $name, 15) );
1134 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1135 substr( $hash, 0, 2 ) . '/'.$name;
1137 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1139 return wfUrlencode($url);
1143 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1144 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1146 * @param string $length
1147 * @return int Length in pixels
1149 function wfScaleSVGUnit( $length ) {
1150 static $unitLength = array(
1157 '' => 1.0, // "User units" pixels by default
1158 '%' => 2.0, // Fake it!
1160 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1161 $length = FloatVal( $matches[1] );
1162 $unit = $matches[2];
1163 return round( $length * $unitLength[$unit] );
1166 return round( FloatVal( $length ) );
1171 * Compatible with PHP getimagesize()
1172 * @todo support gzipped SVGZ
1173 * @todo check XML more carefully
1174 * @todo sensible defaults
1176 * @param string $filename
1179 function wfGetSVGsize( $filename ) {
1183 // Read a chunk of the file
1184 $f = fopen( $filename, "rt" );
1185 if( !$f ) return false;
1186 $chunk = fread( $f, 4096 );
1189 // Uber-crappy hack! Run through a real XML parser.
1190 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1194 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1195 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1197 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1198 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1201 return array( $width, $height, 'SVG',
1202 "width=\"$width\" height=\"$height\"" );
1206 * Is an image on the bad image list?
1208 function wfIsBadImage( $name ) {
1211 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1212 foreach ( $lines as $line ) {
1213 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1214 $t = Title
::newFromText( $m[1] );
1215 if ( $t->getDBkey() == $name ) {
1226 * Wrapper class for thumbnail images
1227 * @package MediaWiki
1229 class ThumbnailImage
{
1231 * @param string $path Filesystem path to the thumb
1232 * @param string $url URL path to the thumb
1235 function ThumbnailImage( $url, $width, $height, $path = false ) {
1237 $this->width
= $width;
1238 $this->height
= $height;
1239 $this->path
= $path;
1243 * @return string The thumbnail URL
1250 * Return HTML <img ... /> tag for the thumbnail, will include
1251 * width and height attributes and a blank alt text (as required).
1253 * You can set or override additional attributes by passing an
1254 * associative array of name => data pairs. The data will be escaped
1255 * for HTML output, so should be in plaintext.
1257 * @param array $attribs
1261 function toHtml( $attribs = array() ) {
1262 $attribs['src'] = $this->url
;
1263 $attribs['width'] = $this->width
;
1264 $attribs['height'] = $this->height
;
1265 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1268 foreach( $attribs as $name => $data ) {
1269 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';