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 * Bump this number when serialized cache records may be incompatible.
18 define( 'MW_IMAGE_VERSION', 1 );
21 * Class to represent an image
23 * Provides methods to retrieve paths (physical, logical, URL),
24 * to generate thumbnails or for uploading.
32 var $name, # name of the image (constructor)
33 $imagePath, # Path of the image (loadFromXxx)
34 $url, # Image URL (accessor)
35 $title, # Title object for this image (constructor)
36 $fileExists, # does the image file exist on disk? (loadFromXxx)
37 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
38 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
39 $historyRes, # result of the query for the image's history (nextHistoryLine)
42 $bits, # --- returned by getimagesize (loadFromXxx)
44 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
45 $mime, # MIME type, determined by MimeMagic::guessMimeType
46 $size, # Size in bytes (loadFromXxx)
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $lastError; # Error string associated with a thumbnail display error
55 * Create an Image object from an image name
57 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
60 function newFromName( $name ) {
61 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
62 if ( is_object( $title ) ) {
63 return new Image( $title );
70 * Obsolete factory function, use constructor
72 function newFromTitle( $title ) {
73 return new Image( $title );
76 function Image( $title ) {
77 if( !is_object( $title ) ) {
78 throw new MWException( 'Image constructor given bogus title.' );
80 $this->title
=& $title;
81 $this->name
= $title->getDBkey();
82 $this->metadata
= serialize ( array() ) ;
84 $n = strrpos( $this->name
, '.' );
85 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
86 $this->historyLine
= 0;
88 $this->dataLoaded
= false;
92 * Get the memcached keys
93 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
95 function getCacheKeys( ) {
96 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
98 $hashedName = md5($this->name
);
99 $keys = array( "$wgDBname:Image:$hashedName" );
100 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
101 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
107 * Try to load image metadata from memcached. Returns true on success.
109 function loadFromCache() {
110 global $wgUseSharedUploads, $wgMemc;
111 $fname = 'Image::loadFromMemcached';
112 wfProfileIn( $fname );
113 $this->dataLoaded
= false;
114 $keys = $this->getCacheKeys();
115 $cachedValues = $wgMemc->get( $keys[0] );
117 // Check if the key existed and belongs to this version of MediaWiki
118 if (!empty($cachedValues) && is_array($cachedValues)
119 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
120 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
122 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
123 # if this is shared file, we need to check if image
124 # in shared repository has not changed
125 if ( isset( $keys[1] ) ) {
126 $commonsCachedValues = $wgMemc->get( $keys[1] );
127 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
128 && isset($commonsCachedValues['version'])
129 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
130 && isset($commonsCachedValues['mime'])) {
131 wfDebug( "Pulling image metadata from shared repository cache\n" );
132 $this->name
= $commonsCachedValues['name'];
133 $this->imagePath
= $commonsCachedValues['imagePath'];
134 $this->fileExists
= $commonsCachedValues['fileExists'];
135 $this->width
= $commonsCachedValues['width'];
136 $this->height
= $commonsCachedValues['height'];
137 $this->bits
= $commonsCachedValues['bits'];
138 $this->type
= $commonsCachedValues['type'];
139 $this->mime
= $commonsCachedValues['mime'];
140 $this->metadata
= $commonsCachedValues['metadata'];
141 $this->size
= $commonsCachedValues['size'];
142 $this->fromSharedDirectory
= true;
143 $this->dataLoaded
= true;
144 $this->imagePath
= $this->getFullPath(true);
148 wfDebug( "Pulling image metadata from local cache\n" );
149 $this->name
= $cachedValues['name'];
150 $this->imagePath
= $cachedValues['imagePath'];
151 $this->fileExists
= $cachedValues['fileExists'];
152 $this->width
= $cachedValues['width'];
153 $this->height
= $cachedValues['height'];
154 $this->bits
= $cachedValues['bits'];
155 $this->type
= $cachedValues['type'];
156 $this->mime
= $cachedValues['mime'];
157 $this->metadata
= $cachedValues['metadata'];
158 $this->size
= $cachedValues['size'];
159 $this->fromSharedDirectory
= false;
160 $this->dataLoaded
= true;
161 $this->imagePath
= $this->getFullPath();
164 if ( $this->dataLoaded
) {
165 wfIncrStats( 'image_cache_hit' );
167 wfIncrStats( 'image_cache_miss' );
170 wfProfileOut( $fname );
171 return $this->dataLoaded
;
175 * Save the image metadata to memcached
177 function saveToCache() {
180 $keys = $this->getCacheKeys();
181 if ( $this->fileExists
) {
182 // We can't cache negative metadata for non-existent files,
183 // because if the file later appears in commons, the local
184 // keys won't be purged.
185 $cachedValues = array(
186 'version' => MW_IMAGE_VERSION
,
187 'name' => $this->name
,
188 'imagePath' => $this->imagePath
,
189 'fileExists' => $this->fileExists
,
190 'fromShared' => $this->fromSharedDirectory
,
191 'width' => $this->width
,
192 'height' => $this->height
,
193 'bits' => $this->bits
,
194 'type' => $this->type
,
195 'mime' => $this->mime
,
196 'metadata' => $this->metadata
,
197 'size' => $this->size
);
199 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
201 // However we should clear them, so they aren't leftover
202 // if we've deleted the file.
203 $wgMemc->delete( $keys[0] );
208 * Load metadata from the file itself
210 function loadFromFile() {
211 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
212 $fname = 'Image::loadFromFile';
213 wfProfileIn( $fname );
214 $this->imagePath
= $this->getFullPath();
215 $this->fileExists
= file_exists( $this->imagePath
);
216 $this->fromSharedDirectory
= false;
219 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
221 # If the file is not found, and a shared upload directory is used, look for it there.
222 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
223 # In case we're on a wgCapitalLinks=false wiki, we
224 # capitalize the first letter of the filename before
225 # looking it up in the shared repository.
226 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
227 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
228 if ( $this->fileExists
) {
229 $this->name
= $sharedImage->name
;
230 $this->imagePath
= $this->getFullPath(true);
231 $this->fromSharedDirectory
= true;
236 if ( $this->fileExists
) {
237 $magic=& wfGetMimeMagic();
239 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
240 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
243 $this->size
= filesize( $this->imagePath
);
245 $magic=& wfGetMimeMagic();
248 if( $this->mime
== 'image/svg' ) {
249 wfSuppressWarnings();
250 $gis = wfGetSVGsize( $this->imagePath
);
253 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
254 # Don't try to get the width and height of sound and video files, that's bad for performance
257 $gis[2]= 0; //unknown
258 $gis[3]= ""; //width height string
261 wfSuppressWarnings();
262 $gis = getimagesize( $this->imagePath
);
266 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
271 $gis[2]= 0; //unknown
272 $gis[3]= ""; //width height string
275 $this->type
= MEDIATYPE_UNKNOWN
;
276 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
279 $this->width
= $gis[0];
280 $this->height
= $gis[1];
282 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
284 #NOTE: we have to set this flag early to avoid load() to be called
285 # be some of the functions below. This may lead to recursion or other bad things!
286 # as ther's only one thread of execution, this should be safe anyway.
287 $this->dataLoaded
= true;
290 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
291 else $this->metadata
= serialize ( array() ) ;
293 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
294 else $this->bits
= 0;
296 wfProfileOut( $fname );
300 * Load image metadata from the DB
302 function loadFromDB() {
303 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
304 $fname = 'Image::loadFromDB';
305 wfProfileIn( $fname );
307 $dbr =& wfGetDB( DB_SLAVE
);
309 $this->checkDBSchema($dbr);
311 $row = $dbr->selectRow( 'image',
312 array( 'img_size', 'img_width', 'img_height', 'img_bits',
313 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
314 array( 'img_name' => $this->name
), $fname );
316 $this->fromSharedDirectory
= false;
317 $this->fileExists
= true;
318 $this->loadFromRow( $row );
319 $this->imagePath
= $this->getFullPath();
320 // Check for rows from a previous schema, quietly upgrade them
321 if ( is_null($this->type
) ) {
324 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
325 # In case we're on a wgCapitalLinks=false wiki, we
326 # capitalize the first letter of the filename before
327 # looking it up in the shared repository.
328 $name = $wgContLang->ucfirst($this->name
);
329 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
331 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
333 'img_size', 'img_width', 'img_height', 'img_bits',
334 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
335 array( 'img_name' => $name ), $fname );
337 $this->fromSharedDirectory
= true;
338 $this->fileExists
= true;
339 $this->imagePath
= $this->getFullPath(true);
341 $this->loadFromRow( $row );
343 // Check for rows from a previous schema, quietly upgrade them
344 if ( is_null($this->type
) ) {
356 $this->fileExists
= false;
357 $this->fromSharedDirectory
= false;
358 $this->metadata
= serialize ( array() ) ;
361 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
362 $this->dataLoaded
= true;
363 wfProfileOut( $fname );
367 * Load image metadata from a DB result row
369 function loadFromRow( &$row ) {
370 $this->size
= $row->img_size
;
371 $this->width
= $row->img_width
;
372 $this->height
= $row->img_height
;
373 $this->bits
= $row->img_bits
;
374 $this->type
= $row->img_media_type
;
376 $major= $row->img_major_mime
;
377 $minor= $row->img_minor_mime
;
379 if (!$major) $this->mime
= "unknown/unknown";
381 if (!$minor) $minor= "unknown";
382 $this->mime
= $major.'/'.$minor;
385 $this->metadata
= $row->img_metadata
;
386 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
388 $this->dataLoaded
= true;
392 * Load image metadata from cache or DB, unless already loaded
395 global $wgSharedUploadDBname, $wgUseSharedUploads;
396 if ( !$this->dataLoaded
) {
397 if ( !$this->loadFromCache() ) {
399 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
400 $this->loadFromFile();
401 } elseif ( $this->fileExists
) {
402 $this->saveToCache();
405 $this->dataLoaded
= true;
410 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
411 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
413 function upgradeRow() {
414 global $wgDBname, $wgSharedUploadDBname;
415 $fname = 'Image::upgradeRow';
416 wfProfileIn( $fname );
418 $this->loadFromFile();
420 if ( $this->fromSharedDirectory
) {
421 if ( !$wgSharedUploadDBname ) {
422 wfProfileOut( $fname );
426 // Write to the other DB using selectDB, not database selectors
427 // This avoids breaking replication in MySQL
428 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
429 $dbw->selectDB( $wgSharedUploadDBname );
431 $dbw =& wfGetDB( DB_MASTER
);
434 $this->checkDBSchema($dbw);
436 if (strpos($this->mime
,'/')!==false) {
437 list($major,$minor)= explode('/',$this->mime
,2);
444 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
446 $dbw->update( 'image',
448 'img_width' => $this->width
,
449 'img_height' => $this->height
,
450 'img_bits' => $this->bits
,
451 'img_media_type' => $this->type
,
452 'img_major_mime' => $major,
453 'img_minor_mime' => $minor,
454 'img_metadata' => $this->metadata
,
455 ), array( 'img_name' => $this->name
), $fname
457 if ( $this->fromSharedDirectory
) {
458 $dbw->selectDB( $wgDBname );
460 wfProfileOut( $fname );
464 * Return the name of this image
472 * Return the associated title object
475 function getTitle() {
480 * Return the URL of the image file
486 if($this->fileExists
) {
487 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
495 function getViewURL() {
496 if( $this->mustRender()) {
497 if( $this->canRender() ) {
498 return $this->createThumb( $this->getWidth() );
501 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
502 return $this->getURL(); #hm... return NULL?
505 return $this->getURL();
510 * Return the image path of the image in the
511 * local file system as an absolute path
514 function getImagePath() {
516 return $this->imagePath
;
520 * Return the width of the image
522 * Returns -1 if the file specified is not a known image type
525 function getWidth() {
531 * Return the height of the image
533 * Returns -1 if the file specified is not a known image type
536 function getHeight() {
538 return $this->height
;
542 * Return the size of the image file, in bytes
551 * Returns the mime type of the file.
553 function getMimeType() {
559 * Return the type of the media in the file.
560 * Use the value returned by this function with the MEDIATYPE_xxx constants.
562 function getMediaType() {
568 * Checks if the file can be presented to the browser as a bitmap.
570 * Currently, this checks if the file is an image format
571 * that can be converted to a format
572 * supported by all browsers (namely GIF, PNG and JPEG),
573 * or if it is an SVG image and SVG conversion is enabled.
575 * @todo remember the result of this check.
577 function canRender() {
578 global $wgUseImageMagick;
580 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
582 $mime= $this->getMimeType();
584 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
586 #if it's SVG, check if there's a converter enabled
587 if ($mime === 'image/svg') {
588 global $wgSVGConverters, $wgSVGConverter;
590 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
591 wfDebug( "Image::canRender: SVG is ready!\n" );
594 wfDebug( "Image::canRender: SVG renderer missing\n" );
598 #image formats available on ALL browsers
599 if ( $mime === 'image/gif'
600 ||
$mime === 'image/png'
601 ||
$mime === 'image/jpeg' ) return true;
603 #image formats that can be converted to the above formats
604 if ($wgUseImageMagick) {
605 #convertable by ImageMagick (there are more...)
606 if ( $mime === 'image/vnd.wap.wbmp'
607 ||
$mime === 'image/x-xbitmap'
608 ||
$mime === 'image/x-xpixmap'
609 #|| $mime === 'image/x-icon' #file may be split into multiple parts
610 ||
$mime === 'image/x-portable-anymap'
611 ||
$mime === 'image/x-portable-bitmap'
612 ||
$mime === 'image/x-portable-graymap'
613 ||
$mime === 'image/x-portable-pixmap'
614 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
615 ||
$mime === 'image/x-rgb'
616 ||
$mime === 'image/x-bmp'
617 ||
$mime === 'image/tiff' ) return true;
620 #convertable by the PHP GD image lib
621 if ( $mime === 'image/vnd.wap.wbmp'
622 ||
$mime === 'image/x-xbitmap' ) return true;
630 * Return true if the file is of a type that can't be directly
631 * rendered by typical browsers and needs to be re-rasterized.
633 * This returns true for everything but the bitmap types
634 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
635 * also return true for any non-image formats.
639 function mustRender() {
640 $mime= $this->getMimeType();
642 if ( $mime === "image/gif"
643 ||
$mime === "image/png"
644 ||
$mime === "image/jpeg" ) return false;
650 * Determines if this media file may be shown inline on a page.
652 * This is currently synonymous to canRender(), but this could be
653 * extended to also allow inline display of other media,
654 * like flash animations or videos. If you do so, please keep in mind that
655 * that could be a security risk.
657 function allowInlineDisplay() {
658 return $this->canRender();
662 * Determines if this media file is in a format that is unlikely to
663 * contain viruses or malicious content. It uses the global
664 * $wgTrustedMediaFormats list to determine if the file is safe.
666 * This is used to show a warning on the description page of non-safe files.
667 * It may also be used to disallow direct [[media:...]] links to such files.
669 * Note that this function will always return true if allowInlineDisplay()
670 * or isTrustedFile() is true for this file.
672 function isSafeFile() {
673 if ($this->allowInlineDisplay()) return true;
674 if ($this->isTrustedFile()) return true;
676 global $wgTrustedMediaFormats;
678 $type= $this->getMediaType();
679 $mime= $this->getMimeType();
680 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
682 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
683 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
685 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
686 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
691 /** Returns true if the file is flagged as trusted. Files flagged that way
692 * can be linked to directly, even if that is not allowed for this type of
695 * This is a dummy function right now and always returns false. It could be
696 * implemented to extract a flag from the database. The trusted flag could be
697 * set on upload, if the user has sufficient privileges, to bypass script-
698 * and html-filters. It may even be coupled with cryptographics signatures
701 function isTrustedFile() {
702 #this could be implemented to check a flag in the databas,
703 #look for signatures, etc
708 * Return the escapeLocalURL of this image
711 function getEscapeLocalURL() {
713 return $this->title
->escapeLocalURL();
717 * Return the escapeFullURL of this image
720 function getEscapeFullURL() {
722 return $this->title
->escapeFullURL();
726 * Return the URL of an image, provided its name.
728 * @param string $name Name of the image, without the leading "Image:"
729 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
730 * @return string URL of $name image
734 function imageUrl( $name, $fromSharedDirectory = false ) {
735 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
736 if($fromSharedDirectory) {
738 $path = $wgSharedUploadPath;
740 $base = $wgUploadBaseUrl;
741 $path = $wgUploadPath;
743 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
744 return wfUrlencode( $url );
748 * Returns true if the image file exists on disk.
749 * @return boolean Whether image file exist on disk.
754 return $this->fileExists
;
761 function thumbUrl( $width, $subdir='thumb') {
762 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
763 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
765 // Generate thumb.php URL if possible
769 if ( $this->fromSharedDirectory
) {
770 if ( $wgSharedThumbnailScriptPath ) {
771 $script = $wgSharedThumbnailScriptPath;
774 if ( $wgThumbnailScriptPath ) {
775 $script = $wgThumbnailScriptPath;
779 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
780 if( $this->mustRender() ) {
784 $name = $this->thumbName( $width );
785 if($this->fromSharedDirectory
) {
787 $path = $wgSharedUploadPath;
789 $base = $wgUploadBaseUrl;
790 $path = $wgUploadPath;
792 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
793 $url = "{$base}{$path}/{$subdir}" .
794 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
795 . $this->name
.'/'.$name;
796 $url = wfUrlencode( $url );
798 $url = "{$base}{$path}/{$subdir}/{$name}";
801 return array( $script !== false, $url );
805 * Return the file name of a thumbnail of the specified width
807 * @param integer $width Width of the thumbnail image
808 * @param boolean $shared Does the thumbnail come from the shared repository?
811 function thumbName( $width ) {
812 $thumb = $width."px-".$this->name
;
814 if( $this->mustRender() ) {
815 if( $this->canRender() ) {
816 # Rasterize to PNG (for SVG vector images, etc)
820 #should we use iconThumb here to get a symbolic thumbnail?
821 #or should we fail with an internal error?
822 return NULL; //can't make bitmap
829 * Create a thumbnail of the image having the specified width/height.
830 * The thumbnail will not be created if the width is larger than the
831 * image's width. Let the browser do the scaling in this case.
832 * The thumbnail is stored on disk and is only computed if the thumbnail
833 * file does not exist OR if it is older than the image.
836 * Keeps aspect ratio of original image. If both width and height are
837 * specified, the generated image will be no bigger than width x height,
838 * and will also have correct aspect ratio.
840 * @param integer $width maximum width of the generated thumbnail
841 * @param integer $height maximum height of the image (optional)
844 function createThumb( $width, $height=-1 ) {
845 $thumb = $this->getThumbnail( $width, $height );
846 if( is_null( $thumb ) ) return '';
847 return $thumb->getUrl();
851 * As createThumb, but returns a ThumbnailImage object. This can
852 * provide access to the actual file, the real size of the thumb,
853 * and can produce a convenient <img> tag for you.
855 * @param integer $width maximum width of the generated thumbnail
856 * @param integer $height maximum height of the image (optional)
857 * @return ThumbnailImage
860 function getThumbnail( $width, $height=-1 ) {
861 if ( $height <= 0 ) {
862 return $this->renderThumb( $width );
866 if ($this->canRender()) {
867 if ( $width > $this->width
* $height / $this->height
)
868 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
869 $thumb = $this->renderThumb( $width );
871 else $thumb= NULL; #not a bitmap or renderable image, don't try.
873 if( is_null( $thumb ) ) {
874 $thumb = $this->iconThumb();
880 * @return ThumbnailImage
882 function iconThumb() {
883 global $wgStylePath, $wgStyleDirectory;
885 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
886 foreach( $try as $icon ) {
887 $path = '/common/images/icons/' . $icon;
888 $filepath = $wgStyleDirectory . $path;
889 if( file_exists( $filepath ) ) {
890 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
897 * Create a thumbnail of the image having the specified width.
898 * The thumbnail will not be created if the width is larger than the
899 * image's width. Let the browser do the scaling in this case.
900 * The thumbnail is stored on disk and is only computed if the thumbnail
901 * file does not exist OR if it is older than the image.
902 * Returns an object which can return the pathname, URL, and physical
903 * pixel size of the thumbnail -- or null on failure.
905 * @return ThumbnailImage
908 function renderThumb( $width, $useScript = true ) {
910 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
912 $fname = 'Image::renderThumb';
913 wfProfileIn( $fname );
915 $width = intval( $width );
918 if ( ! $this->exists() )
920 # If there is no image, there will be no thumbnail
921 wfProfileOut( $fname );
925 # Sanity check $width
926 if( $width <= 0 ||
$this->width
<= 0) {
928 wfProfileOut( $fname );
932 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
933 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
934 # an exception for it.
935 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
936 $this->getMimeType() !== 'image/jpeg' &&
937 $this->width
* $this->height
> $wgMaxImageArea )
939 wfProfileOut( $fname );
943 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
944 if ( $this->mustRender() ) {
945 $width = min( $width, $wgSVGMaxSize );
946 } elseif ( $width > $this->width
- 1 ) {
947 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
948 wfProfileOut( $fname );
952 $height = round( $this->height
* $width / $this->width
);
954 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
955 if ( $isScriptUrl && $useScript ) {
956 // Use thumb.php to render the image
957 $thumb = new ThumbnailImage( $url, $width, $height );
958 wfProfileOut( $fname );
962 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
963 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
965 if ( is_dir( $thumbPath ) ) {
966 // Directory where file should be
967 // This happened occasionally due to broken migration code in 1.5
968 // Rename to broken-*
969 global $wgUploadDirectory;
970 for ( $i = 0; $i < 100 ; $i++
) {
971 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
972 if ( !file_exists( $broken ) ) {
973 rename( $thumbPath, $broken );
977 // Code below will ask if it exists, and the answer is now no
982 if ( !file_exists( $thumbPath ) ||
983 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) ) {
984 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
988 // Migration from old directory structure
989 if ( is_file( $oldThumbPath ) ) {
990 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
991 if ( file_exists( $thumbPath ) ) {
992 if ( !is_dir( $thumbPath ) ) {
993 // Old image in the way of rename
994 unlink( $thumbPath );
996 // This should have been dealt with already
997 throw new MWException( "Directory where image should be: $thumbPath" );
1000 // Rename the old image into the new location
1001 rename( $oldThumbPath, $thumbPath );
1004 unlink( $oldThumbPath );
1008 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1009 if ( $this->lastError
=== true ) {
1011 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1012 // Log the error but output anyway.
1013 // With luck it's a transitory error...
1018 # This has to be done after the image is updated and present for all machines on NFS,
1019 # or else the old version might be stored into the squid again
1020 if ( $wgUseSquid ) {
1021 $urlArr = array( $url );
1022 wfPurgeSquidServers($urlArr);
1028 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1032 wfProfileOut( $fname );
1034 } // END OF function renderThumb
1037 * Really render a thumbnail
1038 * Call this only for images for which canRender() returns true.
1040 * @param string $thumbPath Path to thumbnail
1041 * @param int $width Desired width in pixels
1042 * @param int $height Desired height in pixels
1043 * @return bool True on error, false or error string on failure.
1046 function reallyRenderThumb( $thumbPath, $width, $height ) {
1047 global $wgSVGConverters, $wgSVGConverter;
1048 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1049 global $wgCustomConvertCommand;
1057 if( $this->mime
=== "image/svg" ) {
1058 #Right now we have only SVG
1060 global $wgSVGConverters, $wgSVGConverter;
1061 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1062 global $wgSVGConverterPath;
1064 array( '$path/', '$width', '$height', '$input', '$output' ),
1065 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1068 wfEscapeShellArg( $this->imagePath
),
1069 wfEscapeShellArg( $thumbPath ) ),
1070 $wgSVGConverters[$wgSVGConverter] );
1071 wfProfileIn( 'rsvg' );
1072 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1073 $err = wfShellExec( $cmd, $retval );
1074 wfProfileOut( 'rsvg' );
1076 } elseif ( $wgUseImageMagick ) {
1079 if ( $this->mime
== 'image/jpeg' ) {
1080 $quality = "-quality 80"; // 80%
1081 } elseif ( $this->mime
== 'image/png' ) {
1082 $quality = "-quality 95"; // zlib 9, adaptive filtering
1084 $quality = ''; // default
1087 # Specify white background color, will be used for transparent images
1088 # in Internet Explorer/Windows instead of default black.
1090 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1091 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1092 # the wrong size in the second case.
1094 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1095 " {$quality} -background white -size {$width} ".
1096 wfEscapeShellArg($this->imagePath
) .
1097 // Coalesce is needed to scale animated GIFs properly (bug 1017).
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, $retval );
1108 wfProfileOut( 'convert' );
1109 } elseif( $wgCustomConvertCommand ) {
1110 # Use a custom convert command
1111 # Variables: %s %d %w %h
1112 $src = wfEscapeShellArg( $this->imagePath
);
1113 $dst = wfEscapeShellArg( $thumbPath );
1114 $cmd = $wgCustomConvertCommand;
1115 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1116 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1117 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1118 wfProfileIn( 'convert' );
1119 $err = wfShellExec( $cmd, $retval );
1120 wfProfileOut( 'convert' );
1122 # Use PHP's builtin GD library functions.
1124 # First find out what kind of file this is, and select the correct
1125 # input routine for this.
1128 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1129 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1130 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1131 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1132 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1134 if( !isset( $typemap[$this->mime
] ) ) {
1135 $err = 'Image type not supported';
1136 wfDebug( "$err\n" );
1139 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1141 if( !function_exists( $loader ) ) {
1142 $err = "Incomplete GD library configuration: missing function $loader";
1143 wfDebug( "$err\n" );
1146 if( $colorStyle == 'palette' ) {
1148 } elseif( $colorStyle == 'truecolor' ) {
1150 } elseif( $colorStyle == 'bits' ) {
1151 $truecolor = ( $this->bits
> 8 );
1154 $src_image = call_user_func( $loader, $this->imagePath
);
1156 $dst_image = imagecreatetruecolor( $width, $height );
1158 $dst_image = imagecreate( $width, $height );
1160 imagecopyresampled( $dst_image, $src_image,
1162 $width, $height, $this->width
, $this->height
);
1163 call_user_func( $saveType, $dst_image, $thumbPath );
1164 imagedestroy( $dst_image );
1165 imagedestroy( $src_image );
1169 # Check for zero-sized thumbnails. Those can be generated when
1170 # no disk space is available or some other error occurs
1172 if( file_exists( $thumbPath ) ) {
1173 $thumbstat = stat( $thumbPath );
1174 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1175 wfDebugLog( 'thumbnail',
1176 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1177 $thumbstat['size'], $thumbPath ) );
1178 unlink( $thumbPath );
1181 if ( $retval != 0 ) {
1182 wfDebugLog( 'thumbnail',
1183 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1184 wfHostname(), $retval, trim($err), $cmd ) );
1185 return wfMsg( 'thumbnail_error', $err );
1191 function getLastError() {
1192 return $this->lastError
;
1195 function imageJpegWrapper( $dst_image, $thumbPath ) {
1196 imageinterlace( $dst_image );
1197 imagejpeg( $dst_image, $thumbPath, 95 );
1201 * Get all thumbnail names previously generated for this image
1203 function getThumbnails( $shared = false ) {
1204 if ( Image
::isHashed( $shared ) ) {
1207 $dir = wfImageThumbDir( $this->name
, $shared );
1209 // This generates an error on failure, hence the @
1210 $handle = @opendir
( $dir );
1213 while ( false !== ( $file = readdir($handle) ) ) {
1214 if ( $file{0} != '.' ) {
1218 closedir( $handle );
1228 * Refresh metadata in memcached, but don't touch thumbnails or squid
1230 function purgeMetadataCache() {
1232 $this->loadFromFile();
1233 $this->saveToCache();
1237 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1239 function purgeCache( $archiveFiles = array(), $shared = false ) {
1242 // Refresh metadata cache
1243 $this->purgeMetadataCache();
1245 // Delete thumbnails
1246 $files = $this->getThumbnails( $shared );
1247 $dir = wfImageThumbDir( $this->name
, $shared );
1249 foreach ( $files as $file ) {
1250 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1251 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1252 @unlink
( "$dir/$file" );
1257 if ( $wgUseSquid ) {
1258 $urls[] = $this->getViewURL();
1259 foreach ( $archiveFiles as $file ) {
1260 $urls[] = wfImageArchiveUrl( $file );
1262 wfPurgeSquidServers( $urls );
1266 function checkDBSchema(&$db) {
1267 global $wgCheckDBSchema;
1268 if (!$wgCheckDBSchema) {
1271 # img_name must be unique
1272 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1273 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1276 # new fields must exist
1278 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1279 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1280 # something. The only reason I put the above schema check in was because the absence of that particular
1281 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1284 if ( !$db->fieldExists( 'image', 'img_media_type' )
1285 || !$db->fieldExists( 'image', 'img_metadata' )
1286 || !$db->fieldExists( 'image', 'img_width' ) ) {
1288 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1294 * Return the image history of this image, line by line.
1295 * starts with current version, then old versions.
1296 * uses $this->historyLine to check which line to return:
1297 * 0 return line for current version
1298 * 1 query for old versions, return first one
1299 * 2, ... return next old version from above query
1303 function nextHistoryLine() {
1304 $fname = 'Image::nextHistoryLine()';
1305 $dbr =& wfGetDB( DB_SLAVE
);
1307 $this->checkDBSchema($dbr);
1309 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1310 $this->historyRes
= $dbr->select( 'image',
1314 'img_user','img_user_text',
1318 "'' AS oi_archive_name"
1320 array( 'img_name' => $this->title
->getDBkey() ),
1323 if ( 0 == wfNumRows( $this->historyRes
) ) {
1326 } else if ( $this->historyLine
== 1 ) {
1327 $this->historyRes
= $dbr->select( 'oldimage',
1329 'oi_size AS img_size',
1330 'oi_description AS img_description',
1331 'oi_user AS img_user',
1332 'oi_user_text AS img_user_text',
1333 'oi_timestamp AS img_timestamp',
1334 'oi_width as img_width',
1335 'oi_height as img_height',
1338 array( 'oi_name' => $this->title
->getDBkey() ),
1340 array( 'ORDER BY' => 'oi_timestamp DESC' )
1343 $this->historyLine ++
;
1345 return $dbr->fetchObject( $this->historyRes
);
1349 * Reset the history pointer to the first element of the history
1352 function resetHistory() {
1353 $this->historyLine
= 0;
1357 * Return the full filesystem path to the file. Note that this does
1358 * not mean that a file actually exists under that location.
1360 * This path depends on whether directory hashing is active or not,
1361 * i.e. whether the images are all found in the same directory,
1362 * or in hashed paths like /images/3/3c.
1365 * @param boolean $fromSharedDirectory Return the path to the file
1366 * in a shared repository (see $wgUseSharedRepository and related
1367 * options in DefaultSettings.php) instead of a local one.
1370 function getFullPath( $fromSharedRepository = false ) {
1371 global $wgUploadDirectory, $wgSharedUploadDirectory;
1373 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1376 // $wgSharedUploadDirectory may be false, if thumb.php is used
1378 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1390 function isHashed( $shared ) {
1391 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1392 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1396 * Record an image upload in the upload log and the image table
1398 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1399 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1401 $fname = 'Image::recordUpload';
1402 $dbw =& wfGetDB( DB_MASTER
);
1404 $this->checkDBSchema($dbw);
1406 // Delete thumbnails and refresh the metadata cache
1407 $this->purgeCache();
1409 // Fail now if the image isn't there
1410 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1411 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1415 if ( $wgUseCopyrightUpload ) {
1416 if ( $license != '' ) {
1417 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1419 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1420 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1422 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1424 if ( $license != '' ) {
1425 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1426 $textdesc = $filedesc .
1427 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1433 $now = $dbw->timestamp();
1436 if (strpos($this->mime
,'/')!==false) {
1437 list($major,$minor)= explode('/',$this->mime
,2);
1440 $major= $this->mime
;
1444 # Test to see if the row exists using INSERT IGNORE
1445 # This avoids race conditions by locking the row until the commit, and also
1446 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1447 $dbw->insert( 'image',
1449 'img_name' => $this->name
,
1450 'img_size'=> $this->size
,
1451 'img_width' => intval( $this->width
),
1452 'img_height' => intval( $this->height
),
1453 'img_bits' => $this->bits
,
1454 'img_media_type' => $this->type
,
1455 'img_major_mime' => $major,
1456 'img_minor_mime' => $minor,
1457 'img_timestamp' => $now,
1458 'img_description' => $desc,
1459 'img_user' => $wgUser->getID(),
1460 'img_user_text' => $wgUser->getName(),
1461 'img_metadata' => $this->metadata
,
1466 $descTitle = $this->getTitle();
1467 $purgeURLs = array();
1469 if( $dbw->affectedRows() == 0 ) {
1470 # Collision, this is an update of an image
1471 # Insert previous contents into oldimage
1472 $dbw->insertSelect( 'oldimage', 'image',
1474 'oi_name' => 'img_name',
1475 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1476 'oi_size' => 'img_size',
1477 'oi_width' => 'img_width',
1478 'oi_height' => 'img_height',
1479 'oi_bits' => 'img_bits',
1480 'oi_timestamp' => 'img_timestamp',
1481 'oi_description' => 'img_description',
1482 'oi_user' => 'img_user',
1483 'oi_user_text' => 'img_user_text',
1484 ), array( 'img_name' => $this->name
), $fname
1487 # Update the current image row
1488 $dbw->update( 'image',
1490 'img_size' => $this->size
,
1491 'img_width' => intval( $this->width
),
1492 'img_height' => intval( $this->height
),
1493 'img_bits' => $this->bits
,
1494 'img_media_type' => $this->type
,
1495 'img_major_mime' => $major,
1496 'img_minor_mime' => $minor,
1497 'img_timestamp' => $now,
1498 'img_description' => $desc,
1499 'img_user' => $wgUser->getID(),
1500 'img_user_text' => $wgUser->getName(),
1501 'img_metadata' => $this->metadata
,
1502 ), array( /* WHERE */
1503 'img_name' => $this->name
1507 # This is a new image
1508 # Update the image count
1509 $site_stats = $dbw->tableName( 'site_stats' );
1510 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
1513 $article = new Article( $descTitle );
1515 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1516 $suppressRC = true; // There's already a log entry, so don't double the RC load
1518 if( $descTitle->exists() ) {
1519 // TODO: insert a null revision into the page history for this update.
1521 $wgUser->addWatch( $descTitle );
1524 # Invalidate the cache for the description page
1525 $descTitle->invalidateCache();
1526 $purgeURLs[] = $descTitle->getInternalURL();
1528 // New image; create the description page.
1529 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1532 # Invalidate cache for all pages using this image
1533 $linksTo = $this->getLinksTo();
1535 if ( $wgUseSquid ) {
1536 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1537 array_push( $wgPostCommitUpdateList, $u );
1539 Title
::touchArray( $linksTo );
1541 $log = new LogPage( 'upload' );
1542 $log->addEntry( 'upload', $descTitle, $desc );
1548 * Get an array of Title objects which are articles which use this image
1549 * Also adds their IDs to the link cache
1551 * This is mostly copied from Title::getLinksTo()
1553 function getLinksTo( $options = '' ) {
1554 $fname = 'Image::getLinksTo';
1555 wfProfileIn( $fname );
1558 $db =& wfGetDB( DB_MASTER
);
1560 $db =& wfGetDB( DB_SLAVE
);
1562 $linkCache =& LinkCache
::singleton();
1564 extract( $db->tableNames( 'page', 'imagelinks' ) );
1565 $encName = $db->addQuotes( $this->name
);
1566 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1567 $res = $db->query( $sql, $fname );
1570 if ( $db->numRows( $res ) ) {
1571 while ( $row = $db->fetchObject( $res ) ) {
1572 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1573 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1574 $retVal[] = $titleObj;
1578 $db->freeResult( $res );
1579 wfProfileOut( $fname );
1583 * Retrive Exif data from the database
1585 * Retrive Exif data from the database and prune unrecognized tags
1586 * and/or tags with invalid contents
1590 function retrieveExifData() {
1591 if ( $this->getMimeType() !== "image/jpeg" )
1594 $exif = new Exif( $this->imagePath
);
1595 return $exif->getFilteredData();
1598 function getExifData() {
1600 if ( $this->metadata
=== '0' )
1603 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1604 $ret = unserialize( $this->metadata
);
1606 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1607 $newver = Exif
::version();
1609 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1610 $this->purgeMetadataCache();
1611 $this->updateExifData( $newver );
1613 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1614 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1615 $format = new FormatExif( $ret );
1617 return $format->getFormattedData();
1620 function updateExifData( $version ) {
1621 $fname = 'Image:updateExifData';
1623 if ( $this->getImagePath() === false ) # Not a local image
1626 # Get EXIF data from image
1627 $exif = $this->retrieveExifData();
1628 if ( count( $exif ) ) {
1629 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1630 $this->metadata
= serialize( $exif );
1632 $this->metadata
= '0';
1635 # Update EXIF data in database
1636 $dbw =& wfGetDB( DB_MASTER
);
1638 $this->checkDBSchema($dbw);
1640 $dbw->update( 'image',
1641 array( 'img_metadata' => $this->metadata
),
1642 array( 'img_name' => $this->name
),
1648 * Returns true if the image does not come from the shared
1653 function isLocal() {
1654 return !$this->fromSharedDirectory
;
1658 * Was this image ever deleted from the wiki?
1662 function wasDeleted() {
1663 $dbw =& wfGetDB( DB_MASTER
);
1664 $del = $dbw->selectField( 'archive', 'COUNT(*) AS count', array( 'ar_namespace' => NS_IMAGE
, 'ar_title' => $this->title
->getDBkey() ), 'Image::wasDeleted' );
1672 * Returns the image directory of an image
1673 * If the directory does not exist, it is created.
1674 * The result is an absolute path.
1676 * This function is called from thumb.php before Setup.php is included
1678 * @param $fname String: file name of the image file.
1681 function wfImageDir( $fname ) {
1682 global $wgUploadDirectory, $wgHashedUploadDirectory;
1684 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1686 $hash = md5( $fname );
1687 $oldumask = umask(0);
1688 $dest = $wgUploadDirectory . '/' . $hash{0};
1689 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1690 $dest .= '/' . substr( $hash, 0, 2 );
1691 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1698 * Returns the image directory of an image's thubnail
1699 * If the directory does not exist, it is created.
1700 * The result is an absolute path.
1702 * This function is called from thumb.php before Setup.php is included
1704 * @param $fname String: file name of the original image file
1705 * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
1708 function wfImageThumbDir( $fname, $shared = false ) {
1709 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1710 if ( Image
::isHashed( $shared ) ) {
1711 $dir = "$base/$fname";
1713 if ( !is_dir( $base ) ) {
1714 $oldumask = umask(0);
1715 @mkdir
( $base, 0777 );
1719 if ( ! is_dir( $dir ) ) {
1720 if ( is_file( $dir ) ) {
1721 // Old thumbnail in the way of directory creation, kill it
1724 $oldumask = umask(0);
1725 @mkdir
( $dir, 0777 );
1736 * Old thumbnail directory, kept for conversion
1738 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1739 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1743 * Returns the image directory of an image's old version
1744 * If the directory does not exist, it is created.
1745 * The result is an absolute path.
1747 * This function is called from thumb.php before Setup.php is included
1749 * @param $fname String: file name of the thumbnail file, including file size prefix.
1750 * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
1751 * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
1754 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1755 global $wgUploadDirectory, $wgHashedUploadDirectory;
1756 global $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1757 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1758 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1759 if (!$hashdir) { return $dir.'/'.$subdir; }
1760 $hash = md5( $fname );
1761 $oldumask = umask(0);
1763 # Suppress warning messages here; if the file itself can't
1764 # be written we'll worry about it then.
1765 wfSuppressWarnings();
1767 $archive = $dir.'/'.$subdir;
1768 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1769 $archive .= '/' . $hash{0};
1770 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1771 $archive .= '/' . substr( $hash, 0, 2 );
1772 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1774 wfRestoreWarnings();
1781 * Return the hash path component of an image path (URL or filesystem),
1782 * e.g. "/3/3c/", or just "/" if hashing is not used.
1784 * @param $dbkey The filesystem / database name of the file
1785 * @param $fromSharedDirectory Use the shared file repository? It may
1786 * use different hash settings from the local one.
1788 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1789 if( Image
::isHashed( $fromSharedDirectory ) ) {
1790 $hash = md5($dbkey);
1791 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1798 * Returns the image URL of an image's old version
1800 * @param $name String: file name of the image file
1801 * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1804 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1805 global $wgUploadPath, $wgHashedUploadDirectory;
1807 if ($wgHashedUploadDirectory) {
1808 $hash = md5( substr( $name, 15) );
1809 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1810 substr( $hash, 0, 2 ) . '/'.$name;
1812 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1814 return wfUrlencode($url);
1818 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1819 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1821 * @param $length String: CSS/SVG length.
1822 * @return Integer: length in pixels
1824 function wfScaleSVGUnit( $length ) {
1825 static $unitLength = array(
1832 '' => 1.0, // "User units" pixels by default
1833 '%' => 2.0, // Fake it!
1835 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1836 $length = floatval( $matches[1] );
1837 $unit = $matches[2];
1838 return round( $length * $unitLength[$unit] );
1841 return round( floatval( $length ) );
1846 * Compatible with PHP getimagesize()
1847 * @todo support gzipped SVGZ
1848 * @todo check XML more carefully
1849 * @todo sensible defaults
1851 * @param $filename String: full name of the file (passed to php fopen()).
1854 function wfGetSVGsize( $filename ) {
1858 // Read a chunk of the file
1859 $f = fopen( $filename, "rt" );
1860 if( !$f ) return false;
1861 $chunk = fread( $f, 4096 );
1864 // Uber-crappy hack! Run through a real XML parser.
1865 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1869 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1870 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1872 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1873 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1876 return array( $width, $height, 'SVG',
1877 "width=\"$width\" height=\"$height\"" );
1881 * Determine if an image exists on the 'bad image list'.
1883 * @param $name String: the image name to check
1886 function wfIsBadImage( $name ) {
1887 static $titleList = false;
1890 # Build the list now
1891 $titleList = array();
1892 $lines = explode( "\n", wfMsgForContent( 'bad_image_list' ) );
1893 foreach( $lines as $line ) {
1894 if( preg_match( '/^\*\s*\[\[:?(.*?)\]\]/i', $line, $matches ) ) {
1895 $title = Title
::newFromText( $matches[1] );
1896 if( is_object( $title ) && $title->getNamespace() == NS_IMAGE
)
1897 $titleList[ $title->getDBkey() ] = true;
1901 return array_key_exists( $name, $titleList );
1907 * Wrapper class for thumbnail images
1908 * @package MediaWiki
1910 class ThumbnailImage
{
1912 * @param string $path Filesystem path to the thumb
1913 * @param string $url URL path to the thumb
1916 function ThumbnailImage( $url, $width, $height, $path = false ) {
1918 $this->width
= round( $width );
1919 $this->height
= round( $height );
1920 # These should be integers when they get here.
1921 # If not, there's a bug somewhere. But let's at
1922 # least produce valid HTML code regardless.
1923 $this->path
= $path;
1927 * @return string The thumbnail URL
1934 * Return HTML <img ... /> tag for the thumbnail, will include
1935 * width and height attributes and a blank alt text (as required).
1937 * You can set or override additional attributes by passing an
1938 * associative array of name => data pairs. The data will be escaped
1939 * for HTML output, so should be in plaintext.
1941 * @param array $attribs
1945 function toHtml( $attribs = array() ) {
1946 $attribs['src'] = $this->url
;
1947 $attribs['width'] = $this->width
;
1948 $attribs['height'] = $this->height
;
1949 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1952 foreach( $attribs as $name => $data ) {
1953 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1962 * Calculate the largest thumbnail width for a given original file size
1963 * such that the thumbnail's height is at most $maxHeight.
1964 * @param $boxWidth Integer Width of the thumbnail box.
1965 * @param $boxHeight Integer Height of the thumbnail box.
1966 * @param $maxHeight Integer Maximum height expected for the thumbnail.
1969 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
1970 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
1971 $roundedUp = ceil( $idealWidth );
1972 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
1973 return floor( $idealWidth );