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 global $wgSharedUploadDBname, $wgUseSharedUploads;
289 if ( !$this->dataLoaded
) {
290 if ( !$this->loadFromCache() ) {
292 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
293 $this->loadFromFile();
294 } elseif ( $this->fileExists
) {
295 $this->saveToCache();
298 $this->dataLoaded
= true;
303 * Return the name of this image
311 * Return the associated title object
314 function getTitle() {
319 * Return the URL of the image file
325 if($this->fileExists
) {
326 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
334 function getViewURL() {
335 if( $this->mustRender() ) {
336 return $this->createThumb( $this->getWidth() );
338 return $this->getURL();
343 * Return the image path of the image in the
344 * local file system as an absolute path
347 function getImagePath() {
349 return $this->imagePath
;
353 * Return the width of the image
355 * Returns -1 if the file specified is not a known image type
358 function getWidth() {
364 * Return the height of the image
366 * Returns -1 if the file specified is not a known image type
369 function getHeight() {
371 return $this->height
;
375 * Return the size of the image file, in bytes
384 * Return the type of the image
398 * Return the escapeLocalURL of this image
401 function getEscapeLocalURL() {
403 return $this->title
->escapeLocalURL();
407 * Return the escapeFullURL of this image
410 function getEscapeFullURL() {
412 return $this->title
->escapeFullURL();
416 * Return the URL of an image, provided its name.
418 * @param string $name Name of the image, without the leading "Image:"
419 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
423 function imageUrl( $name, $fromSharedDirectory = false ) {
424 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
425 if($fromSharedDirectory) {
427 $path = $wgSharedUploadPath;
429 $base = $wgUploadBaseUrl;
430 $path = $wgUploadPath;
432 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
433 return wfUrlencode( $url );
437 * Returns true if the image file exists on disk.
443 return $this->fileExists
;
450 function thumbUrl( $width, $subdir='thumb') {
451 global $wgUploadPath, $wgUploadBaseUrl,
452 $wgSharedUploadPath,$wgSharedUploadDirectory,
453 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
455 // Generate thumb.php URL if possible
459 if ( $this->fromSharedDirectory
) {
460 if ( $wgSharedThumbnailScriptPath ) {
461 $script = $wgSharedThumbnailScriptPath;
464 if ( $wgThumbnailScriptPath ) {
465 $script = $wgThumbnailScriptPath;
469 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
471 $name = $this->thumbName( $width );
472 if($this->fromSharedDirectory
) {
474 $path = $wgSharedUploadPath;
476 $base = $wgUploadBaseUrl;
477 $path = $wgUploadPath;
479 $url = "{$base}{$path}/{$subdir}" .
480 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
481 . $this->name
.'/'.$name;
482 $url = wfUrlencode( $url );
484 return array( $script !== false, $url );
488 * Return the file name of a thumbnail of the specified width
490 * @param integer $width Width of the thumbnail image
491 * @param boolean $shared Does the thumbnail come from the shared repository?
494 function thumbName( $width ) {
495 $thumb = $width."px-".$this->name
;
496 if( $this->extension
== 'svg' ) {
497 # Rasterize SVG vector images to PNG
504 * Create a thumbnail of the image having the specified width/height.
505 * The thumbnail will not be created if the width is larger than the
506 * image's width. Let the browser do the scaling in this case.
507 * The thumbnail is stored on disk and is only computed if the thumbnail
508 * file does not exist OR if it is older than the image.
511 * Keeps aspect ratio of original image. If both width and height are
512 * specified, the generated image will be no bigger than width x height,
513 * and will also have correct aspect ratio.
515 * @param integer $width maximum width of the generated thumbnail
516 * @param integer $height maximum height of the image (optional)
519 function createThumb( $width, $height=-1 ) {
520 $thumb = $this->getThumbnail( $width, $height );
521 if( is_null( $thumb ) ) return '';
522 return $thumb->getUrl();
526 * As createThumb, but returns a ThumbnailImage object. This can
527 * provide access to the actual file, the real size of the thumb,
528 * and can produce a convenient <img> tag for you.
530 * @param integer $width maximum width of the generated thumbnail
531 * @param integer $height maximum height of the image (optional)
532 * @return ThumbnailImage
535 function &getThumbnail( $width, $height=-1 ) {
536 if ( $height == -1 ) {
537 return $this->renderThumb( $width );
540 if ( $width < $this->width
) {
541 $thumbheight = $this->height
* $width / $this->width
;
542 $thumbwidth = $width;
544 $thumbheight = $this->height
;
545 $thumbwidth = $this->width
;
547 if ( $thumbheight > $height ) {
548 $thumbwidth = $thumbwidth * $height / $thumbheight;
549 $thumbheight = $height;
551 $thumb = $this->renderThumb( $thumbwidth );
552 if( is_null( $thumb ) ) {
553 $thumb = $this->iconThumb();
559 * @return ThumbnailImage
561 function iconThumb() {
562 global $wgStylePath, $wgStyleDirectory;
564 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
565 foreach( $try as $icon ) {
566 $path = '/common/images/' . $icon;
567 $filepath = $wgStyleDirectory . $path;
568 if( file_exists( $filepath ) ) {
569 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
576 * Create a thumbnail of the image having the specified width.
577 * The thumbnail will not be created if the width is larger than the
578 * image's width. Let the browser do the scaling in this case.
579 * The thumbnail is stored on disk and is only computed if the thumbnail
580 * file does not exist OR if it is older than the image.
581 * Returns an object which can return the pathname, URL, and physical
582 * pixel size of the thumbnail -- or null on failure.
584 * @return ThumbnailImage
587 function /* private */ renderThumb( $width, $useScript = true ) {
588 global $wgUseSquid, $wgInternalServer;
589 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
591 $width = IntVal( $width );
594 if ( ! $this->exists() )
596 # If there is no image, there will be no thumbnail
600 # Sanity check $width
606 if( $width > $this->width
&& !$this->mustRender() ) {
607 # Don't make an image bigger than the source
608 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
611 $height = floor( $this->height
* ( $width/$this->width
) );
613 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
614 if ( $isScriptUrl && $useScript ) {
615 // Use thumb.php to render the image
616 return new ThumbnailImage( $url, $width, $height );
619 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
620 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
622 if ( !file_exists( $thumbPath ) ) {
623 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
626 if ( file_exists( $oldThumbPath ) ) {
627 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
628 rename( $oldThumbPath, $thumbPath );
631 unlink( $oldThumbPath );
635 $this->reallyRenderThumb( $thumbPath, $width, $height );
638 # This has to be done after the image is updated and present for all machines on NFS,
639 # or else the old version might be stored into the squid again
641 if ( substr( $url, 0, 4 ) == 'http' ) {
642 $urlArr = array( $url );
644 $urlArr = array( $wgInternalServer.$url );
646 wfPurgeSquidServers($urlArr);
650 return new ThumbnailImage( $url, $width, $height, $thumbPath );
651 } // END OF function renderThumb
654 * Really render a thumbnail
658 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
659 global $wgSVGConverters, $wgSVGConverter,
660 $wgUseImageMagick, $wgImageMagickConvertCommand;
664 if( $this->extension
== 'svg' ) {
665 global $wgSVGConverters, $wgSVGConverter;
666 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
667 global $wgSVGConverterPath;
669 array( '$path/', '$width', '$input', '$output' ),
670 array( $wgSVGConverterPath,
672 escapeshellarg( $this->imagePath
),
673 escapeshellarg( $thumbPath ) ),
674 $wgSVGConverters[$wgSVGConverter] );
675 $conv = shell_exec( $cmd );
679 } elseif ( $wgUseImageMagick ) {
681 # Specify white background color, will be used for transparent images
682 # in Internet Explorer/Windows instead of default black.
683 $cmd = $wgImageMagickConvertCommand .
684 " -quality 85 -background white -geometry {$width} ".
685 escapeshellarg($this->imagePath
) . " " .
686 escapeshellarg($thumbPath);
687 $conv = shell_exec( $cmd );
689 # Use PHP's builtin GD library functions.
691 # First find out what kind of file this is, and select the correct
692 # input routine for this.
696 switch( $this->type
) {
698 $src_image = imagecreatefromgif( $this->imagePath
);
701 $src_image = imagecreatefromjpeg( $this->imagePath
);
705 $src_image = imagecreatefrompng( $this->imagePath
);
706 $truecolor = ( $this->bits
> 8 );
708 case 15: # WBMP for WML
709 $src_image = imagecreatefromwbmp( $this->imagePath
);
712 $src_image = imagecreatefromxbm( $this->imagePath
);
715 return 'Image type not supported';
719 $dst_image = imagecreatetruecolor( $width, $height );
721 $dst_image = imagecreate( $width, $height );
723 imagecopyresampled( $dst_image, $src_image,
725 $width, $height, $this->width
, $this->height
);
726 switch( $this->type
) {
731 imagepng( $dst_image, $thumbPath );
734 imageinterlace( $dst_image );
735 imagejpeg( $dst_image, $thumbPath, 95 );
740 imagedestroy( $dst_image );
741 imagedestroy( $src_image );
744 # Check for zero-sized thumbnails. Those can be generated when
745 # no disk space is available or some other error occurs
747 if( file_exists( $thumbPath ) ) {
748 $thumbstat = stat( $thumbPath );
749 if( $thumbstat['size'] == 0 ) {
750 unlink( $thumbPath );
756 * Get all thumbnail names previously generated for this image
758 function getThumbnails( $shared = false ) {
761 $dir = wfImageThumbDir( $this->name
, $shared );
763 // This generates an error on failure, hence the @
764 $handle = @opendir
( $dir );
767 while ( false !== ( $file = readdir($handle) ) ) {
768 if ( $file{0} != '.' ) {
779 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
781 function purgeCache( $archiveFiles = array(), $shared = false ) {
782 global $wgInternalServer, $wgUseSquid;
784 // Refresh metadata cache
785 $this->loadFromFile();
786 $this->saveToCache();
789 $files = $this->getThumbnails( $shared );
790 $dir = wfImageThumbDir( $this->name
, $shared );
792 foreach ( $files as $file ) {
793 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
794 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
795 @unlink
( "$dir/$file" );
801 $urls[] = $wgInternalServer . $this->getViewURL();
802 foreach ( $archiveFiles as $file ) {
803 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
805 wfPurgeSquidServers( $urls );
810 * Return the image history of this image, line by line.
811 * starts with current version, then old versions.
812 * uses $this->historyLine to check which line to return:
813 * 0 return line for current version
814 * 1 query for old versions, return first one
815 * 2, ... return next old version from above query
819 function nextHistoryLine() {
820 $fname = 'Image::nextHistoryLine()';
821 $dbr =& wfGetDB( DB_SLAVE
);
822 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
823 $this->historyRes
= $dbr->select( 'image',
824 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
825 array( 'img_name' => $this->title
->getDBkey() ),
828 if ( 0 == wfNumRows( $this->historyRes
) ) {
831 } else if ( $this->historyLine
== 1 ) {
832 $this->historyRes
= $dbr->select( 'oldimage',
833 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
834 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
835 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
838 $this->historyLine ++
;
840 return $dbr->fetchObject( $this->historyRes
);
844 * Reset the history pointer to the first element of the history
847 function resetHistory() {
848 $this->historyLine
= 0;
852 * Return true if the file is of a type that can't be directly
853 * rendered by typical browsers and needs to be re-rasterized.
856 function mustRender() {
858 return ( $this->extension
== 'svg' );
862 * Return the full filesystem path to the file. Note that this does
863 * not mean that a file actually exists under that location.
865 * This path depends on whether directory hashing is active or not,
866 * i.e. whether the images are all found in the same directory,
867 * or in hashed paths like /images/3/3c.
870 * @param boolean $fromSharedDirectory Return the path to the file
871 * in a shared repository (see $wgUseSharedRepository and related
872 * options in DefaultSettings.php) instead of a local one.
875 function getFullPath( $fromSharedRepository = false ) {
876 global $wgUploadDirectory, $wgSharedUploadDirectory;
877 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
879 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
882 // $wgSharedUploadDirectory may be false, if thumb.php is used
884 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
896 function isKnownImageExtension( $ext ) {
897 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
898 return in_array( $ext, $extensions );
902 * Record an image upload in the upload log and the image table
904 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
905 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
906 global $wgUseCopyrightUpload;
908 $fname = 'Image::recordUpload';
909 $dbw =& wfGetDB( DB_MASTER
);
911 # img_name must be unique
912 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
913 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
916 // Delete thumbnails and refresh the cache
919 // Fail now if the image isn't there
920 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
924 if ( $wgUseCopyrightUpload ) {
925 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
926 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
927 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
932 $now = wfTimestampNow();
934 # Test to see if the row exists using INSERT IGNORE
935 # This avoids race conditions by locking the row until the commit, and also
936 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
937 $dbw->insert( 'image',
939 'img_name' => $this->name
,
940 'img_size'=> $this->size
,
941 'img_width' => $this->width
,
942 'img_height' => $this->height
,
943 'img_bits' => $this->bits
,
944 'img_type' => $this->type
,
945 'img_timestamp' => $dbw->timestamp($now),
946 'img_description' => $desc,
947 'img_user' => $wgUser->getID(),
948 'img_user_text' => $wgUser->getName(),
951 $descTitle = $this->getTitle();
953 if ( $dbw->affectedRows() ) {
954 # Successfully inserted, this is a new image
955 $id = $descTitle->getArticleID();
958 $article = new Article( $descTitle );
959 $article->insertNewArticle( $textdesc, $desc, false, false, true );
962 # Collision, this is an update of an image
963 # Insert previous contents into oldimage
964 $dbw->insertSelect( 'oldimage', 'image',
966 'oi_name' => 'img_name',
967 'oi_archive_name' => $dbw->addQuotes( $oldver ),
968 'oi_size' => 'img_size',
969 'oi_width' => 'img_width',
970 'oi_height' => 'img_height',
971 'oi_bits' => 'img_bits',
972 'oi_type' => 'img_type',
973 'oi_timestamp' => 'img_timestamp',
974 'oi_description' => 'img_description',
975 'oi_user' => 'img_user',
976 'oi_user_text' => 'img_user_text',
977 ), array( 'img_name' => $this->name
), $fname
980 # Update the current image row
981 $dbw->update( 'image',
983 'img_size' => $this->size
,
984 'img_width' => $this->width
,
985 'img_height' => $this->height
,
986 'img_bits' => $this->bits
,
987 'img_type' => $this->type
,
988 'img_timestamp' => $dbw->timestamp(),
989 'img_user' => $wgUser->getID(),
990 'img_user_text' => $wgUser->getName(),
991 'img_description' => $desc,
992 ), array( /* WHERE */
993 'img_name' => $this->name
997 # Invalidate the cache for the description page
998 $descTitle->invalidateCache();
1001 $log = new LogPage( 'upload' );
1002 $log->addEntry( 'upload', $descTitle, $desc );
1011 * Returns the image directory of an image
1012 * If the directory does not exist, it is created.
1013 * The result is an absolute path.
1015 * This function is called from thumb.php before Setup.php is included
1017 * @param string $fname file name of the image file
1020 function wfImageDir( $fname ) {
1021 global $wgUploadDirectory, $wgHashedUploadDirectory;
1023 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1025 $hash = md5( $fname );
1026 $oldumask = umask(0);
1027 $dest = $wgUploadDirectory . '/' . $hash{0};
1028 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1029 $dest .= '/' . substr( $hash, 0, 2 );
1030 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1037 * Returns the image directory of an image's thubnail
1038 * If the directory does not exist, it is created.
1039 * The result is an absolute path.
1041 * This function is called from thumb.php before Setup.php is included
1043 * @param string $fname file name of the original image file
1044 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1045 * @param boolean $shared (optional) use the shared upload directory
1048 function wfImageThumbDir( $fname, $shared = false ) {
1049 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1050 $dir = "$base/$fname";
1052 if ( !is_dir( $base ) ) {
1053 $oldumask = umask(0);
1054 @mkdir
( $base, 0777 );
1058 if ( ! is_dir( $dir ) ) {
1059 $oldumask = umask(0);
1060 @mkdir
( $dir, 0777 );
1068 * Old thumbnail directory, kept for conversion
1070 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1071 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1075 * Returns the image directory of an image's old version
1076 * If the directory does not exist, it is created.
1077 * The result is an absolute path.
1079 * This function is called from thumb.php before Setup.php is included
1081 * @param string $fname file name of the thumbnail file, including file size prefix
1082 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1083 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1086 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1087 global $wgUploadDirectory, $wgHashedUploadDirectory,
1088 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1089 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1090 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1091 if (!$hashdir) { return $dir.'/'.$subdir; }
1092 $hash = md5( $fname );
1093 $oldumask = umask(0);
1095 # Suppress warning messages here; if the file itself can't
1096 # be written we'll worry about it then.
1097 wfSuppressWarnings();
1099 $archive = $dir.'/'.$subdir;
1100 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1101 $archive .= '/' . $hash{0};
1102 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1103 $archive .= '/' . substr( $hash, 0, 2 );
1104 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1106 wfRestoreWarnings();
1113 * Return the hash path component of an image path (URL or filesystem),
1114 * e.g. "/3/3c/", or just "/" if hashing is not used.
1116 * @param $dbkey The filesystem / database name of the file
1117 * @param $fromSharedDirectory Use the shared file repository? It may
1118 * use different hash settings from the local one.
1120 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1121 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1122 global $wgHashedUploadDirectory;
1124 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
1125 $wgHashedUploadDirectory;
1127 $hash = md5($dbkey);
1128 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1135 * Returns the image URL of an image's old version
1137 * @param string $fname file name of the image file
1138 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1141 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1142 global $wgUploadPath, $wgHashedUploadDirectory;
1144 if ($wgHashedUploadDirectory) {
1145 $hash = md5( substr( $name, 15) );
1146 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1147 substr( $hash, 0, 2 ) . '/'.$name;
1149 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1151 return wfUrlencode($url);
1155 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1156 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1158 * @param string $length
1159 * @return int Length in pixels
1161 function wfScaleSVGUnit( $length ) {
1162 static $unitLength = array(
1169 '' => 1.0, // "User units" pixels by default
1170 '%' => 2.0, // Fake it!
1172 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1173 $length = FloatVal( $matches[1] );
1174 $unit = $matches[2];
1175 return round( $length * $unitLength[$unit] );
1178 return round( FloatVal( $length ) );
1183 * Compatible with PHP getimagesize()
1184 * @todo support gzipped SVGZ
1185 * @todo check XML more carefully
1186 * @todo sensible defaults
1188 * @param string $filename
1191 function wfGetSVGsize( $filename ) {
1195 // Read a chunk of the file
1196 $f = fopen( $filename, "rt" );
1197 if( !$f ) return false;
1198 $chunk = fread( $f, 4096 );
1201 // Uber-crappy hack! Run through a real XML parser.
1202 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1206 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1207 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1209 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1210 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1213 return array( $width, $height, 'SVG',
1214 "width=\"$width\" height=\"$height\"" );
1218 * Is an image on the bad image list?
1220 function wfIsBadImage( $name ) {
1223 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1224 foreach ( $lines as $line ) {
1225 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE
) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1226 $t = Title
::newFromText( $m[1] );
1227 if ( $t->getDBkey() == $name ) {
1238 * Wrapper class for thumbnail images
1239 * @package MediaWiki
1241 class ThumbnailImage
{
1243 * @param string $path Filesystem path to the thumb
1244 * @param string $url URL path to the thumb
1247 function ThumbnailImage( $url, $width, $height, $path = false ) {
1249 $this->width
= $width;
1250 $this->height
= $height;
1251 $this->path
= $path;
1255 * @return string The thumbnail URL
1262 * Return HTML <img ... /> tag for the thumbnail, will include
1263 * width and height attributes and a blank alt text (as required).
1265 * You can set or override additional attributes by passing an
1266 * associative array of name => data pairs. The data will be escaped
1267 * for HTML output, so should be in plaintext.
1269 * @param array $attribs
1273 function toHtml( $attribs = array() ) {
1274 $attribs['src'] = $this->url
;
1275 $attribs['width'] = $this->width
;
1276 $attribs['height'] = $this->height
;
1277 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1280 foreach( $attribs as $name => $data ) {
1281 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';