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)
52 $lastError; # Error string associated with a thumbnail display error
58 * Create an Image object from an image name
60 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
63 function newFromName( $name ) {
64 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
65 if ( is_object( $title ) ) {
66 return new Image( $title );
73 * Obsolete factory function, use constructor
75 function newFromTitle( $title ) {
76 return new Image( $title );
79 function Image( $title ) {
80 if( !is_object( $title ) ) {
81 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
83 $this->title
=& $title;
84 $this->name
= $title->getDBkey();
85 $this->metadata
= serialize ( array() ) ;
87 $n = strrpos( $this->name
, '.' );
88 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
89 $this->historyLine
= 0;
91 $this->dataLoaded
= false;
95 * Get the memcached keys
96 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
98 function getCacheKeys( $shared = false ) {
99 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
101 $foundCached = false;
102 $hashedName = md5($this->name
);
103 $keys = array( "$wgDBname:Image:$hashedName" );
104 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
105 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
111 * Try to load image metadata from memcached. Returns true on success.
113 function loadFromCache() {
114 global $wgUseSharedUploads, $wgMemc;
115 $fname = 'Image::loadFromMemcached';
116 wfProfileIn( $fname );
117 $this->dataLoaded
= false;
118 $keys = $this->getCacheKeys();
119 $cachedValues = $wgMemc->get( $keys[0] );
121 // Check if the key existed and belongs to this version of MediaWiki
122 if (!empty($cachedValues) && is_array($cachedValues)
123 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
124 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
126 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
127 # if this is shared file, we need to check if image
128 # in shared repository has not changed
129 if ( isset( $keys[1] ) ) {
130 $commonsCachedValues = $wgMemc->get( $keys[1] );
131 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
132 && isset($commonsCachedValues['version'])
133 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
134 && isset($commonsCachedValues['mime'])) {
135 wfDebug( "Pulling image metadata from shared repository cache\n" );
136 $this->name
= $commonsCachedValues['name'];
137 $this->imagePath
= $commonsCachedValues['imagePath'];
138 $this->fileExists
= $commonsCachedValues['fileExists'];
139 $this->width
= $commonsCachedValues['width'];
140 $this->height
= $commonsCachedValues['height'];
141 $this->bits
= $commonsCachedValues['bits'];
142 $this->type
= $commonsCachedValues['type'];
143 $this->mime
= $commonsCachedValues['mime'];
144 $this->metadata
= $commonsCachedValues['metadata'];
145 $this->size
= $commonsCachedValues['size'];
146 $this->fromSharedDirectory
= true;
147 $this->dataLoaded
= true;
148 $this->imagePath
= $this->getFullPath(true);
152 wfDebug( "Pulling image metadata from local cache\n" );
153 $this->name
= $cachedValues['name'];
154 $this->imagePath
= $cachedValues['imagePath'];
155 $this->fileExists
= $cachedValues['fileExists'];
156 $this->width
= $cachedValues['width'];
157 $this->height
= $cachedValues['height'];
158 $this->bits
= $cachedValues['bits'];
159 $this->type
= $cachedValues['type'];
160 $this->mime
= $cachedValues['mime'];
161 $this->metadata
= $cachedValues['metadata'];
162 $this->size
= $cachedValues['size'];
163 $this->fromSharedDirectory
= false;
164 $this->dataLoaded
= true;
165 $this->imagePath
= $this->getFullPath();
168 if ( $this->dataLoaded
) {
169 wfIncrStats( 'image_cache_hit' );
171 wfIncrStats( 'image_cache_miss' );
174 wfProfileOut( $fname );
175 return $this->dataLoaded
;
179 * Save the image metadata to memcached
181 function saveToCache() {
184 $keys = $this->getCacheKeys();
185 if ( $this->fileExists
) {
186 // We can't cache negative metadata for non-existent files,
187 // because if the file later appears in commons, the local
188 // keys won't be purged.
189 $cachedValues = array(
190 'version' => MW_IMAGE_VERSION
,
191 'name' => $this->name
,
192 'imagePath' => $this->imagePath
,
193 'fileExists' => $this->fileExists
,
194 'fromShared' => $this->fromSharedDirectory
,
195 'width' => $this->width
,
196 'height' => $this->height
,
197 'bits' => $this->bits
,
198 'type' => $this->type
,
199 'mime' => $this->mime
,
200 'metadata' => $this->metadata
,
201 'size' => $this->size
);
203 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
205 // However we should clear them, so they aren't leftover
206 // if we've deleted the file.
207 $wgMemc->delete( $keys[0] );
212 * Load metadata from the file itself
214 function loadFromFile() {
215 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang,
217 $fname = 'Image::loadFromFile';
218 wfProfileIn( $fname );
219 $this->imagePath
= $this->getFullPath();
220 $this->fileExists
= file_exists( $this->imagePath
);
221 $this->fromSharedDirectory
= false;
224 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
226 # If the file is not found, and a shared upload directory is used, look for it there.
227 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
228 # In case we're on a wgCapitalLinks=false wiki, we
229 # capitalize the first letter of the filename before
230 # looking it up in the shared repository.
231 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
232 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
233 if ( $this->fileExists
) {
234 $this->name
= $sharedImage->name
;
235 $this->imagePath
= $this->getFullPath(true);
236 $this->fromSharedDirectory
= true;
241 if ( $this->fileExists
) {
242 $magic=& wfGetMimeMagic();
244 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
245 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
248 $this->size
= filesize( $this->imagePath
);
250 $magic=& wfGetMimeMagic();
253 if( $this->mime
== 'image/svg' ) {
254 wfSuppressWarnings();
255 $gis = wfGetSVGsize( $this->imagePath
);
258 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
259 # Don't try to get the width and height of sound and video files, that's bad for performance
262 $gis[2]= 0; //unknown
263 $gis[3]= ""; //width height string
266 wfSuppressWarnings();
267 $gis = getimagesize( $this->imagePath
);
271 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
276 $gis[2]= 0; //unknown
277 $gis[3]= ""; //width height string
280 $this->type
= MEDIATYPE_UNKNOWN
;
281 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
284 $this->width
= $gis[0];
285 $this->height
= $gis[1];
287 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
289 #NOTE: we have to set this flag early to avoid load() to be called
290 # be some of the functions below. This may lead to recursion or other bad things!
291 # as ther's only one thread of execution, this should be safe anyway.
292 $this->dataLoaded
= true;
295 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
296 else $this->metadata
= serialize ( array() ) ;
298 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
299 else $this->bits
= 0;
301 wfProfileOut( $fname );
305 * Load image metadata from the DB
307 function loadFromDB() {
308 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
309 $fname = 'Image::loadFromDB';
310 wfProfileIn( $fname );
312 $dbr =& wfGetDB( DB_SLAVE
);
314 $this->checkDBSchema($dbr);
316 $row = $dbr->selectRow( 'image',
317 array( 'img_size', 'img_width', 'img_height', 'img_bits',
318 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
319 array( 'img_name' => $this->name
), $fname );
321 $this->fromSharedDirectory
= false;
322 $this->fileExists
= true;
323 $this->loadFromRow( $row );
324 $this->imagePath
= $this->getFullPath();
325 // Check for rows from a previous schema, quietly upgrade them
326 if ( is_null($this->type
) ) {
329 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
330 # In case we're on a wgCapitalLinks=false wiki, we
331 # capitalize the first letter of the filename before
332 # looking it up in the shared repository.
333 $name = $wgContLang->ucfirst($this->name
);
335 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
337 'img_size', 'img_width', 'img_height', 'img_bits',
338 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
339 array( 'img_name' => $name ), $fname );
341 $this->fromSharedDirectory
= true;
342 $this->fileExists
= true;
343 $this->imagePath
= $this->getFullPath(true);
345 $this->loadFromRow( $row );
347 // Check for rows from a previous schema, quietly upgrade them
348 if ( is_null($this->type
) ) {
360 $this->fileExists
= false;
361 $this->fromSharedDirectory
= false;
362 $this->metadata
= serialize ( array() ) ;
365 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
366 $this->dataLoaded
= true;
367 wfProfileOut( $fname );
371 * Load image metadata from a DB result row
373 function loadFromRow( &$row ) {
374 $this->size
= $row->img_size
;
375 $this->width
= $row->img_width
;
376 $this->height
= $row->img_height
;
377 $this->bits
= $row->img_bits
;
378 $this->type
= $row->img_media_type
;
380 $major= $row->img_major_mime
;
381 $minor= $row->img_minor_mime
;
383 if (!$major) $this->mime
= "unknown/unknown";
385 if (!$minor) $minor= "unknown";
386 $this->mime
= $major.'/'.$minor;
389 $this->metadata
= $row->img_metadata
;
390 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
392 $this->dataLoaded
= true;
396 * Load image metadata from cache or DB, unless already loaded
399 global $wgSharedUploadDBname, $wgUseSharedUploads;
400 if ( !$this->dataLoaded
) {
401 if ( !$this->loadFromCache() ) {
403 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
404 $this->loadFromFile();
405 } elseif ( $this->fileExists
) {
406 $this->saveToCache();
409 $this->dataLoaded
= true;
414 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
415 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
417 function upgradeRow() {
418 global $wgDBname, $wgSharedUploadDBname;
419 $fname = 'Image::upgradeRow';
420 wfProfileIn( $fname );
422 $this->loadFromFile();
423 $dbw =& wfGetDB( DB_MASTER
);
425 if ( $this->fromSharedDirectory
) {
426 if ( !$wgSharedUploadDBname ) {
427 wfProfileOut( $fname );
431 // Write to the other DB using selectDB, not database selectors
432 // This avoids breaking replication in MySQL
433 $dbw->selectDB( $wgSharedUploadDBname );
436 $this->checkDBSchema($dbw);
438 if (strpos($this->mime
,'/')!==false) {
439 list($major,$minor)= explode('/',$this->mime
,2);
446 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
448 $dbw->update( 'image',
450 'img_width' => $this->width
,
451 'img_height' => $this->height
,
452 'img_bits' => $this->bits
,
453 'img_media_type' => $this->type
,
454 'img_major_mime' => $major,
455 'img_minor_mime' => $minor,
456 'img_metadata' => $this->metadata
,
457 ), array( 'img_name' => $this->name
), $fname
459 if ( $this->fromSharedDirectory
) {
460 $dbw->selectDB( $wgDBname );
462 wfProfileOut( $fname );
466 * Return the name of this image
474 * Return the associated title object
477 function getTitle() {
482 * Return the URL of the image file
488 if($this->fileExists
) {
489 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
497 function getViewURL() {
498 if( $this->mustRender()) {
499 if( $this->canRender() ) {
500 return $this->createThumb( $this->getWidth() );
503 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
504 return $this->getURL(); #hm... return NULL?
507 return $this->getURL();
512 * Return the image path of the image in the
513 * local file system as an absolute path
516 function getImagePath() {
518 return $this->imagePath
;
522 * Return the width of the image
524 * Returns -1 if the file specified is not a known image type
527 function getWidth() {
533 * Return the height of the image
535 * Returns -1 if the file specified is not a known image type
538 function getHeight() {
540 return $this->height
;
544 * Return the size of the image file, in bytes
553 * Returns the mime type of the file.
555 function getMimeType() {
561 * Return the type of the media in the file.
562 * Use the value returned by this function with the MEDIATYPE_xxx constants.
564 function getMediaType() {
570 * Checks if the file can be presented to the browser as a bitmap.
572 * Currently, this checks if the file is an image format
573 * that can be converted to a format
574 * supported by all browsers (namely GIF, PNG and JPEG),
575 * or if it is an SVG image and SVG conversion is enabled.
577 * @todo remember the result of this check.
579 function canRender() {
580 global $wgUseImageMagick;
582 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
584 $mime= $this->getMimeType();
586 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
588 #if it's SVG, check if there's a converter enabled
589 if ($mime === 'image/svg') {
590 global $wgSVGConverters, $wgSVGConverter;
592 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
593 wfDebug( "Image::canRender: SVG is ready!\n" );
596 wfDebug( "Image::canRender: SVG renderer missing\n" );
600 #image formats available on ALL browsers
601 if ( $mime === 'image/gif'
602 ||
$mime === 'image/png'
603 ||
$mime === 'image/jpeg' ) return true;
605 #image formats that can be converted to the above formats
606 if ($wgUseImageMagick) {
607 #convertable by ImageMagick (there are more...)
608 if ( $mime === 'image/vnd.wap.wbmp'
609 ||
$mime === 'image/x-xbitmap'
610 ||
$mime === 'image/x-xpixmap'
611 #|| $mime === 'image/x-icon' #file may be split into multiple parts
612 ||
$mime === 'image/x-portable-anymap'
613 ||
$mime === 'image/x-portable-bitmap'
614 ||
$mime === 'image/x-portable-graymap'
615 ||
$mime === 'image/x-portable-pixmap'
616 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
617 ||
$mime === 'image/x-rgb'
618 ||
$mime === 'image/x-bmp'
619 ||
$mime === 'image/tiff' ) return true;
622 #convertable by the PHP GD image lib
623 if ( $mime === 'image/vnd.wap.wbmp'
624 ||
$mime === 'image/x-xbitmap' ) return true;
632 * Return true if the file is of a type that can't be directly
633 * rendered by typical browsers and needs to be re-rasterized.
635 * This returns true for everything but the bitmap types
636 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
637 * also return true for any non-image formats.
641 function mustRender() {
642 $mime= $this->getMimeType();
644 if ( $mime === "image/gif"
645 ||
$mime === "image/png"
646 ||
$mime === "image/jpeg" ) return false;
652 * Determines if this media file may be shown inline on a page.
654 * This is currently synonymous to canRender(), but this could be
655 * extended to also allow inline display of other media,
656 * like flash animations or videos. If you do so, please keep in mind that
657 * that could be a security risk.
659 function allowInlineDisplay() {
660 return $this->canRender();
664 * Determines if this media file is in a format that is unlikely to
665 * contain viruses or malicious content. It uses the global
666 * $wgTrustedMediaFormats list to determine if the file is safe.
668 * This is used to show a warning on the description page of non-safe files.
669 * It may also be used to disallow direct [[media:...]] links to such files.
671 * Note that this function will always return true if allowInlineDisplay()
672 * or isTrustedFile() is true for this file.
674 function isSafeFile() {
675 if ($this->allowInlineDisplay()) return true;
676 if ($this->isTrustedFile()) return true;
678 global $wgTrustedMediaFormats;
680 $type= $this->getMediaType();
681 $mime= $this->getMimeType();
682 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
684 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
685 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
687 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
688 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
693 /** Returns true if the file is flagged as trusted. Files flagged that way
694 * can be linked to directly, even if that is not allowed for this type of
697 * This is a dummy function right now and always returns false. It could be
698 * implemented to extract a flag from the database. The trusted flag could be
699 * set on upload, if the user has sufficient privileges, to bypass script-
700 * and html-filters. It may even be coupled with cryptographics signatures
703 function isTrustedFile() {
704 #this could be implemented to check a flag in the databas,
705 #look for signatures, etc
710 * Return the escapeLocalURL of this image
713 function getEscapeLocalURL() {
715 return $this->title
->escapeLocalURL();
719 * Return the escapeFullURL of this image
722 function getEscapeFullURL() {
724 return $this->title
->escapeFullURL();
728 * Return the URL of an image, provided its name.
730 * @param string $name Name of the image, without the leading "Image:"
731 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
732 * @return string URL of $name image
736 function imageUrl( $name, $fromSharedDirectory = false ) {
737 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
738 if($fromSharedDirectory) {
740 $path = $wgSharedUploadPath;
742 $base = $wgUploadBaseUrl;
743 $path = $wgUploadPath;
745 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
746 return wfUrlencode( $url );
750 * Returns true if the image file exists on disk.
751 * @return boolean Whether image file exist on disk.
756 return $this->fileExists
;
763 function thumbUrl( $width, $subdir='thumb') {
764 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
765 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
767 // Generate thumb.php URL if possible
771 if ( $this->fromSharedDirectory
) {
772 if ( $wgSharedThumbnailScriptPath ) {
773 $script = $wgSharedThumbnailScriptPath;
776 if ( $wgThumbnailScriptPath ) {
777 $script = $wgThumbnailScriptPath;
781 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
782 if( $this->mustRender() ) {
786 $name = $this->thumbName( $width );
787 if($this->fromSharedDirectory
) {
789 $path = $wgSharedUploadPath;
791 $base = $wgUploadBaseUrl;
792 $path = $wgUploadPath;
794 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
795 $url = "{$base}{$path}/{$subdir}" .
796 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
797 . $this->name
.'/'.$name;
798 $url = wfUrlencode( $url );
800 $url = "{$base}{$path}/{$subdir}/{$name}";
803 return array( $script !== false, $url );
807 * Return the file name of a thumbnail of the specified width
809 * @param integer $width Width of the thumbnail image
810 * @param boolean $shared Does the thumbnail come from the shared repository?
813 function thumbName( $width ) {
814 $thumb = $width."px-".$this->name
;
816 if( $this->mustRender() ) {
817 if( $this->canRender() ) {
818 # Rasterize to PNG (for SVG vector images, etc)
822 #should we use iconThumb here to get a symbolic thumbnail?
823 #or should we fail with an internal error?
824 return NULL; //can't make bitmap
831 * Create a thumbnail of the image having the specified width/height.
832 * The thumbnail will not be created if the width is larger than the
833 * image's width. Let the browser do the scaling in this case.
834 * The thumbnail is stored on disk and is only computed if the thumbnail
835 * file does not exist OR if it is older than the image.
838 * Keeps aspect ratio of original image. If both width and height are
839 * specified, the generated image will be no bigger than width x height,
840 * and will also have correct aspect ratio.
842 * @param integer $width maximum width of the generated thumbnail
843 * @param integer $height maximum height of the image (optional)
846 function createThumb( $width, $height=-1 ) {
847 $thumb = $this->getThumbnail( $width, $height );
848 if( is_null( $thumb ) ) return '';
849 return $thumb->getUrl();
853 * As createThumb, but returns a ThumbnailImage object. This can
854 * provide access to the actual file, the real size of the thumb,
855 * and can produce a convenient <img> tag for you.
857 * @param integer $width maximum width of the generated thumbnail
858 * @param integer $height maximum height of the image (optional)
859 * @return ThumbnailImage
862 function getThumbnail( $width, $height=-1 ) {
863 if ( $height <= 0 ) {
864 return $this->renderThumb( $width );
868 if ($this->canRender()) {
869 if ( $width > $this->width
* $height / $this->height
)
870 $width = floor( $this->width
* $height / $this->height
);
871 # Note this is the largest width such that the thumbnail's
872 # height is at most $height.
874 $thumb = $this->renderThumb( $width );
876 else $thumb= NULL; #not a bitmap or renderable image, don't try.
878 if( is_null( $thumb ) ) {
879 $thumb = $this->iconThumb();
885 * @return ThumbnailImage
887 function iconThumb() {
888 global $wgStylePath, $wgStyleDirectory;
890 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
891 foreach( $try as $icon ) {
892 $path = '/common/images/icons/' . $icon;
893 $filepath = $wgStyleDirectory . $path;
894 if( file_exists( $filepath ) ) {
895 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
902 * Create a thumbnail of the image having the specified width.
903 * The thumbnail will not be created if the width is larger than the
904 * image's width. Let the browser do the scaling in this case.
905 * The thumbnail is stored on disk and is only computed if the thumbnail
906 * file does not exist OR if it is older than the image.
907 * Returns an object which can return the pathname, URL, and physical
908 * pixel size of the thumbnail -- or null on failure.
910 * @return ThumbnailImage
913 function renderThumb( $width, $useScript = true ) {
914 global $wgUseSquid, $wgInternalServer;
915 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
916 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
918 $fname = 'Image::renderThumb';
919 wfProfileIn( $fname );
921 $width = intval( $width );
924 if ( ! $this->exists() )
926 # If there is no image, there will be no thumbnail
927 wfProfileOut( $fname );
931 # Sanity check $width
932 if( $width <= 0 ||
$this->width
<= 0) {
934 wfProfileOut( $fname );
938 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
939 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
940 # an exception for it.
941 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
942 $this->getMimeType() !== 'image/jpeg' &&
943 $this->width
* $this->height
> $wgMaxImageArea )
945 wfProfileOut( $fname );
949 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
950 if ( $this->mustRender() ) {
951 $width = min( $width, $wgSVGMaxSize );
952 } elseif ( $width > $this->width
- 1 ) {
953 $thumb = new ThumbnailImage( $this->getURL(), $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 ( is_dir( $thumbPath ) ) {
972 // Directory where file should be
973 // This happened occasionally due to broken migration code in 1.5
974 // Rename to broken-*
975 global $wgUploadDirectory;
976 for ( $i = 0; $i < 100 ; $i++
) {
977 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
978 if ( !file_exists( $broken ) ) {
979 rename( $thumbPath, $broken );
983 // Code below will ask if it exists, and the answer is now no
988 if ( !file_exists( $thumbPath ) ||
989 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) ) {
990 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
994 // Migration from old directory structure
995 if ( is_file( $oldThumbPath ) ) {
996 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
997 if ( file_exists( $thumbPath ) ) {
998 if ( !is_dir( $thumbPath ) ) {
999 // Old image in the way of rename
1000 unlink( $thumbPath );
1002 // This should have been dealt with already
1003 wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
1006 // Rename the old image into the new location
1007 rename( $oldThumbPath, $thumbPath );
1010 unlink( $oldThumbPath );
1014 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1015 if ( $this->lastError
=== true ) {
1020 # This has to be done after the image is updated and present for all machines on NFS,
1021 # or else the old version might be stored into the squid again
1022 if ( $wgUseSquid ) {
1023 if ( substr( $url, 0, 4 ) == 'http' ) {
1024 $urlArr = array( $url );
1026 $urlArr = array( $wgInternalServer.$url );
1028 wfPurgeSquidServers($urlArr);
1034 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1038 wfProfileOut( $fname );
1040 } // END OF function renderThumb
1043 * Really render a thumbnail
1044 * Call this only for images for which canRender() returns true.
1046 * @param string $thumbPath Path to thumbnail
1047 * @param int $width Desired width in pixels
1048 * @param int $height Desired height in pixels
1049 * @return bool True on error, false or error string on failure.
1052 function reallyRenderThumb( $thumbPath, $width, $height ) {
1053 global $wgSVGConverters, $wgSVGConverter,
1054 $wgUseImageMagick, $wgImageMagickConvertCommand;
1059 if( $this->mime
=== "image/svg" ) {
1060 #Right now we have only SVG
1062 global $wgSVGConverters, $wgSVGConverter;
1063 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1064 global $wgSVGConverterPath;
1066 array( '$path/', '$width', '$height', '$input', '$output' ),
1067 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1070 wfEscapeShellArg( $this->imagePath
),
1071 wfEscapeShellArg( $thumbPath ) ),
1072 $wgSVGConverters[$wgSVGConverter] );
1073 wfProfileIn( 'rsvg' );
1074 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1075 $err = wfShellExec( $cmd );
1076 wfProfileOut( 'rsvg' );
1078 } elseif ( $wgUseImageMagick ) {
1081 if ( $this->mime
== 'image/jpeg' ) {
1082 $quality = "-quality 80"; // 80%
1083 } elseif ( $this->mime
== 'image/png' ) {
1084 $quality = "-quality 95"; // zlib 9, adaptive filtering
1086 $quality = ''; // default
1089 # Specify white background color, will be used for transparent images
1090 # in Internet Explorer/Windows instead of default black.
1092 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1093 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1094 # the wrong size in the second case.
1096 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1097 " {$quality} -background white -size {$width} ".
1098 wfEscapeShellArg($this->imagePath
) .
1099 // For the -resize option a "!" is needed to force exact size,
1100 // or ImageMagick may decide your ratio is wrong and slice off
1102 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1104 wfEscapeShellArg($thumbPath) . " 2>&1";
1105 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1106 wfProfileIn( 'convert' );
1107 $err = wfShellExec( $cmd );
1108 wfProfileOut( 'convert' );
1110 # Use PHP's builtin GD library functions.
1112 # First find out what kind of file this is, and select the correct
1113 # input routine for this.
1116 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1117 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1118 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1119 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1120 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1122 if( !isset( $typemap[$this->mime
] ) ) {
1123 $err = 'Image type not supported';
1124 wfDebug( "$err\n" );
1127 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1129 if( !function_exists( $loader ) ) {
1130 $err = "Incomplete GD library configuration: missing function $loader";
1131 wfDebug( "$err\n" );
1134 if( $colorStyle == 'palette' ) {
1136 } elseif( $colorStyle == 'truecolor' ) {
1138 } elseif( $colorStyle == 'bits' ) {
1139 $truecolor = ( $this->bits
> 8 );
1142 $src_image = call_user_func( $loader, $this->imagePath
);
1144 $dst_image = imagecreatetruecolor( $width, $height );
1146 $dst_image = imagecreate( $width, $height );
1148 imagecopyresampled( $dst_image, $src_image,
1150 $width, $height, $this->width
, $this->height
);
1151 call_user_func( $saveType, $dst_image, $thumbPath );
1152 imagedestroy( $dst_image );
1153 imagedestroy( $src_image );
1157 # Check for zero-sized thumbnails. Those can be generated when
1158 # no disk space is available or some other error occurs
1160 if( file_exists( $thumbPath ) ) {
1161 $thumbstat = stat( $thumbPath );
1162 if( $thumbstat['size'] == 0 ) {
1163 unlink( $thumbPath );
1169 if ( $err !== true ) {
1170 return wfMsg( 'thumbnail_error', $err );
1176 function getLastError() {
1177 return $this->lastError
;
1180 function imageJpegWrapper( $dst_image, $thumbPath ) {
1181 imageinterlace( $dst_image );
1182 imagejpeg( $dst_image, $thumbPath, 95 );
1186 * Get all thumbnail names previously generated for this image
1188 function getThumbnails( $shared = false ) {
1189 if ( Image
::isHashed( $shared ) ) {
1192 $dir = wfImageThumbDir( $this->name
, $shared );
1194 // This generates an error on failure, hence the @
1195 $handle = @opendir
( $dir );
1198 while ( false !== ( $file = readdir($handle) ) ) {
1199 if ( $file{0} != '.' ) {
1203 closedir( $handle );
1213 * Refresh metadata in memcached, but don't touch thumbnails or squid
1215 function purgeMetadataCache() {
1217 $this->loadFromFile();
1218 $this->saveToCache();
1222 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1224 function purgeCache( $archiveFiles = array(), $shared = false ) {
1225 global $wgInternalServer, $wgUseSquid;
1227 // Refresh metadata cache
1228 $this->purgeMetadataCache();
1230 // Delete thumbnails
1231 $files = $this->getThumbnails( $shared );
1232 $dir = wfImageThumbDir( $this->name
, $shared );
1234 foreach ( $files as $file ) {
1235 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1236 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1237 @unlink
( "$dir/$file" );
1242 if ( $wgUseSquid ) {
1243 $urls[] = $wgInternalServer . $this->getViewURL();
1244 foreach ( $archiveFiles as $file ) {
1245 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1247 wfPurgeSquidServers( $urls );
1251 function checkDBSchema(&$db) {
1252 global $wgCheckDBSchema;
1253 if (!$wgCheckDBSchema) {
1256 # img_name must be unique
1257 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1258 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1261 #new fields must exist
1262 if ( !$db->fieldExists( 'image', 'img_media_type' )
1263 ||
!$db->fieldExists( 'image', 'img_metadata' )
1264 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1266 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1271 * Return the image history of this image, line by line.
1272 * starts with current version, then old versions.
1273 * uses $this->historyLine to check which line to return:
1274 * 0 return line for current version
1275 * 1 query for old versions, return first one
1276 * 2, ... return next old version from above query
1280 function nextHistoryLine() {
1281 $fname = 'Image::nextHistoryLine()';
1282 $dbr =& wfGetDB( DB_SLAVE
);
1284 $this->checkDBSchema($dbr);
1286 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1287 $this->historyRes
= $dbr->select( 'image',
1291 'img_user','img_user_text',
1295 "'' AS oi_archive_name"
1297 array( 'img_name' => $this->title
->getDBkey() ),
1300 if ( 0 == wfNumRows( $this->historyRes
) ) {
1303 } else if ( $this->historyLine
== 1 ) {
1304 $this->historyRes
= $dbr->select( 'oldimage',
1306 'oi_size AS img_size',
1307 'oi_description AS img_description',
1308 'oi_user AS img_user',
1309 'oi_user_text AS img_user_text',
1310 'oi_timestamp AS img_timestamp',
1311 'oi_width as img_width',
1312 'oi_height as img_height',
1315 array( 'oi_name' => $this->title
->getDBkey() ),
1317 array( 'ORDER BY' => 'oi_timestamp DESC' )
1320 $this->historyLine ++
;
1322 return $dbr->fetchObject( $this->historyRes
);
1326 * Reset the history pointer to the first element of the history
1329 function resetHistory() {
1330 $this->historyLine
= 0;
1334 * Return the full filesystem path to the file. Note that this does
1335 * not mean that a file actually exists under that location.
1337 * This path depends on whether directory hashing is active or not,
1338 * i.e. whether the images are all found in the same directory,
1339 * or in hashed paths like /images/3/3c.
1342 * @param boolean $fromSharedDirectory Return the path to the file
1343 * in a shared repository (see $wgUseSharedRepository and related
1344 * options in DefaultSettings.php) instead of a local one.
1347 function getFullPath( $fromSharedRepository = false ) {
1348 global $wgUploadDirectory, $wgSharedUploadDirectory;
1350 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1353 // $wgSharedUploadDirectory may be false, if thumb.php is used
1355 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1367 function isHashed( $shared ) {
1368 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1369 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1373 * Record an image upload in the upload log and the image table
1375 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1376 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1378 $fname = 'Image::recordUpload';
1379 $dbw =& wfGetDB( DB_MASTER
);
1381 $this->checkDBSchema($dbw);
1383 // Delete thumbnails and refresh the metadata cache
1384 $this->purgeCache();
1386 // Fail now if the image isn't there
1387 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1388 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1392 if ( $wgUseCopyrightUpload ) {
1393 if ( $license != '' ) {
1394 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1396 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1397 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1399 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1401 if ( $license != '' ) {
1402 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1403 $textdesc = $filedesc .
1404 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1410 $now = $dbw->timestamp();
1413 if (strpos($this->mime
,'/')!==false) {
1414 list($major,$minor)= explode('/',$this->mime
,2);
1417 $major= $this->mime
;
1421 # Test to see if the row exists using INSERT IGNORE
1422 # This avoids race conditions by locking the row until the commit, and also
1423 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1424 $dbw->insert( 'image',
1426 'img_name' => $this->name
,
1427 'img_size'=> $this->size
,
1428 'img_width' => intval( $this->width
),
1429 'img_height' => intval( $this->height
),
1430 'img_bits' => $this->bits
,
1431 'img_media_type' => $this->type
,
1432 'img_major_mime' => $major,
1433 'img_minor_mime' => $minor,
1434 'img_timestamp' => $now,
1435 'img_description' => $desc,
1436 'img_user' => $wgUser->getID(),
1437 'img_user_text' => $wgUser->getName(),
1438 'img_metadata' => $this->metadata
,
1443 $descTitle = $this->getTitle();
1444 $purgeURLs = array();
1446 if( $dbw->affectedRows() == 0 ) {
1447 # Collision, this is an update of an image
1448 # Insert previous contents into oldimage
1449 $dbw->insertSelect( 'oldimage', 'image',
1451 'oi_name' => 'img_name',
1452 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1453 'oi_size' => 'img_size',
1454 'oi_width' => 'img_width',
1455 'oi_height' => 'img_height',
1456 'oi_bits' => 'img_bits',
1457 'oi_timestamp' => 'img_timestamp',
1458 'oi_description' => 'img_description',
1459 'oi_user' => 'img_user',
1460 'oi_user_text' => 'img_user_text',
1461 ), array( 'img_name' => $this->name
), $fname
1464 # Update the current image row
1465 $dbw->update( 'image',
1467 'img_size' => $this->size
,
1468 'img_width' => intval( $this->width
),
1469 'img_height' => intval( $this->height
),
1470 'img_bits' => $this->bits
,
1471 'img_media_type' => $this->type
,
1472 'img_major_mime' => $major,
1473 'img_minor_mime' => $minor,
1474 'img_timestamp' => $now,
1475 'img_description' => $desc,
1476 'img_user' => $wgUser->getID(),
1477 'img_user_text' => $wgUser->getName(),
1478 'img_metadata' => $this->metadata
,
1479 ), array( /* WHERE */
1480 'img_name' => $this->name
1485 $article = new Article( $descTitle );
1487 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1488 $suppressRC = true; // There's already a log entry, so don't double the RC load
1490 if( $descTitle->exists() ) {
1491 // TODO: insert a null revision into the page history for this update.
1493 $wgUser->addWatch( $descTitle );
1496 # Invalidate the cache for the description page
1497 $descTitle->invalidateCache();
1498 $purgeURLs[] = $descTitle->getInternalURL();
1500 // New image; create the description page.
1501 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1504 # Invalidate cache for all pages using this image
1505 $linksTo = $this->getLinksTo();
1507 if ( $wgUseSquid ) {
1508 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1509 array_push( $wgPostCommitUpdateList, $u );
1511 Title
::touchArray( $linksTo );
1513 $log = new LogPage( 'upload' );
1514 $log->addEntry( 'upload', $descTitle, $desc );
1520 * Get an array of Title objects which are articles which use this image
1521 * Also adds their IDs to the link cache
1523 * This is mostly copied from Title::getLinksTo()
1525 function getLinksTo( $options = '' ) {
1526 $fname = 'Image::getLinksTo';
1527 wfProfileIn( $fname );
1530 $db =& wfGetDB( DB_MASTER
);
1532 $db =& wfGetDB( DB_SLAVE
);
1534 $linkCache =& LinkCache
::singleton();
1536 extract( $db->tableNames( 'page', 'imagelinks' ) );
1537 $encName = $db->addQuotes( $this->name
);
1538 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1539 $res = $db->query( $sql, $fname );
1542 if ( $db->numRows( $res ) ) {
1543 while ( $row = $db->fetchObject( $res ) ) {
1544 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1545 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1546 $retVal[] = $titleObj;
1550 $db->freeResult( $res );
1551 wfProfileOut( $fname );
1555 * Retrive Exif data from the database
1557 * Retrive Exif data from the database and prune unrecognized tags
1558 * and/or tags with invalid contents
1562 function retrieveExifData() {
1563 if ( $this->getMimeType() !== "image/jpeg" )
1566 $exif = new Exif( $this->imagePath
);
1567 return $exif->getFilteredData();
1570 function getExifData() {
1572 if ( $this->metadata
=== '0' )
1575 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1576 $ret = unserialize( $this->metadata
);
1578 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1579 $newver = Exif
::version();
1581 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1582 $this->purgeMetadataCache();
1583 $this->updateExifData( $newver );
1585 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1586 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1587 $format = new FormatExif( $ret );
1589 return $format->getFormattedData();
1592 function updateExifData( $version ) {
1593 $fname = 'Image:updateExifData';
1595 if ( $this->getImagePath() === false ) # Not a local image
1598 # Get EXIF data from image
1599 $exif = $this->retrieveExifData();
1600 if ( count( $exif ) ) {
1601 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1602 $this->metadata
= serialize( $exif );
1604 $this->metadata
= '0';
1607 # Update EXIF data in database
1608 $dbw =& wfGetDB( DB_MASTER
);
1610 $this->checkDBSchema($dbw);
1612 $dbw->update( 'image',
1613 array( 'img_metadata' => $this->metadata
),
1614 array( 'img_name' => $this->name
),
1620 * Returns true if the image does not come from the shared
1625 function isLocal() {
1626 return !$this->fromSharedDirectory
;
1633 * Returns the image directory of an image
1634 * If the directory does not exist, it is created.
1635 * The result is an absolute path.
1637 * This function is called from thumb.php before Setup.php is included
1639 * @param string $fname file name of the image file
1642 function wfImageDir( $fname ) {
1643 global $wgUploadDirectory, $wgHashedUploadDirectory;
1645 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1647 $hash = md5( $fname );
1648 $oldumask = umask(0);
1649 $dest = $wgUploadDirectory . '/' . $hash{0};
1650 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1651 $dest .= '/' . substr( $hash, 0, 2 );
1652 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1659 * Returns the image directory of an image's thubnail
1660 * If the directory does not exist, it is created.
1661 * The result is an absolute path.
1663 * This function is called from thumb.php before Setup.php is included
1665 * @param string $fname file name of the original image file
1666 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1667 * @param boolean $shared (optional) use the shared upload directory
1670 function wfImageThumbDir( $fname, $shared = false ) {
1671 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1672 if ( Image
::isHashed( $shared ) ) {
1673 $dir = "$base/$fname";
1675 if ( !is_dir( $base ) ) {
1676 $oldumask = umask(0);
1677 @mkdir
( $base, 0777 );
1681 if ( ! is_dir( $dir ) ) {
1682 if ( is_file( $dir ) ) {
1683 // Old thumbnail in the way of directory creation, kill it
1686 $oldumask = umask(0);
1687 @mkdir
( $dir, 0777 );
1698 * Old thumbnail directory, kept for conversion
1700 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1701 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1705 * Returns the image directory of an image's old version
1706 * If the directory does not exist, it is created.
1707 * The result is an absolute path.
1709 * This function is called from thumb.php before Setup.php is included
1711 * @param string $fname file name of the thumbnail file, including file size prefix
1712 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1713 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1716 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1717 global $wgUploadDirectory, $wgHashedUploadDirectory,
1718 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1719 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1720 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1721 if (!$hashdir) { return $dir.'/'.$subdir; }
1722 $hash = md5( $fname );
1723 $oldumask = umask(0);
1725 # Suppress warning messages here; if the file itself can't
1726 # be written we'll worry about it then.
1727 wfSuppressWarnings();
1729 $archive = $dir.'/'.$subdir;
1730 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1731 $archive .= '/' . $hash{0};
1732 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1733 $archive .= '/' . substr( $hash, 0, 2 );
1734 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1736 wfRestoreWarnings();
1743 * Return the hash path component of an image path (URL or filesystem),
1744 * e.g. "/3/3c/", or just "/" if hashing is not used.
1746 * @param $dbkey The filesystem / database name of the file
1747 * @param $fromSharedDirectory Use the shared file repository? It may
1748 * use different hash settings from the local one.
1750 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1751 if( Image
::isHashed( $fromSharedDirectory ) ) {
1752 $hash = md5($dbkey);
1753 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1760 * Returns the image URL of an image's old version
1762 * @param string $fname file name of the image file
1763 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1766 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1767 global $wgUploadPath, $wgHashedUploadDirectory;
1769 if ($wgHashedUploadDirectory) {
1770 $hash = md5( substr( $name, 15) );
1771 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1772 substr( $hash, 0, 2 ) . '/'.$name;
1774 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1776 return wfUrlencode($url);
1780 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1781 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1783 * @param string $length
1784 * @return int Length in pixels
1786 function wfScaleSVGUnit( $length ) {
1787 static $unitLength = array(
1794 '' => 1.0, // "User units" pixels by default
1795 '%' => 2.0, // Fake it!
1797 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1798 $length = floatval( $matches[1] );
1799 $unit = $matches[2];
1800 return round( $length * $unitLength[$unit] );
1803 return round( floatval( $length ) );
1808 * Compatible with PHP getimagesize()
1809 * @todo support gzipped SVGZ
1810 * @todo check XML more carefully
1811 * @todo sensible defaults
1813 * @param string $filename
1816 function wfGetSVGsize( $filename ) {
1820 // Read a chunk of the file
1821 $f = fopen( $filename, "rt" );
1822 if( !$f ) return false;
1823 $chunk = fread( $f, 4096 );
1826 // Uber-crappy hack! Run through a real XML parser.
1827 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1831 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1832 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1834 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1835 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1838 return array( $width, $height, 'SVG',
1839 "width=\"$width\" height=\"$height\"" );
1843 * Determine if an image exists on the 'bad image list'
1845 * @param string $name The image to check
1848 function wfIsBadImage( $name ) {
1850 static $titleList = false;
1851 if ( $titleList === false ) {
1852 $titleList = array();
1854 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1855 foreach ( $lines as $line ) {
1856 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1857 $t = Title
::newFromText( $m[1] );
1858 $titleList[$t->getDBkey()] = 1;
1863 return array_key_exists( $name, $titleList );
1869 * Wrapper class for thumbnail images
1870 * @package MediaWiki
1872 class ThumbnailImage
{
1874 * @param string $path Filesystem path to the thumb
1875 * @param string $url URL path to the thumb
1878 function ThumbnailImage( $url, $width, $height, $path = false ) {
1880 $this->width
= round( $width );
1881 $this->height
= round( $height );
1882 # These should be integers when they get here.
1883 # If not, there's a bug somewhere. But let's at
1884 # least produce valid HTML code regardless.
1885 $this->path
= $path;
1889 * @return string The thumbnail URL
1896 * Return HTML <img ... /> tag for the thumbnail, will include
1897 * width and height attributes and a blank alt text (as required).
1899 * You can set or override additional attributes by passing an
1900 * associative array of name => data pairs. The data will be escaped
1901 * for HTML output, so should be in plaintext.
1903 * @param array $attribs
1907 function toHtml( $attribs = array() ) {
1908 $attribs['src'] = $this->url
;
1909 $attribs['width'] = $this->width
;
1910 $attribs['height'] = $this->height
;
1911 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1914 foreach( $attribs as $name => $data ) {
1915 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';