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( ) {
99 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
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, $wgShowEXIF;
215 $fname = 'Image::loadFromFile';
216 wfProfileIn( $fname );
217 $this->imagePath
= $this->getFullPath();
218 $this->fileExists
= file_exists( $this->imagePath
);
219 $this->fromSharedDirectory
= false;
222 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
224 # If the file is not found, and a shared upload directory is used, look for it there.
225 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
226 # In case we're on a wgCapitalLinks=false wiki, we
227 # capitalize the first letter of the filename before
228 # looking it up in the shared repository.
229 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
230 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
231 if ( $this->fileExists
) {
232 $this->name
= $sharedImage->name
;
233 $this->imagePath
= $this->getFullPath(true);
234 $this->fromSharedDirectory
= true;
239 if ( $this->fileExists
) {
240 $magic=& wfGetMimeMagic();
242 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
243 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
246 $this->size
= filesize( $this->imagePath
);
248 $magic=& wfGetMimeMagic();
251 if( $this->mime
== 'image/svg' ) {
252 wfSuppressWarnings();
253 $gis = wfGetSVGsize( $this->imagePath
);
256 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
257 # Don't try to get the width and height of sound and video files, that's bad for performance
260 $gis[2]= 0; //unknown
261 $gis[3]= ""; //width height string
264 wfSuppressWarnings();
265 $gis = getimagesize( $this->imagePath
);
269 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
274 $gis[2]= 0; //unknown
275 $gis[3]= ""; //width height string
278 $this->type
= MEDIATYPE_UNKNOWN
;
279 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
282 $this->width
= $gis[0];
283 $this->height
= $gis[1];
285 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
287 #NOTE: we have to set this flag early to avoid load() to be called
288 # be some of the functions below. This may lead to recursion or other bad things!
289 # as ther's only one thread of execution, this should be safe anyway.
290 $this->dataLoaded
= true;
293 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
294 else $this->metadata
= serialize ( array() ) ;
296 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
297 else $this->bits
= 0;
299 wfProfileOut( $fname );
303 * Load image metadata from the DB
305 function loadFromDB() {
306 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
307 $fname = 'Image::loadFromDB';
308 wfProfileIn( $fname );
310 $dbr =& wfGetDB( DB_SLAVE
);
312 $this->checkDBSchema($dbr);
314 $row = $dbr->selectRow( 'image',
315 array( 'img_size', 'img_width', 'img_height', 'img_bits',
316 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
317 array( 'img_name' => $this->name
), $fname );
319 $this->fromSharedDirectory
= false;
320 $this->fileExists
= true;
321 $this->loadFromRow( $row );
322 $this->imagePath
= $this->getFullPath();
323 // Check for rows from a previous schema, quietly upgrade them
324 if ( is_null($this->type
) ) {
327 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
328 # In case we're on a wgCapitalLinks=false wiki, we
329 # capitalize the first letter of the filename before
330 # looking it up in the shared repository.
331 $name = $wgContLang->ucfirst($this->name
);
332 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
334 $row = $dbc->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();
423 if ( $this->fromSharedDirectory
) {
424 if ( !$wgSharedUploadDBname ) {
425 wfProfileOut( $fname );
429 // Write to the other DB using selectDB, not database selectors
430 // This avoids breaking replication in MySQL
431 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
432 $dbw->selectDB( $wgSharedUploadDBname );
434 $dbw =& wfGetDB( DB_MASTER
);
437 $this->checkDBSchema($dbw);
439 if (strpos($this->mime
,'/')!==false) {
440 list($major,$minor)= explode('/',$this->mime
,2);
447 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
449 $dbw->update( 'image',
451 'img_width' => $this->width
,
452 'img_height' => $this->height
,
453 'img_bits' => $this->bits
,
454 'img_media_type' => $this->type
,
455 'img_major_mime' => $major,
456 'img_minor_mime' => $minor,
457 'img_metadata' => $this->metadata
,
458 ), array( 'img_name' => $this->name
), $fname
460 if ( $this->fromSharedDirectory
) {
461 $dbw->selectDB( $wgDBname );
463 wfProfileOut( $fname );
467 * Return the name of this image
475 * Return the associated title object
478 function getTitle() {
483 * Return the URL of the image file
489 if($this->fileExists
) {
490 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
498 function getViewURL() {
499 if( $this->mustRender()) {
500 if( $this->canRender() ) {
501 return $this->createThumb( $this->getWidth() );
504 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
505 return $this->getURL(); #hm... return NULL?
508 return $this->getURL();
513 * Return the image path of the image in the
514 * local file system as an absolute path
517 function getImagePath() {
519 return $this->imagePath
;
523 * Return the width of the image
525 * Returns -1 if the file specified is not a known image type
528 function getWidth() {
534 * Return the height of the image
536 * Returns -1 if the file specified is not a known image type
539 function getHeight() {
541 return $this->height
;
545 * Return the size of the image file, in bytes
554 * Returns the mime type of the file.
556 function getMimeType() {
562 * Return the type of the media in the file.
563 * Use the value returned by this function with the MEDIATYPE_xxx constants.
565 function getMediaType() {
571 * Checks if the file can be presented to the browser as a bitmap.
573 * Currently, this checks if the file is an image format
574 * that can be converted to a format
575 * supported by all browsers (namely GIF, PNG and JPEG),
576 * or if it is an SVG image and SVG conversion is enabled.
578 * @todo remember the result of this check.
580 function canRender() {
581 global $wgUseImageMagick;
583 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
585 $mime= $this->getMimeType();
587 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
589 #if it's SVG, check if there's a converter enabled
590 if ($mime === 'image/svg') {
591 global $wgSVGConverters, $wgSVGConverter;
593 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
594 wfDebug( "Image::canRender: SVG is ready!\n" );
597 wfDebug( "Image::canRender: SVG renderer missing\n" );
601 #image formats available on ALL browsers
602 if ( $mime === 'image/gif'
603 ||
$mime === 'image/png'
604 ||
$mime === 'image/jpeg' ) return true;
606 #image formats that can be converted to the above formats
607 if ($wgUseImageMagick) {
608 #convertable by ImageMagick (there are more...)
609 if ( $mime === 'image/vnd.wap.wbmp'
610 ||
$mime === 'image/x-xbitmap'
611 ||
$mime === 'image/x-xpixmap'
612 #|| $mime === 'image/x-icon' #file may be split into multiple parts
613 ||
$mime === 'image/x-portable-anymap'
614 ||
$mime === 'image/x-portable-bitmap'
615 ||
$mime === 'image/x-portable-graymap'
616 ||
$mime === 'image/x-portable-pixmap'
617 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
618 ||
$mime === 'image/x-rgb'
619 ||
$mime === 'image/x-bmp'
620 ||
$mime === 'image/tiff' ) return true;
623 #convertable by the PHP GD image lib
624 if ( $mime === 'image/vnd.wap.wbmp'
625 ||
$mime === 'image/x-xbitmap' ) return true;
633 * Return true if the file is of a type that can't be directly
634 * rendered by typical browsers and needs to be re-rasterized.
636 * This returns true for everything but the bitmap types
637 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
638 * also return true for any non-image formats.
642 function mustRender() {
643 $mime= $this->getMimeType();
645 if ( $mime === "image/gif"
646 ||
$mime === "image/png"
647 ||
$mime === "image/jpeg" ) return false;
653 * Determines if this media file may be shown inline on a page.
655 * This is currently synonymous to canRender(), but this could be
656 * extended to also allow inline display of other media,
657 * like flash animations or videos. If you do so, please keep in mind that
658 * that could be a security risk.
660 function allowInlineDisplay() {
661 return $this->canRender();
665 * Determines if this media file is in a format that is unlikely to
666 * contain viruses or malicious content. It uses the global
667 * $wgTrustedMediaFormats list to determine if the file is safe.
669 * This is used to show a warning on the description page of non-safe files.
670 * It may also be used to disallow direct [[media:...]] links to such files.
672 * Note that this function will always return true if allowInlineDisplay()
673 * or isTrustedFile() is true for this file.
675 function isSafeFile() {
676 if ($this->allowInlineDisplay()) return true;
677 if ($this->isTrustedFile()) return true;
679 global $wgTrustedMediaFormats;
681 $type= $this->getMediaType();
682 $mime= $this->getMimeType();
683 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
685 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
686 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
688 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
689 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
694 /** Returns true if the file is flagged as trusted. Files flagged that way
695 * can be linked to directly, even if that is not allowed for this type of
698 * This is a dummy function right now and always returns false. It could be
699 * implemented to extract a flag from the database. The trusted flag could be
700 * set on upload, if the user has sufficient privileges, to bypass script-
701 * and html-filters. It may even be coupled with cryptographics signatures
704 function isTrustedFile() {
705 #this could be implemented to check a flag in the databas,
706 #look for signatures, etc
711 * Return the escapeLocalURL of this image
714 function getEscapeLocalURL() {
716 return $this->title
->escapeLocalURL();
720 * Return the escapeFullURL of this image
723 function getEscapeFullURL() {
725 return $this->title
->escapeFullURL();
729 * Return the URL of an image, provided its name.
731 * @param string $name Name of the image, without the leading "Image:"
732 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
733 * @return string URL of $name image
737 function imageUrl( $name, $fromSharedDirectory = false ) {
738 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
739 if($fromSharedDirectory) {
741 $path = $wgSharedUploadPath;
743 $base = $wgUploadBaseUrl;
744 $path = $wgUploadPath;
746 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
747 return wfUrlencode( $url );
751 * Returns true if the image file exists on disk.
752 * @return boolean Whether image file exist on disk.
757 return $this->fileExists
;
764 function thumbUrl( $width, $subdir='thumb') {
765 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
766 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
768 // Generate thumb.php URL if possible
772 if ( $this->fromSharedDirectory
) {
773 if ( $wgSharedThumbnailScriptPath ) {
774 $script = $wgSharedThumbnailScriptPath;
777 if ( $wgThumbnailScriptPath ) {
778 $script = $wgThumbnailScriptPath;
782 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
783 if( $this->mustRender() ) {
787 $name = $this->thumbName( $width );
788 if($this->fromSharedDirectory
) {
790 $path = $wgSharedUploadPath;
792 $base = $wgUploadBaseUrl;
793 $path = $wgUploadPath;
795 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
796 $url = "{$base}{$path}/{$subdir}" .
797 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
798 . $this->name
.'/'.$name;
799 $url = wfUrlencode( $url );
801 $url = "{$base}{$path}/{$subdir}/{$name}";
804 return array( $script !== false, $url );
808 * Return the file name of a thumbnail of the specified width
810 * @param integer $width Width of the thumbnail image
811 * @param boolean $shared Does the thumbnail come from the shared repository?
814 function thumbName( $width ) {
815 $thumb = $width."px-".$this->name
;
817 if( $this->mustRender() ) {
818 if( $this->canRender() ) {
819 # Rasterize to PNG (for SVG vector images, etc)
823 #should we use iconThumb here to get a symbolic thumbnail?
824 #or should we fail with an internal error?
825 return NULL; //can't make bitmap
832 * Create a thumbnail of the image having the specified width/height.
833 * The thumbnail will not be created if the width is larger than the
834 * image's width. Let the browser do the scaling in this case.
835 * The thumbnail is stored on disk and is only computed if the thumbnail
836 * file does not exist OR if it is older than the image.
839 * Keeps aspect ratio of original image. If both width and height are
840 * specified, the generated image will be no bigger than width x height,
841 * and will also have correct aspect ratio.
843 * @param integer $width maximum width of the generated thumbnail
844 * @param integer $height maximum height of the image (optional)
847 function createThumb( $width, $height=-1 ) {
848 $thumb = $this->getThumbnail( $width, $height );
849 if( is_null( $thumb ) ) return '';
850 return $thumb->getUrl();
854 * As createThumb, but returns a ThumbnailImage object. This can
855 * provide access to the actual file, the real size of the thumb,
856 * and can produce a convenient <img> tag for you.
858 * @param integer $width maximum width of the generated thumbnail
859 * @param integer $height maximum height of the image (optional)
860 * @return ThumbnailImage
863 function getThumbnail( $width, $height=-1 ) {
864 if ( $height <= 0 ) {
865 return $this->renderThumb( $width );
869 if ($this->canRender()) {
870 if ( $width > $this->width
* $height / $this->height
)
871 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
872 $thumb = $this->renderThumb( $width );
874 else $thumb= NULL; #not a bitmap or renderable image, don't try.
876 if( is_null( $thumb ) ) {
877 $thumb = $this->iconThumb();
883 * @return ThumbnailImage
885 function iconThumb() {
886 global $wgStylePath, $wgStyleDirectory;
888 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
889 foreach( $try as $icon ) {
890 $path = '/common/images/icons/' . $icon;
891 $filepath = $wgStyleDirectory . $path;
892 if( file_exists( $filepath ) ) {
893 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
900 * Create a thumbnail of the image having the specified width.
901 * The thumbnail will not be created if the width is larger than the
902 * image's width. Let the browser do the scaling in this case.
903 * The thumbnail is stored on disk and is only computed if the thumbnail
904 * file does not exist OR if it is older than the image.
905 * Returns an object which can return the pathname, URL, and physical
906 * pixel size of the thumbnail -- or null on failure.
908 * @return ThumbnailImage
911 function renderThumb( $width, $useScript = true ) {
913 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
915 $fname = 'Image::renderThumb';
916 wfProfileIn( $fname );
918 $width = intval( $width );
921 if ( ! $this->exists() )
923 # If there is no image, there will be no thumbnail
924 wfProfileOut( $fname );
928 # Sanity check $width
929 if( $width <= 0 ||
$this->width
<= 0) {
931 wfProfileOut( $fname );
935 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
936 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
937 # an exception for it.
938 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
939 $this->getMimeType() !== 'image/jpeg' &&
940 $this->width
* $this->height
> $wgMaxImageArea )
942 wfProfileOut( $fname );
946 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
947 if ( $this->mustRender() ) {
948 $width = min( $width, $wgSVGMaxSize );
949 } elseif ( $width > $this->width
- 1 ) {
950 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
951 wfProfileOut( $fname );
955 $height = round( $this->height
* $width / $this->width
);
957 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
958 if ( $isScriptUrl && $useScript ) {
959 // Use thumb.php to render the image
960 $thumb = new ThumbnailImage( $url, $width, $height );
961 wfProfileOut( $fname );
965 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
966 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
968 if ( is_dir( $thumbPath ) ) {
969 // Directory where file should be
970 // This happened occasionally due to broken migration code in 1.5
971 // Rename to broken-*
972 global $wgUploadDirectory;
973 for ( $i = 0; $i < 100 ; $i++
) {
974 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
975 if ( !file_exists( $broken ) ) {
976 rename( $thumbPath, $broken );
980 // Code below will ask if it exists, and the answer is now no
985 if ( !file_exists( $thumbPath ) ||
986 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) ) {
987 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
991 // Migration from old directory structure
992 if ( is_file( $oldThumbPath ) ) {
993 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
994 if ( file_exists( $thumbPath ) ) {
995 if ( !is_dir( $thumbPath ) ) {
996 // Old image in the way of rename
997 unlink( $thumbPath );
999 // This should have been dealt with already
1000 wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
1003 // Rename the old image into the new location
1004 rename( $oldThumbPath, $thumbPath );
1007 unlink( $oldThumbPath );
1011 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1012 if ( $this->lastError
=== true ) {
1017 # This has to be done after the image is updated and present for all machines on NFS,
1018 # or else the old version might be stored into the squid again
1019 if ( $wgUseSquid ) {
1020 $urlArr = array( $url );
1021 wfPurgeSquidServers($urlArr);
1027 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1031 wfProfileOut( $fname );
1033 } // END OF function renderThumb
1036 * Really render a thumbnail
1037 * Call this only for images for which canRender() returns true.
1039 * @param string $thumbPath Path to thumbnail
1040 * @param int $width Desired width in pixels
1041 * @param int $height Desired height in pixels
1042 * @return bool True on error, false or error string on failure.
1045 function reallyRenderThumb( $thumbPath, $width, $height ) {
1046 global $wgSVGConverters, $wgSVGConverter;
1047 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1048 global $wgCustomConvertCommand;
1053 if( $this->mime
=== "image/svg" ) {
1054 #Right now we have only SVG
1056 global $wgSVGConverters, $wgSVGConverter;
1057 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1058 global $wgSVGConverterPath;
1060 array( '$path/', '$width', '$height', '$input', '$output' ),
1061 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1064 wfEscapeShellArg( $this->imagePath
),
1065 wfEscapeShellArg( $thumbPath ) ),
1066 $wgSVGConverters[$wgSVGConverter] );
1067 wfProfileIn( 'rsvg' );
1068 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1069 $err = wfShellExec( $cmd );
1070 wfProfileOut( 'rsvg' );
1072 } elseif ( $wgUseImageMagick ) {
1075 if ( $this->mime
== 'image/jpeg' ) {
1076 $quality = "-quality 80"; // 80%
1077 } elseif ( $this->mime
== 'image/png' ) {
1078 $quality = "-quality 95"; // zlib 9, adaptive filtering
1080 $quality = ''; // default
1083 # Specify white background color, will be used for transparent images
1084 # in Internet Explorer/Windows instead of default black.
1086 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1087 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1088 # the wrong size in the second case.
1090 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1091 " {$quality} -background white -size {$width} ".
1092 wfEscapeShellArg($this->imagePath
) .
1093 // For the -resize option a "!" is needed to force exact size,
1094 // or ImageMagick may decide your ratio is wrong and slice off
1096 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1098 wfEscapeShellArg($thumbPath) . " 2>&1";
1099 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1100 wfProfileIn( 'convert' );
1101 $err = wfShellExec( $cmd );
1102 wfProfileOut( 'convert' );
1103 } elseif( $wgCustomConvertCommand ) {
1104 # Use a custom convert command
1105 # Variables: %s %d %w %h
1106 $src = wfEscapeShellArg( $this->imagePath
);
1107 $dst = wfEscapeShellArg( $thumbPath );
1108 $cmd = $wgCustomConvertCommand;
1109 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1110 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1111 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1112 wfProfileIn( 'convert' );
1113 $err = wfShellExec( $cmd );
1114 wfProfileOut( 'convert' );
1116 # Use PHP's builtin GD library functions.
1118 # First find out what kind of file this is, and select the correct
1119 # input routine for this.
1122 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1123 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1124 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1125 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1126 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1128 if( !isset( $typemap[$this->mime
] ) ) {
1129 $err = 'Image type not supported';
1130 wfDebug( "$err\n" );
1133 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1135 if( !function_exists( $loader ) ) {
1136 $err = "Incomplete GD library configuration: missing function $loader";
1137 wfDebug( "$err\n" );
1140 if( $colorStyle == 'palette' ) {
1142 } elseif( $colorStyle == 'truecolor' ) {
1144 } elseif( $colorStyle == 'bits' ) {
1145 $truecolor = ( $this->bits
> 8 );
1148 $src_image = call_user_func( $loader, $this->imagePath
);
1150 $dst_image = imagecreatetruecolor( $width, $height );
1152 $dst_image = imagecreate( $width, $height );
1154 imagecopyresampled( $dst_image, $src_image,
1156 $width, $height, $this->width
, $this->height
);
1157 call_user_func( $saveType, $dst_image, $thumbPath );
1158 imagedestroy( $dst_image );
1159 imagedestroy( $src_image );
1163 # Check for zero-sized thumbnails. Those can be generated when
1164 # no disk space is available or some other error occurs
1166 if( file_exists( $thumbPath ) ) {
1167 $thumbstat = stat( $thumbPath );
1168 if( $thumbstat['size'] == 0 ) {
1169 unlink( $thumbPath );
1175 if ( $err !== true ) {
1176 return wfMsg( 'thumbnail_error', $err );
1182 function getLastError() {
1183 return $this->lastError
;
1186 function imageJpegWrapper( $dst_image, $thumbPath ) {
1187 imageinterlace( $dst_image );
1188 imagejpeg( $dst_image, $thumbPath, 95 );
1192 * Get all thumbnail names previously generated for this image
1194 function getThumbnails( $shared = false ) {
1195 if ( Image
::isHashed( $shared ) ) {
1198 $dir = wfImageThumbDir( $this->name
, $shared );
1200 // This generates an error on failure, hence the @
1201 $handle = @opendir
( $dir );
1204 while ( false !== ( $file = readdir($handle) ) ) {
1205 if ( $file{0} != '.' ) {
1209 closedir( $handle );
1219 * Refresh metadata in memcached, but don't touch thumbnails or squid
1221 function purgeMetadataCache() {
1223 $this->loadFromFile();
1224 $this->saveToCache();
1228 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1230 function purgeCache( $archiveFiles = array(), $shared = false ) {
1233 // Refresh metadata cache
1234 $this->purgeMetadataCache();
1236 // Delete thumbnails
1237 $files = $this->getThumbnails( $shared );
1238 $dir = wfImageThumbDir( $this->name
, $shared );
1240 foreach ( $files as $file ) {
1241 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1242 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1243 @unlink
( "$dir/$file" );
1248 if ( $wgUseSquid ) {
1249 $urls[] = $this->getViewURL();
1250 foreach ( $archiveFiles as $file ) {
1251 $urls[] = wfImageArchiveUrl( $file );
1253 wfPurgeSquidServers( $urls );
1257 function checkDBSchema(&$db) {
1258 global $wgCheckDBSchema;
1259 if (!$wgCheckDBSchema) {
1262 # img_name must be unique
1263 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1264 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1267 #new fields must exist
1268 if ( !$db->fieldExists( 'image', 'img_media_type' )
1269 ||
!$db->fieldExists( 'image', 'img_metadata' )
1270 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1272 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1277 * Return the image history of this image, line by line.
1278 * starts with current version, then old versions.
1279 * uses $this->historyLine to check which line to return:
1280 * 0 return line for current version
1281 * 1 query for old versions, return first one
1282 * 2, ... return next old version from above query
1286 function nextHistoryLine() {
1287 $fname = 'Image::nextHistoryLine()';
1288 $dbr =& wfGetDB( DB_SLAVE
);
1290 $this->checkDBSchema($dbr);
1292 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1293 $this->historyRes
= $dbr->select( 'image',
1297 'img_user','img_user_text',
1301 "'' AS oi_archive_name"
1303 array( 'img_name' => $this->title
->getDBkey() ),
1306 if ( 0 == wfNumRows( $this->historyRes
) ) {
1309 } else if ( $this->historyLine
== 1 ) {
1310 $this->historyRes
= $dbr->select( 'oldimage',
1312 'oi_size AS img_size',
1313 'oi_description AS img_description',
1314 'oi_user AS img_user',
1315 'oi_user_text AS img_user_text',
1316 'oi_timestamp AS img_timestamp',
1317 'oi_width as img_width',
1318 'oi_height as img_height',
1321 array( 'oi_name' => $this->title
->getDBkey() ),
1323 array( 'ORDER BY' => 'oi_timestamp DESC' )
1326 $this->historyLine ++
;
1328 return $dbr->fetchObject( $this->historyRes
);
1332 * Reset the history pointer to the first element of the history
1335 function resetHistory() {
1336 $this->historyLine
= 0;
1340 * Return the full filesystem path to the file. Note that this does
1341 * not mean that a file actually exists under that location.
1343 * This path depends on whether directory hashing is active or not,
1344 * i.e. whether the images are all found in the same directory,
1345 * or in hashed paths like /images/3/3c.
1348 * @param boolean $fromSharedDirectory Return the path to the file
1349 * in a shared repository (see $wgUseSharedRepository and related
1350 * options in DefaultSettings.php) instead of a local one.
1353 function getFullPath( $fromSharedRepository = false ) {
1354 global $wgUploadDirectory, $wgSharedUploadDirectory;
1356 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1359 // $wgSharedUploadDirectory may be false, if thumb.php is used
1361 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1373 function isHashed( $shared ) {
1374 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1375 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1379 * Record an image upload in the upload log and the image table
1381 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1382 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1384 $fname = 'Image::recordUpload';
1385 $dbw =& wfGetDB( DB_MASTER
);
1387 $this->checkDBSchema($dbw);
1389 // Delete thumbnails and refresh the metadata cache
1390 $this->purgeCache();
1392 // Fail now if the image isn't there
1393 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1394 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1398 if ( $wgUseCopyrightUpload ) {
1399 if ( $license != '' ) {
1400 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1402 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1403 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1405 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1407 if ( $license != '' ) {
1408 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1409 $textdesc = $filedesc .
1410 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1416 $now = $dbw->timestamp();
1419 if (strpos($this->mime
,'/')!==false) {
1420 list($major,$minor)= explode('/',$this->mime
,2);
1423 $major= $this->mime
;
1427 # Test to see if the row exists using INSERT IGNORE
1428 # This avoids race conditions by locking the row until the commit, and also
1429 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1430 $dbw->insert( 'image',
1432 'img_name' => $this->name
,
1433 'img_size'=> $this->size
,
1434 'img_width' => intval( $this->width
),
1435 'img_height' => intval( $this->height
),
1436 'img_bits' => $this->bits
,
1437 'img_media_type' => $this->type
,
1438 'img_major_mime' => $major,
1439 'img_minor_mime' => $minor,
1440 'img_timestamp' => $now,
1441 'img_description' => $desc,
1442 'img_user' => $wgUser->getID(),
1443 'img_user_text' => $wgUser->getName(),
1444 'img_metadata' => $this->metadata
,
1449 $descTitle = $this->getTitle();
1450 $purgeURLs = array();
1452 if( $dbw->affectedRows() == 0 ) {
1453 # Collision, this is an update of an image
1454 # Insert previous contents into oldimage
1455 $dbw->insertSelect( 'oldimage', 'image',
1457 'oi_name' => 'img_name',
1458 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1459 'oi_size' => 'img_size',
1460 'oi_width' => 'img_width',
1461 'oi_height' => 'img_height',
1462 'oi_bits' => 'img_bits',
1463 'oi_timestamp' => 'img_timestamp',
1464 'oi_description' => 'img_description',
1465 'oi_user' => 'img_user',
1466 'oi_user_text' => 'img_user_text',
1467 ), array( 'img_name' => $this->name
), $fname
1470 # Update the current image row
1471 $dbw->update( 'image',
1473 'img_size' => $this->size
,
1474 'img_width' => intval( $this->width
),
1475 'img_height' => intval( $this->height
),
1476 'img_bits' => $this->bits
,
1477 'img_media_type' => $this->type
,
1478 'img_major_mime' => $major,
1479 'img_minor_mime' => $minor,
1480 'img_timestamp' => $now,
1481 'img_description' => $desc,
1482 'img_user' => $wgUser->getID(),
1483 'img_user_text' => $wgUser->getName(),
1484 'img_metadata' => $this->metadata
,
1485 ), array( /* WHERE */
1486 'img_name' => $this->name
1490 # This is a new image
1491 # Update the image count
1492 $site_stats = $dbw->tableName( 'site_stats' );
1493 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
1496 $article = new Article( $descTitle );
1498 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1499 $suppressRC = true; // There's already a log entry, so don't double the RC load
1501 if( $descTitle->exists() ) {
1502 // TODO: insert a null revision into the page history for this update.
1504 $wgUser->addWatch( $descTitle );
1507 # Invalidate the cache for the description page
1508 $descTitle->invalidateCache();
1509 $purgeURLs[] = $descTitle->getInternalURL();
1511 // New image; create the description page.
1512 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1515 # Invalidate cache for all pages using this image
1516 $linksTo = $this->getLinksTo();
1518 if ( $wgUseSquid ) {
1519 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1520 array_push( $wgPostCommitUpdateList, $u );
1522 Title
::touchArray( $linksTo );
1524 $log = new LogPage( 'upload' );
1525 $log->addEntry( 'upload', $descTitle, $desc );
1531 * Get an array of Title objects which are articles which use this image
1532 * Also adds their IDs to the link cache
1534 * This is mostly copied from Title::getLinksTo()
1536 function getLinksTo( $options = '' ) {
1537 $fname = 'Image::getLinksTo';
1538 wfProfileIn( $fname );
1541 $db =& wfGetDB( DB_MASTER
);
1543 $db =& wfGetDB( DB_SLAVE
);
1545 $linkCache =& LinkCache
::singleton();
1547 extract( $db->tableNames( 'page', 'imagelinks' ) );
1548 $encName = $db->addQuotes( $this->name
);
1549 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1550 $res = $db->query( $sql, $fname );
1553 if ( $db->numRows( $res ) ) {
1554 while ( $row = $db->fetchObject( $res ) ) {
1555 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1556 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1557 $retVal[] = $titleObj;
1561 $db->freeResult( $res );
1562 wfProfileOut( $fname );
1566 * Retrive Exif data from the database
1568 * Retrive Exif data from the database and prune unrecognized tags
1569 * and/or tags with invalid contents
1573 function retrieveExifData() {
1574 if ( $this->getMimeType() !== "image/jpeg" )
1577 $exif = new Exif( $this->imagePath
);
1578 return $exif->getFilteredData();
1581 function getExifData() {
1583 if ( $this->metadata
=== '0' )
1586 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1587 $ret = unserialize( $this->metadata
);
1589 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1590 $newver = Exif
::version();
1592 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1593 $this->purgeMetadataCache();
1594 $this->updateExifData( $newver );
1596 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1597 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1598 $format = new FormatExif( $ret );
1600 return $format->getFormattedData();
1603 function updateExifData( $version ) {
1604 $fname = 'Image:updateExifData';
1606 if ( $this->getImagePath() === false ) # Not a local image
1609 # Get EXIF data from image
1610 $exif = $this->retrieveExifData();
1611 if ( count( $exif ) ) {
1612 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1613 $this->metadata
= serialize( $exif );
1615 $this->metadata
= '0';
1618 # Update EXIF data in database
1619 $dbw =& wfGetDB( DB_MASTER
);
1621 $this->checkDBSchema($dbw);
1623 $dbw->update( 'image',
1624 array( 'img_metadata' => $this->metadata
),
1625 array( 'img_name' => $this->name
),
1631 * Returns true if the image does not come from the shared
1636 function isLocal() {
1637 return !$this->fromSharedDirectory
;
1641 * Was this image ever deleted from the wiki?
1645 function wasDeleted() {
1646 $dbw =& wfGetDB( DB_MASTER
);
1647 $del = $dbw->selectField( 'archive', 'COUNT(*) AS count', array( 'ar_namespace' => NS_IMAGE
, 'ar_title' => $this->title
->getDBkey() ), 'Image::wasDeleted' );
1655 * Returns the image directory of an image
1656 * If the directory does not exist, it is created.
1657 * The result is an absolute path.
1659 * This function is called from thumb.php before Setup.php is included
1661 * @param $fname String: file name of the image file.
1664 function wfImageDir( $fname ) {
1665 global $wgUploadDirectory, $wgHashedUploadDirectory;
1667 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1669 $hash = md5( $fname );
1670 $oldumask = umask(0);
1671 $dest = $wgUploadDirectory . '/' . $hash{0};
1672 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1673 $dest .= '/' . substr( $hash, 0, 2 );
1674 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1681 * Returns the image directory of an image's thubnail
1682 * If the directory does not exist, it is created.
1683 * The result is an absolute path.
1685 * This function is called from thumb.php before Setup.php is included
1687 * @param $fname String: file name of the original image file
1688 * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
1691 function wfImageThumbDir( $fname, $shared = false ) {
1692 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1693 if ( Image
::isHashed( $shared ) ) {
1694 $dir = "$base/$fname";
1696 if ( !is_dir( $base ) ) {
1697 $oldumask = umask(0);
1698 @mkdir
( $base, 0777 );
1702 if ( ! is_dir( $dir ) ) {
1703 if ( is_file( $dir ) ) {
1704 // Old thumbnail in the way of directory creation, kill it
1707 $oldumask = umask(0);
1708 @mkdir
( $dir, 0777 );
1719 * Old thumbnail directory, kept for conversion
1721 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1722 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1726 * Returns the image directory of an image's old version
1727 * If the directory does not exist, it is created.
1728 * The result is an absolute path.
1730 * This function is called from thumb.php before Setup.php is included
1732 * @param $fname String: file name of the thumbnail file, including file size prefix.
1733 * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
1734 * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
1737 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1738 global $wgUploadDirectory, $wgHashedUploadDirectory;
1739 global $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1740 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1741 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1742 if (!$hashdir) { return $dir.'/'.$subdir; }
1743 $hash = md5( $fname );
1744 $oldumask = umask(0);
1746 # Suppress warning messages here; if the file itself can't
1747 # be written we'll worry about it then.
1748 wfSuppressWarnings();
1750 $archive = $dir.'/'.$subdir;
1751 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1752 $archive .= '/' . $hash{0};
1753 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1754 $archive .= '/' . substr( $hash, 0, 2 );
1755 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1757 wfRestoreWarnings();
1764 * Return the hash path component of an image path (URL or filesystem),
1765 * e.g. "/3/3c/", or just "/" if hashing is not used.
1767 * @param $dbkey The filesystem / database name of the file
1768 * @param $fromSharedDirectory Use the shared file repository? It may
1769 * use different hash settings from the local one.
1771 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1772 if( Image
::isHashed( $fromSharedDirectory ) ) {
1773 $hash = md5($dbkey);
1774 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1781 * Returns the image URL of an image's old version
1783 * @param $name String: file name of the image file
1784 * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1787 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1788 global $wgUploadPath, $wgHashedUploadDirectory;
1790 if ($wgHashedUploadDirectory) {
1791 $hash = md5( substr( $name, 15) );
1792 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1793 substr( $hash, 0, 2 ) . '/'.$name;
1795 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1797 return wfUrlencode($url);
1801 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1802 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1804 * @param $length String: CSS/SVG length.
1805 * @return Integer: length in pixels
1807 function wfScaleSVGUnit( $length ) {
1808 static $unitLength = array(
1815 '' => 1.0, // "User units" pixels by default
1816 '%' => 2.0, // Fake it!
1818 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1819 $length = floatval( $matches[1] );
1820 $unit = $matches[2];
1821 return round( $length * $unitLength[$unit] );
1824 return round( floatval( $length ) );
1829 * Compatible with PHP getimagesize()
1830 * @todo support gzipped SVGZ
1831 * @todo check XML more carefully
1832 * @todo sensible defaults
1834 * @param $filename String: full name of the file (passed to php fopen()).
1837 function wfGetSVGsize( $filename ) {
1841 // Read a chunk of the file
1842 $f = fopen( $filename, "rt" );
1843 if( !$f ) return false;
1844 $chunk = fread( $f, 4096 );
1847 // Uber-crappy hack! Run through a real XML parser.
1848 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1852 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1853 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1855 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1856 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1859 return array( $width, $height, 'SVG',
1860 "width=\"$width\" height=\"$height\"" );
1864 * Determine if an image exists on the 'bad image list'.
1866 * @param $name String: the image name to check
1869 function wfIsBadImage( $name ) {
1870 static $titleList = false;
1873 # Build the list now
1874 $titleList = array();
1875 $lines = explode( "\n", wfMsgForContent( 'bad_image_list' ) );
1876 foreach( $lines as $line ) {
1877 if( preg_match( '/^\*\s*\[\[:?(.*?)\]\]/i', $line, $matches ) ) {
1878 $title = Title
::newFromText( $matches[1] );
1879 if( is_object( $title ) && $title->getNamespace() == NS_IMAGE
)
1880 $titleList[ $title->getDBkey() ] = true;
1884 return array_key_exists( $name, $titleList );
1890 * Wrapper class for thumbnail images
1891 * @package MediaWiki
1893 class ThumbnailImage
{
1895 * @param string $path Filesystem path to the thumb
1896 * @param string $url URL path to the thumb
1899 function ThumbnailImage( $url, $width, $height, $path = false ) {
1901 $this->width
= round( $width );
1902 $this->height
= round( $height );
1903 # These should be integers when they get here.
1904 # If not, there's a bug somewhere. But let's at
1905 # least produce valid HTML code regardless.
1906 $this->path
= $path;
1910 * @return string The thumbnail URL
1917 * Return HTML <img ... /> tag for the thumbnail, will include
1918 * width and height attributes and a blank alt text (as required).
1920 * You can set or override additional attributes by passing an
1921 * associative array of name => data pairs. The data will be escaped
1922 * for HTML output, so should be in plaintext.
1924 * @param array $attribs
1928 function toHtml( $attribs = array() ) {
1929 $attribs['src'] = $this->url
;
1930 $attribs['width'] = $this->width
;
1931 $attribs['height'] = $this->height
;
1932 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1935 foreach( $attribs as $name => $data ) {
1936 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1945 * Calculate the largest thumbnail width for a given original file size
1946 * such that the thumbnail's height is at most $maxHeight.
1947 * @param $boxWidth Integer Width of the thumbnail box.
1948 * @param $boxHeight Integer Height of the thumbnail box.
1949 * @param $maxHeight Integer Maximum height expected for the thumbnail.
1952 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
1953 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
1954 $roundedUp = ceil( $idealWidth );
1955 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
1956 return floor( $idealWidth );