9a0d055c5aac43a8e6c0a995ee253d90953096f2
7 * NOTE FOR WINDOWS USERS:
8 * To enable EXIF functions, add the folloing lines to the
9 * "Windows extensions" section of php.ini:
11 * extension=extensions/php_mbstring.dll
12 * extension=extensions/php_exif.dll
16 require_once('Exif.php');
19 * Bump this number when serialized cache records may be incompatible.
21 define( 'MW_IMAGE_VERSION', 1 );
24 * Class to represent an image
26 * Provides methods to retrieve paths (physical, logical, URL),
27 * to generate thumbnails or for uploading.
35 var $name, # name of the image (constructor)
36 $imagePath, # Path of the image (loadFromXxx)
37 $url, # Image URL (accessor)
38 $title, # Title object for this image (constructor)
39 $fileExists, # does the image file exist on disk? (loadFromXxx)
40 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
41 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
42 $historyRes, # result of the query for the image's history (nextHistoryLine)
45 $bits, # --- returned by getimagesize (loadFromXxx)
47 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
48 $mime, # MIME type, determined by MimeMagic::guessMimeType
49 $size, # Size in bytes (loadFromXxx)
51 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
57 * Create an Image object from an image name
59 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
62 function newFromName( $name ) {
63 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
64 if ( is_object( $title ) ) {
65 return new Image( $title );
72 * Obsolete factory function, use constructor
74 function newFromTitle( $title ) {
75 return new Image( $title );
78 function Image( $title ) {
79 if( !is_object( $title ) ) {
80 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
82 $this->title
=& $title;
83 $this->name
= $title->getDBkey();
84 $this->metadata
= serialize ( array() ) ;
86 $n = strrpos( $this->name
, '.' );
87 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
88 $this->historyLine
= 0;
90 $this->dataLoaded
= false;
94 * Get the memcached keys
95 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
97 function getCacheKeys( $shared = false ) {
98 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
100 $foundCached = false;
101 $hashedName = md5($this->name
);
102 $keys = array( "$wgDBname:Image:$hashedName" );
103 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
104 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
110 * Try to load image metadata from memcached. Returns true on success.
112 function loadFromCache() {
113 global $wgUseSharedUploads, $wgMemc;
114 $fname = 'Image::loadFromMemcached';
115 wfProfileIn( $fname );
116 $this->dataLoaded
= false;
117 $keys = $this->getCacheKeys();
118 $cachedValues = $wgMemc->get( $keys[0] );
120 // Check if the key existed and belongs to this version of MediaWiki
121 if (!empty($cachedValues) && is_array($cachedValues)
122 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
123 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
125 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
126 # if this is shared file, we need to check if image
127 # in shared repository has not changed
128 if ( isset( $keys[1] ) ) {
129 $commonsCachedValues = $wgMemc->get( $keys[1] );
130 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
131 && isset($commonsCachedValues['version'])
132 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
133 && isset($commonsCachedValues['mime'])) {
134 wfDebug( "Pulling image metadata from shared repository cache\n" );
135 $this->name
= $commonsCachedValues['name'];
136 $this->imagePath
= $commonsCachedValues['imagePath'];
137 $this->fileExists
= $commonsCachedValues['fileExists'];
138 $this->width
= $commonsCachedValues['width'];
139 $this->height
= $commonsCachedValues['height'];
140 $this->bits
= $commonsCachedValues['bits'];
141 $this->type
= $commonsCachedValues['type'];
142 $this->mime
= $commonsCachedValues['mime'];
143 $this->metadata
= $commonsCachedValues['metadata'];
144 $this->size
= $commonsCachedValues['size'];
145 $this->fromSharedDirectory
= true;
146 $this->dataLoaded
= true;
147 $this->imagePath
= $this->getFullPath(true);
151 wfDebug( "Pulling image metadata from local cache\n" );
152 $this->name
= $cachedValues['name'];
153 $this->imagePath
= $cachedValues['imagePath'];
154 $this->fileExists
= $cachedValues['fileExists'];
155 $this->width
= $cachedValues['width'];
156 $this->height
= $cachedValues['height'];
157 $this->bits
= $cachedValues['bits'];
158 $this->type
= $cachedValues['type'];
159 $this->mime
= $cachedValues['mime'];
160 $this->metadata
= $cachedValues['metadata'];
161 $this->size
= $cachedValues['size'];
162 $this->fromSharedDirectory
= false;
163 $this->dataLoaded
= true;
164 $this->imagePath
= $this->getFullPath();
167 if ( $this->dataLoaded
) {
168 wfIncrStats( 'image_cache_hit' );
170 wfIncrStats( 'image_cache_miss' );
173 wfProfileOut( $fname );
174 return $this->dataLoaded
;
178 * Save the image metadata to memcached
180 function saveToCache() {
183 $keys = $this->getCacheKeys();
184 if ( $this->fileExists
) {
185 // We can't cache negative metadata for non-existent files,
186 // because if the file later appears in commons, the local
187 // keys won't be purged.
188 $cachedValues = array(
189 'version' => MW_IMAGE_VERSION
,
190 'name' => $this->name
,
191 'imagePath' => $this->imagePath
,
192 'fileExists' => $this->fileExists
,
193 'fromShared' => $this->fromSharedDirectory
,
194 'width' => $this->width
,
195 'height' => $this->height
,
196 'bits' => $this->bits
,
197 'type' => $this->type
,
198 'mime' => $this->mime
,
199 'metadata' => $this->metadata
,
200 'size' => $this->size
);
202 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
204 // However we should clear them, so they aren't leftover
205 // if we've deleted the file.
206 $wgMemc->delete( $keys[0] );
211 * Load metadata from the file itself
213 function loadFromFile() {
214 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang,
216 $fname = 'Image::loadFromFile';
217 wfProfileIn( $fname );
218 $this->imagePath
= $this->getFullPath();
219 $this->fileExists
= file_exists( $this->imagePath
);
220 $this->fromSharedDirectory
= false;
223 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
225 # If the file is not found, and a shared upload directory is used, look for it there.
226 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
227 # In case we're on a wgCapitalLinks=false wiki, we
228 # capitalize the first letter of the filename before
229 # looking it up in the shared repository.
230 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
231 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
232 if ( $this->fileExists
) {
233 $this->name
= $sharedImage->name
;
234 $this->imagePath
= $this->getFullPath(true);
235 $this->fromSharedDirectory
= true;
240 if ( $this->fileExists
) {
241 $magic=& wfGetMimeMagic();
243 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
244 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
247 $this->size
= filesize( $this->imagePath
);
249 $magic=& wfGetMimeMagic();
252 if( $this->mime
== 'image/svg' ) {
253 wfSuppressWarnings();
254 $gis = wfGetSVGsize( $this->imagePath
);
257 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
258 # Don't try to get the width and height of sound and video files, that's bad for performance
261 $gis[2]= 0; //unknown
262 $gis[3]= ""; //width height string
265 wfSuppressWarnings();
266 $gis = getimagesize( $this->imagePath
);
270 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
275 $gis[2]= 0; //unknown
276 $gis[3]= ""; //width height string
279 $this->type
= MEDIATYPE_UNKNOWN
;
280 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
283 $this->width
= $gis[0];
284 $this->height
= $gis[1];
286 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
288 #NOTE: we have to set this flag early to avoid load() to be called
289 # be some of the functions below. This may lead to recursion or other bad things!
290 # as ther's only one thread of execution, this should be safe anyway.
291 $this->dataLoaded
= true;
294 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
295 else $this->metadata
= serialize ( array() ) ;
297 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
298 else $this->bits
= 0;
300 wfProfileOut( $fname );
304 * Load image metadata from the DB
306 function loadFromDB() {
307 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
308 $fname = 'Image::loadFromDB';
309 wfProfileIn( $fname );
311 $dbr =& wfGetDB( DB_SLAVE
);
313 $this->checkDBSchema($dbr);
315 $row = $dbr->selectRow( 'image',
316 array( 'img_size', 'img_width', 'img_height', 'img_bits',
317 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
318 array( 'img_name' => $this->name
), $fname );
320 $this->fromSharedDirectory
= false;
321 $this->fileExists
= true;
322 $this->loadFromRow( $row );
323 $this->imagePath
= $this->getFullPath();
324 // Check for rows from a previous schema, quietly upgrade them
325 if ( is_null($this->type
) ) {
328 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
329 # In case we're on a wgCapitalLinks=false wiki, we
330 # capitalize the first letter of the filename before
331 # looking it up in the shared repository.
332 $name = $wgContLang->ucfirst($this->name
);
334 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
336 'img_size', 'img_width', 'img_height', 'img_bits',
337 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
338 array( 'img_name' => $name ), $fname );
340 $this->fromSharedDirectory
= true;
341 $this->fileExists
= true;
342 $this->imagePath
= $this->getFullPath(true);
344 $this->loadFromRow( $row );
346 // Check for rows from a previous schema, quietly upgrade them
347 if ( is_null($this->type
) ) {
359 $this->fileExists
= false;
360 $this->fromSharedDirectory
= false;
361 $this->metadata
= serialize ( array() ) ;
364 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
365 $this->dataLoaded
= true;
366 wfProfileOut( $fname );
370 * Load image metadata from a DB result row
372 function loadFromRow( &$row ) {
373 $this->size
= $row->img_size
;
374 $this->width
= $row->img_width
;
375 $this->height
= $row->img_height
;
376 $this->bits
= $row->img_bits
;
377 $this->type
= $row->img_media_type
;
379 $major= $row->img_major_mime
;
380 $minor= $row->img_minor_mime
;
382 if (!$major) $this->mime
= "unknown/unknown";
384 if (!$minor) $minor= "unknown";
385 $this->mime
= $major.'/'.$minor;
388 $this->metadata
= $row->img_metadata
;
389 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
391 $this->dataLoaded
= true;
395 * Load image metadata from cache or DB, unless already loaded
398 global $wgSharedUploadDBname, $wgUseSharedUploads;
399 if ( !$this->dataLoaded
) {
400 if ( !$this->loadFromCache() ) {
402 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
403 $this->loadFromFile();
404 } elseif ( $this->fileExists
) {
405 $this->saveToCache();
408 $this->dataLoaded
= true;
413 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
414 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
416 function upgradeRow() {
417 global $wgDBname, $wgSharedUploadDBname;
418 $fname = 'Image::upgradeRow';
419 wfProfileIn( $fname );
421 $this->loadFromFile();
422 $dbw =& wfGetDB( DB_MASTER
);
424 if ( $this->fromSharedDirectory
) {
425 if ( !$wgSharedUploadDBname ) {
426 wfProfileOut( $fname );
430 // Write to the other DB using selectDB, not database selectors
431 // This avoids breaking replication in MySQL
432 $dbw->selectDB( $wgSharedUploadDBname );
435 $this->checkDBSchema($dbw);
437 if (strpos($this->mime
,'/')!==false) {
438 list($major,$minor)= explode('/',$this->mime
,2);
445 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
447 $dbw->update( 'image',
449 'img_width' => $this->width
,
450 'img_height' => $this->height
,
451 'img_bits' => $this->bits
,
452 'img_media_type' => $this->type
,
453 'img_major_mime' => $major,
454 'img_minor_mime' => $minor,
455 'img_metadata' => $this->metadata
,
456 ), array( 'img_name' => $this->name
), $fname
458 if ( $this->fromSharedDirectory
) {
459 $dbw->selectDB( $wgDBname );
461 wfProfileOut( $fname );
465 * Return the name of this image
473 * Return the associated title object
476 function getTitle() {
481 * Return the URL of the image file
487 if($this->fileExists
) {
488 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
496 function getViewURL() {
497 if( $this->mustRender()) {
498 if( $this->canRender() ) {
499 return $this->createThumb( $this->getWidth() );
502 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
503 return $this->getURL(); #hm... return NULL?
506 return $this->getURL();
511 * Return the image path of the image in the
512 * local file system as an absolute path
515 function getImagePath() {
517 return $this->imagePath
;
521 * Return the width of the image
523 * Returns -1 if the file specified is not a known image type
526 function getWidth() {
532 * Return the height of the image
534 * Returns -1 if the file specified is not a known image type
537 function getHeight() {
539 return $this->height
;
543 * Return the size of the image file, in bytes
552 * Returns the mime type of the file.
554 function getMimeType() {
560 * Return the type of the media in the file.
561 * Use the value returned by this function with the MEDIATYPE_xxx constants.
563 function getMediaType() {
569 * Checks if the file can be presented to the browser as a bitmap.
571 * Currently, this checks if the file is an image format
572 * that can be converted to a format
573 * supported by all browsers (namely GIF, PNG and JPEG),
574 * or if it is an SVG image and SVG conversion is enabled.
576 * @todo remember the result of this check.
578 function canRender() {
579 global $wgUseImageMagick;
581 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
583 $mime= $this->getMimeType();
585 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
587 #if it's SVG, check if there's a converter enabled
588 if ($mime === 'image/svg') {
589 global $wgSVGConverters, $wgSVGConverter;
591 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
592 wfDebug( "Image::canRender: SVG is ready!\n" );
595 wfDebug( "Image::canRender: SVG renderer missing\n" );
599 #image formats available on ALL browsers
600 if ( $mime === 'image/gif'
601 ||
$mime === 'image/png'
602 ||
$mime === 'image/jpeg' ) return true;
604 #image formats that can be converted to the above formats
605 if ($wgUseImageMagick) {
606 #convertable by ImageMagick (there are more...)
607 if ( $mime === 'image/vnd.wap.wbmp'
608 ||
$mime === 'image/x-xbitmap'
609 ||
$mime === 'image/x-xpixmap'
610 #|| $mime === 'image/x-icon' #file may be split into multiple parts
611 ||
$mime === 'image/x-portable-anymap'
612 ||
$mime === 'image/x-portable-bitmap'
613 ||
$mime === 'image/x-portable-graymap'
614 ||
$mime === 'image/x-portable-pixmap'
615 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
616 ||
$mime === 'image/x-rgb'
617 ||
$mime === 'image/x-bmp'
618 ||
$mime === 'image/tiff' ) return true;
621 #convertable by the PHP GD image lib
622 if ( $mime === 'image/vnd.wap.wbmp'
623 ||
$mime === 'image/x-xbitmap' ) return true;
631 * Return true if the file is of a type that can't be directly
632 * rendered by typical browsers and needs to be re-rasterized.
634 * This returns true for everything but the bitmap types
635 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
636 * also return true for any non-image formats.
640 function mustRender() {
641 $mime= $this->getMimeType();
643 if ( $mime === "image/gif"
644 ||
$mime === "image/png"
645 ||
$mime === "image/jpeg" ) return false;
651 * Determines if this media file may be shown inline on a page.
653 * This is currently synonymous to canRender(), but this could be
654 * extended to also allow inline display of other media,
655 * like flash animations or videos. If you do so, please keep in mind that
656 * that could be a security risk.
658 function allowInlineDisplay() {
659 return $this->canRender();
663 * Determines if this media file is in a format that is unlikely to
664 * contain viruses or malicious content. It uses the global
665 * $wgTrustedMediaFormats list to determine if the file is safe.
667 * This is used to show a warning on the description page of non-safe files.
668 * It may also be used to disallow direct [[media:...]] links to such files.
670 * Note that this function will always return true if allowInlineDisplay()
671 * or isTrustedFile() is true for this file.
673 function isSafeFile() {
674 if ($this->allowInlineDisplay()) return true;
675 if ($this->isTrustedFile()) return true;
677 global $wgTrustedMediaFormats;
679 $type= $this->getMediaType();
680 $mime= $this->getMimeType();
681 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
683 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
684 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
686 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
687 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
692 /** Returns true if the file is flagged as trusted. Files flagged that way
693 * can be linked to directly, even if that is not allowed for this type of
696 * This is a dummy function right now and always returns false. It could be
697 * implemented to extract a flag from the database. The trusted flag could be
698 * set on upload, if the user has sufficient privileges, to bypass script-
699 * and html-filters. It may even be coupled with cryptographics signatures
702 function isTrustedFile() {
703 #this could be implemented to check a flag in the databas,
704 #look for signatures, etc
709 * Return the escapeLocalURL of this image
712 function getEscapeLocalURL() {
714 return $this->title
->escapeLocalURL();
718 * Return the escapeFullURL of this image
721 function getEscapeFullURL() {
723 return $this->title
->escapeFullURL();
727 * Return the URL of an image, provided its name.
729 * @param string $name Name of the image, without the leading "Image:"
730 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
731 * @return string URL of $name image
735 function imageUrl( $name, $fromSharedDirectory = false ) {
736 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
737 if($fromSharedDirectory) {
739 $path = $wgSharedUploadPath;
741 $base = $wgUploadBaseUrl;
742 $path = $wgUploadPath;
744 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
745 return wfUrlencode( $url );
749 * Returns true if the image file exists on disk.
750 * @return boolean Whether image file exist on disk.
755 return $this->fileExists
;
762 function thumbUrl( $width, $subdir='thumb') {
763 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
764 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
766 // Generate thumb.php URL if possible
770 if ( $this->fromSharedDirectory
) {
771 if ( $wgSharedThumbnailScriptPath ) {
772 $script = $wgSharedThumbnailScriptPath;
775 if ( $wgThumbnailScriptPath ) {
776 $script = $wgThumbnailScriptPath;
780 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
781 if( $this->mustRender() ) {
785 $name = $this->thumbName( $width );
786 if($this->fromSharedDirectory
) {
788 $path = $wgSharedUploadPath;
790 $base = $wgUploadBaseUrl;
791 $path = $wgUploadPath;
793 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
794 $url = "{$base}{$path}/{$subdir}" .
795 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
796 . $this->name
.'/'.$name;
797 $url = wfUrlencode( $url );
799 $url = "{$base}{$path}/{$subdir}/{$name}";
802 return array( $script !== false, $url );
806 * Return the file name of a thumbnail of the specified width
808 * @param integer $width Width of the thumbnail image
809 * @param boolean $shared Does the thumbnail come from the shared repository?
812 function thumbName( $width ) {
813 $thumb = $width."px-".$this->name
;
815 if( $this->mustRender() ) {
816 if( $this->canRender() ) {
817 # Rasterize to PNG (for SVG vector images, etc)
821 #should we use iconThumb here to get a symbolic thumbnail?
822 #or should we fail with an internal error?
823 return NULL; //can't make bitmap
830 * Create a thumbnail of the image having the specified width/height.
831 * The thumbnail will not be created if the width is larger than the
832 * image's width. Let the browser do the scaling in this case.
833 * The thumbnail is stored on disk and is only computed if the thumbnail
834 * file does not exist OR if it is older than the image.
837 * Keeps aspect ratio of original image. If both width and height are
838 * specified, the generated image will be no bigger than width x height,
839 * and will also have correct aspect ratio.
841 * @param integer $width maximum width of the generated thumbnail
842 * @param integer $height maximum height of the image (optional)
845 function createThumb( $width, $height=-1 ) {
846 $thumb = $this->getThumbnail( $width, $height );
847 if( is_null( $thumb ) ) return '';
848 return $thumb->getUrl();
852 * As createThumb, but returns a ThumbnailImage object. This can
853 * provide access to the actual file, the real size of the thumb,
854 * and can produce a convenient <img> tag for you.
856 * @param integer $width maximum width of the generated thumbnail
857 * @param integer $height maximum height of the image (optional)
858 * @return ThumbnailImage
861 function getThumbnail( $width, $height=-1 ) {
862 if ( $height <= 0 ) {
863 return $this->renderThumb( $width );
867 if ($this->canRender()) {
868 if ( $width > $this->width
* $height / $this->height
)
869 $width = floor( $this->width
* $height / $this->height
);
870 # Note this is the largest width such that the thumbnail's
871 # height is at most $height.
873 $thumb = $this->renderThumb( $width );
875 else $thumb= NULL; #not a bitmap or renderable image, don't try.
877 if( is_null( $thumb ) ) {
878 $thumb = $this->iconThumb();
884 * @return ThumbnailImage
886 function iconThumb() {
887 global $wgStylePath, $wgStyleDirectory;
889 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
890 foreach( $try as $icon ) {
891 $path = '/common/images/icons/' . $icon;
892 $filepath = $wgStyleDirectory . $path;
893 if( file_exists( $filepath ) ) {
894 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
901 * Create a thumbnail of the image having the specified width.
902 * The thumbnail will not be created if the width is larger than the
903 * image's width. Let the browser do the scaling in this case.
904 * The thumbnail is stored on disk and is only computed if the thumbnail
905 * file does not exist OR if it is older than the image.
906 * Returns an object which can return the pathname, URL, and physical
907 * pixel size of the thumbnail -- or null on failure.
909 * @return ThumbnailImage
912 function renderThumb( $width, $useScript = true ) {
913 global $wgUseSquid, $wgInternalServer;
914 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
915 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
917 $fname = 'Image::renderThumb';
918 wfProfileIn( $fname );
920 $width = intval( $width );
923 if ( ! $this->exists() )
925 # If there is no image, there will be no thumbnail
926 wfProfileOut( $fname );
930 # Sanity check $width
931 if( $width <= 0 ||
$this->width
<= 0) {
933 wfProfileOut( $fname );
937 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
938 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
939 # an exception for it.
940 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
941 $this->getMimeType() !== 'image/jpeg' &&
942 $this->width
* $this->height
> $wgMaxImageArea )
944 wfProfileOut( $fname );
948 $maxsize = $this->mustRender()
949 ?
max( $this->width
, $wgSVGMaxSize )
951 if( $width > $maxsize ) {
952 # Don't make an image bigger than the source
953 $thumb = new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
954 wfProfileOut( $fname );
958 $height = round( $this->height
* $width / $this->width
);
960 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
961 if ( $isScriptUrl && $useScript ) {
962 // Use thumb.php to render the image
963 $thumb = new ThumbnailImage( $url, $width, $height );
964 wfProfileOut( $fname );
968 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
969 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
971 if ( !file_exists( $thumbPath ) ||
972 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) ) {
973 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
976 if ( file_exists( $oldThumbPath ) ) {
977 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
978 rename( $oldThumbPath, $thumbPath );
981 unlink( $oldThumbPath );
985 $this->reallyRenderThumb( $thumbPath, $width, $height );
988 # This has to be done after the image is updated and present for all machines on NFS,
989 # or else the old version might be stored into the squid again
991 if ( substr( $url, 0, 4 ) == 'http' ) {
992 $urlArr = array( $url );
994 $urlArr = array( $wgInternalServer.$url );
996 wfPurgeSquidServers($urlArr);
1001 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1002 wfProfileOut( $fname );
1004 } // END OF function renderThumb
1007 * Really render a thumbnail
1008 * Call this only for images for which canRender() returns true.
1012 function reallyRenderThumb( $thumbPath, $width, $height ) {
1013 global $wgSVGConverters, $wgSVGConverter,
1014 $wgUseImageMagick, $wgImageMagickConvertCommand;
1018 if( $this->mime
=== "image/svg" ) {
1019 #Right now we have only SVG
1021 global $wgSVGConverters, $wgSVGConverter;
1022 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1023 global $wgSVGConverterPath;
1025 array( '$path/', '$width', '$height', '$input', '$output' ),
1026 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1029 wfEscapeShellArg( $this->imagePath
),
1030 wfEscapeShellArg( $thumbPath ) ),
1031 $wgSVGConverters[$wgSVGConverter] );
1032 wfProfileIn( 'rsvg' );
1033 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1034 $conv = wfShellExec( $cmd );
1035 wfProfileOut( 'rsvg' );
1039 } elseif ( $wgUseImageMagick ) {
1041 # Specify white background color, will be used for transparent images
1042 # in Internet Explorer/Windows instead of default black.
1044 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1045 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1046 # the wrong size in the second case.
1047 $cmd = $wgImageMagickConvertCommand .
1048 " -quality 85 -background white -size {$width} ".
1049 wfEscapeShellArg($this->imagePath
) . " -resize {$width}x{$height} " .
1050 wfEscapeShellArg($thumbPath);
1051 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1052 wfProfileIn( 'convert' );
1053 $conv = wfShellExec( $cmd );
1054 wfProfileOut( 'convert' );
1056 # Use PHP's builtin GD library functions.
1058 # First find out what kind of file this is, and select the correct
1059 # input routine for this.
1062 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1063 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1064 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1065 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1066 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1068 if( !isset( $typemap[$this->mime
] ) ) {
1069 $err = 'Image type not supported';
1070 wfDebug( "$err\n" );
1073 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1075 if( !function_exists( $loader ) ) {
1076 $err = "Incomplete GD library configuration: missing function $loader";
1077 wfDebug( "$err\n" );
1080 if( $colorStyle == 'palette' ) {
1082 } elseif( $colorStyle == 'truecolor' ) {
1084 } elseif( $colorStyle == 'bits' ) {
1085 $truecolor = ( $this->bits
> 8 );
1088 $src_image = call_user_func( $loader, $this->imagePath
);
1090 $dst_image = imagecreatetruecolor( $width, $height );
1092 $dst_image = imagecreate( $width, $height );
1094 imagecopyresampled( $dst_image, $src_image,
1096 $width, $height, $this->width
, $this->height
);
1097 call_user_func( $saveType, $dst_image, $thumbPath );
1098 imagedestroy( $dst_image );
1099 imagedestroy( $src_image );
1103 # Check for zero-sized thumbnails. Those can be generated when
1104 # no disk space is available or some other error occurs
1106 if( file_exists( $thumbPath ) ) {
1107 $thumbstat = stat( $thumbPath );
1108 if( $thumbstat['size'] == 0 ) {
1109 unlink( $thumbPath );
1114 function imageJpegWrapper( $dst_image, $thumbPath ) {
1115 imageinterlace( $dst_image );
1116 imagejpeg( $dst_image, $thumbPath, 95 );
1120 * Get all thumbnail names previously generated for this image
1122 function getThumbnails( $shared = false ) {
1123 if ( Image
::isHashed( $shared ) ) {
1126 $dir = wfImageThumbDir( $this->name
, $shared );
1128 // This generates an error on failure, hence the @
1129 $handle = @opendir
( $dir );
1132 while ( false !== ( $file = readdir($handle) ) ) {
1133 if ( $file{0} != '.' ) {
1137 closedir( $handle );
1147 * Refresh metadata in memcached, but don't touch thumbnails or squid
1149 function purgeMetadataCache() {
1151 $this->loadFromFile();
1152 $this->saveToCache();
1156 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1158 function purgeCache( $archiveFiles = array(), $shared = false ) {
1159 global $wgInternalServer, $wgUseSquid;
1161 // Refresh metadata cache
1162 $this->purgeMetadataCache();
1164 // Delete thumbnails
1165 $files = $this->getThumbnails( $shared );
1166 $dir = wfImageThumbDir( $this->name
, $shared );
1168 foreach ( $files as $file ) {
1169 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1170 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1171 @unlink
( "$dir/$file" );
1176 if ( $wgUseSquid ) {
1177 $urls[] = $wgInternalServer . $this->getViewURL();
1178 foreach ( $archiveFiles as $file ) {
1179 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1181 wfPurgeSquidServers( $urls );
1185 function checkDBSchema(&$db) {
1186 # img_name must be unique
1187 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1188 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1191 #new fields must exist
1192 if ( !$db->fieldExists( 'image', 'img_media_type' )
1193 ||
!$db->fieldExists( 'image', 'img_metadata' )
1194 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1196 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1201 * Return the image history of this image, line by line.
1202 * starts with current version, then old versions.
1203 * uses $this->historyLine to check which line to return:
1204 * 0 return line for current version
1205 * 1 query for old versions, return first one
1206 * 2, ... return next old version from above query
1210 function nextHistoryLine() {
1211 $fname = 'Image::nextHistoryLine()';
1212 $dbr =& wfGetDB( DB_SLAVE
);
1214 $this->checkDBSchema($dbr);
1216 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1217 $this->historyRes
= $dbr->select( 'image',
1221 'img_user','img_user_text',
1225 "'' AS oi_archive_name"
1227 array( 'img_name' => $this->title
->getDBkey() ),
1230 if ( 0 == wfNumRows( $this->historyRes
) ) {
1233 } else if ( $this->historyLine
== 1 ) {
1234 $this->historyRes
= $dbr->select( 'oldimage',
1236 'oi_size AS img_size',
1237 'oi_description AS img_description',
1238 'oi_user AS img_user',
1239 'oi_user_text AS img_user_text',
1240 'oi_timestamp AS img_timestamp',
1241 'oi_width as img_width',
1242 'oi_height as img_height',
1245 array( 'oi_name' => $this->title
->getDBkey() ),
1247 array( 'ORDER BY' => 'oi_timestamp DESC' )
1250 $this->historyLine ++
;
1252 return $dbr->fetchObject( $this->historyRes
);
1256 * Reset the history pointer to the first element of the history
1259 function resetHistory() {
1260 $this->historyLine
= 0;
1264 * Return the full filesystem path to the file. Note that this does
1265 * not mean that a file actually exists under that location.
1267 * This path depends on whether directory hashing is active or not,
1268 * i.e. whether the images are all found in the same directory,
1269 * or in hashed paths like /images/3/3c.
1272 * @param boolean $fromSharedDirectory Return the path to the file
1273 * in a shared repository (see $wgUseSharedRepository and related
1274 * options in DefaultSettings.php) instead of a local one.
1277 function getFullPath( $fromSharedRepository = false ) {
1278 global $wgUploadDirectory, $wgSharedUploadDirectory;
1280 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1283 // $wgSharedUploadDirectory may be false, if thumb.php is used
1285 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1297 function isHashed( $shared ) {
1298 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1299 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1303 * Record an image upload in the upload log and the image table
1305 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1306 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1308 $fname = 'Image::recordUpload';
1309 $dbw =& wfGetDB( DB_MASTER
);
1311 $this->checkDBSchema($dbw);
1313 // Delete thumbnails and refresh the metadata cache
1314 $this->purgeCache();
1316 // Fail now if the image isn't there
1317 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1318 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1322 if ( $wgUseCopyrightUpload ) {
1323 if ( $license != '' ) {
1324 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1326 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1327 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1329 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1331 if ( $license != '' ) {
1332 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1333 $textdesc = $filedesc .
1334 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1340 $now = $dbw->timestamp();
1343 if (strpos($this->mime
,'/')!==false) {
1344 list($major,$minor)= explode('/',$this->mime
,2);
1347 $major= $this->mime
;
1351 # Test to see if the row exists using INSERT IGNORE
1352 # This avoids race conditions by locking the row until the commit, and also
1353 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1354 $dbw->insert( 'image',
1356 'img_name' => $this->name
,
1357 'img_size'=> $this->size
,
1358 'img_width' => intval( $this->width
),
1359 'img_height' => intval( $this->height
),
1360 'img_bits' => $this->bits
,
1361 'img_media_type' => $this->type
,
1362 'img_major_mime' => $major,
1363 'img_minor_mime' => $minor,
1364 'img_timestamp' => $now,
1365 'img_description' => $desc,
1366 'img_user' => $wgUser->getID(),
1367 'img_user_text' => $wgUser->getName(),
1368 'img_metadata' => $this->metadata
,
1373 $descTitle = $this->getTitle();
1374 $purgeURLs = array();
1376 if( $dbw->affectedRows() == 0 ) {
1377 # Collision, this is an update of an image
1378 # Insert previous contents into oldimage
1379 $dbw->insertSelect( 'oldimage', 'image',
1381 'oi_name' => 'img_name',
1382 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1383 'oi_size' => 'img_size',
1384 'oi_width' => 'img_width',
1385 'oi_height' => 'img_height',
1386 'oi_bits' => 'img_bits',
1387 'oi_timestamp' => 'img_timestamp',
1388 'oi_description' => 'img_description',
1389 'oi_user' => 'img_user',
1390 'oi_user_text' => 'img_user_text',
1391 ), array( 'img_name' => $this->name
), $fname
1394 # Update the current image row
1395 $dbw->update( 'image',
1397 'img_size' => $this->size
,
1398 'img_width' => intval( $this->width
),
1399 'img_height' => intval( $this->height
),
1400 'img_bits' => $this->bits
,
1401 'img_media_type' => $this->type
,
1402 'img_major_mime' => $major,
1403 'img_minor_mime' => $minor,
1404 'img_timestamp' => $now,
1405 'img_description' => $desc,
1406 'img_user' => $wgUser->getID(),
1407 'img_user_text' => $wgUser->getName(),
1408 'img_metadata' => $this->metadata
,
1409 ), array( /* WHERE */
1410 'img_name' => $this->name
1415 $article = new Article( $descTitle );
1417 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1418 $suppressRC = true; // There's already a log entry, so don't double the RC load
1420 if( $descTitle->exists() ) {
1421 // TODO: insert a null revision into the page history for this update.
1423 $wgUser->addWatch( $descTitle );
1426 # Invalidate the cache for the description page
1427 $descTitle->invalidateCache();
1428 $purgeURLs[] = $descTitle->getInternalURL();
1430 // New image; create the description page.
1431 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1434 # Invalidate cache for all pages using this image
1435 $linksTo = $this->getLinksTo();
1437 if ( $wgUseSquid ) {
1438 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1439 array_push( $wgPostCommitUpdateList, $u );
1441 Title
::touchArray( $linksTo );
1443 $log = new LogPage( 'upload' );
1444 $log->addEntry( 'upload', $descTitle, $desc );
1450 * Get an array of Title objects which are articles which use this image
1451 * Also adds their IDs to the link cache
1453 * This is mostly copied from Title::getLinksTo()
1455 function getLinksTo( $options = '' ) {
1456 $fname = 'Image::getLinksTo';
1457 wfProfileIn( $fname );
1460 $db =& wfGetDB( DB_MASTER
);
1462 $db =& wfGetDB( DB_SLAVE
);
1464 $linkCache =& LinkCache
::singleton();
1466 extract( $db->tableNames( 'page', 'imagelinks' ) );
1467 $encName = $db->addQuotes( $this->name
);
1468 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1469 $res = $db->query( $sql, $fname );
1472 if ( $db->numRows( $res ) ) {
1473 while ( $row = $db->fetchObject( $res ) ) {
1474 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1475 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1476 $retVal[] = $titleObj;
1480 $db->freeResult( $res );
1481 wfProfileOut( $fname );
1485 * Retrive Exif data from the database
1487 * Retrive Exif data from the database and prune unrecognized tags
1488 * and/or tags with invalid contents
1492 function retrieveExifData() {
1493 if ( $this->getMimeType() !== "image/jpeg" )
1496 $exif = new Exif( $this->imagePath
);
1497 return $exif->getFilteredData();
1500 function getExifData() {
1502 if ( $this->metadata
=== '0' )
1505 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1506 $ret = unserialize( $this->metadata
);
1508 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1509 $newver = Exif
::version();
1511 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1512 $this->purgeMetadataCache();
1513 $this->updateExifData( $newver );
1515 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1516 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1517 $format = new FormatExif( $ret );
1519 return $format->getFormattedData();
1522 function updateExifData( $version ) {
1523 $fname = 'Image:updateExifData';
1525 if ( $this->getImagePath() === false ) # Not a local image
1528 # Get EXIF data from image
1529 $exif = $this->retrieveExifData();
1530 if ( count( $exif ) ) {
1531 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1532 $this->metadata
= serialize( $exif );
1534 $this->metadata
= '0';
1537 # Update EXIF data in database
1538 $dbw =& wfGetDB( DB_MASTER
);
1540 $this->checkDBSchema($dbw);
1542 $dbw->update( 'image',
1543 array( 'img_metadata' => $this->metadata
),
1544 array( 'img_name' => $this->name
),
1550 * Returns true if the image does not come from the shared
1555 function isLocal() {
1556 return !$this->fromSharedDirectory
;
1563 * Returns the image directory of an image
1564 * If the directory does not exist, it is created.
1565 * The result is an absolute path.
1567 * This function is called from thumb.php before Setup.php is included
1569 * @param string $fname file name of the image file
1572 function wfImageDir( $fname ) {
1573 global $wgUploadDirectory, $wgHashedUploadDirectory;
1575 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1577 $hash = md5( $fname );
1578 $oldumask = umask(0);
1579 $dest = $wgUploadDirectory . '/' . $hash{0};
1580 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1581 $dest .= '/' . substr( $hash, 0, 2 );
1582 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1589 * Returns the image directory of an image's thubnail
1590 * If the directory does not exist, it is created.
1591 * The result is an absolute path.
1593 * This function is called from thumb.php before Setup.php is included
1595 * @param string $fname file name of the original image file
1596 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1597 * @param boolean $shared (optional) use the shared upload directory
1600 function wfImageThumbDir( $fname, $shared = false ) {
1601 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1602 if ( Image
::isHashed( $shared ) ) {
1603 $dir = "$base/$fname";
1605 if ( !is_dir( $base ) ) {
1606 $oldumask = umask(0);
1607 @mkdir
( $base, 0777 );
1611 if ( ! is_dir( $dir ) ) {
1612 $oldumask = umask(0);
1613 @mkdir
( $dir, 0777 );
1624 * Old thumbnail directory, kept for conversion
1626 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1627 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1631 * Returns the image directory of an image's old version
1632 * If the directory does not exist, it is created.
1633 * The result is an absolute path.
1635 * This function is called from thumb.php before Setup.php is included
1637 * @param string $fname file name of the thumbnail file, including file size prefix
1638 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1639 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1642 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1643 global $wgUploadDirectory, $wgHashedUploadDirectory,
1644 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1645 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1646 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1647 if (!$hashdir) { return $dir.'/'.$subdir; }
1648 $hash = md5( $fname );
1649 $oldumask = umask(0);
1651 # Suppress warning messages here; if the file itself can't
1652 # be written we'll worry about it then.
1653 wfSuppressWarnings();
1655 $archive = $dir.'/'.$subdir;
1656 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1657 $archive .= '/' . $hash{0};
1658 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1659 $archive .= '/' . substr( $hash, 0, 2 );
1660 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1662 wfRestoreWarnings();
1669 * Return the hash path component of an image path (URL or filesystem),
1670 * e.g. "/3/3c/", or just "/" if hashing is not used.
1672 * @param $dbkey The filesystem / database name of the file
1673 * @param $fromSharedDirectory Use the shared file repository? It may
1674 * use different hash settings from the local one.
1676 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1677 if( Image
::isHashed( $fromSharedDirectory ) ) {
1678 $hash = md5($dbkey);
1679 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1686 * Returns the image URL of an image's old version
1688 * @param string $fname file name of the image file
1689 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1692 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1693 global $wgUploadPath, $wgHashedUploadDirectory;
1695 if ($wgHashedUploadDirectory) {
1696 $hash = md5( substr( $name, 15) );
1697 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1698 substr( $hash, 0, 2 ) . '/'.$name;
1700 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1702 return wfUrlencode($url);
1706 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1707 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1709 * @param string $length
1710 * @return int Length in pixels
1712 function wfScaleSVGUnit( $length ) {
1713 static $unitLength = array(
1720 '' => 1.0, // "User units" pixels by default
1721 '%' => 2.0, // Fake it!
1723 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1724 $length = floatval( $matches[1] );
1725 $unit = $matches[2];
1726 return round( $length * $unitLength[$unit] );
1729 return round( floatval( $length ) );
1734 * Compatible with PHP getimagesize()
1735 * @todo support gzipped SVGZ
1736 * @todo check XML more carefully
1737 * @todo sensible defaults
1739 * @param string $filename
1742 function wfGetSVGsize( $filename ) {
1746 // Read a chunk of the file
1747 $f = fopen( $filename, "rt" );
1748 if( !$f ) return false;
1749 $chunk = fread( $f, 4096 );
1752 // Uber-crappy hack! Run through a real XML parser.
1753 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1757 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1758 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1760 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1761 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1764 return array( $width, $height, 'SVG',
1765 "width=\"$width\" height=\"$height\"" );
1769 * Determine if an image exists on the 'bad image list'
1771 * @param string $name The image to check
1774 function wfIsBadImage( $name ) {
1776 static $titleList = false;
1777 if ( $titleList === false ) {
1778 $titleList = array();
1780 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1781 foreach ( $lines as $line ) {
1782 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1783 $t = Title
::newFromText( $m[1] );
1784 $titleList[$t->getDBkey()] = 1;
1789 return array_key_exists( $name, $titleList );
1795 * Wrapper class for thumbnail images
1796 * @package MediaWiki
1798 class ThumbnailImage
{
1800 * @param string $path Filesystem path to the thumb
1801 * @param string $url URL path to the thumb
1804 function ThumbnailImage( $url, $width, $height, $path = false ) {
1806 $this->width
= round( $width );
1807 $this->height
= round( $height );
1808 # These should be integers when they get here.
1809 # If not, there's a bug somewhere. But let's at
1810 # least produce valid HTML code regardless.
1811 $this->path
= $path;
1815 * @return string The thumbnail URL
1822 * Return HTML <img ... /> tag for the thumbnail, will include
1823 * width and height attributes and a blank alt text (as required).
1825 * You can set or override additional attributes by passing an
1826 * associative array of name => data pairs. The data will be escaped
1827 * for HTML output, so should be in plaintext.
1829 * @param array $attribs
1833 function toHtml( $attribs = array() ) {
1834 $attribs['src'] = $this->url
;
1835 $attribs['width'] = $this->width
;
1836 $attribs['height'] = $this->height
;
1837 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1840 foreach( $attribs as $name => $data ) {
1841 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';