6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
15 * Bump this number when serialized cache records may be incompatible.
17 define( 'MW_IMAGE_VERSION', 1 );
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
27 const DELETED_FILE
= 1;
28 const DELETED_COMMENT
= 2;
29 const DELETED_USER
= 4;
30 const DELETED_RESTRICTED
= 8;
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 $page, # Page to render when creating thumbnails
53 $lastError; # Error string associated with a thumbnail display error
59 * Create an Image object from an image name
61 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
64 public static function newFromName( $name ) {
65 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
66 if ( is_object( $title ) ) {
67 return new Image( $title );
74 * Obsolete factory function, use constructor
77 function newFromTitle( $title ) {
78 return new Image( $title );
81 function Image( $title ) {
82 if( !is_object( $title ) ) {
83 throw new MWException( 'Image constructor given bogus title.' );
85 $this->title
=& $title;
86 $this->name
= $title->getDBkey();
87 $this->metadata
= serialize ( array() ) ;
89 $n = strrpos( $this->name
, '.' );
90 $this->extension
= Image
::normalizeExtension( $n ?
91 substr( $this->name
, $n +
1 ) : '' );
92 $this->historyLine
= 0;
95 $this->dataLoaded
= false;
99 * Normalize a file extension to the common form, and ensure it's clean.
100 * Extensions with non-alphanumeric characters will be discarded.
102 * @param $ext string (without the .)
105 static function normalizeExtension( $ext ) {
106 $lower = strtolower( $ext );
112 if( isset( $squish[$lower] ) ) {
113 return $squish[$lower];
114 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
122 * Get the memcached keys
123 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
125 function getCacheKeys( ) {
126 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
128 $hashedName = md5($this->name
);
129 $keys = array( wfMemcKey( 'Image', $hashedName ) );
130 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
131 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
137 * Try to load image metadata from memcached. Returns true on success.
139 function loadFromCache() {
140 global $wgUseSharedUploads, $wgMemc;
141 wfProfileIn( __METHOD__
);
142 $this->dataLoaded
= false;
143 $keys = $this->getCacheKeys();
144 $cachedValues = $wgMemc->get( $keys[0] );
146 // Check if the key existed and belongs to this version of MediaWiki
147 if (!empty($cachedValues) && is_array($cachedValues)
148 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
149 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
151 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
152 # if this is shared file, we need to check if image
153 # in shared repository has not changed
154 if ( isset( $keys[1] ) ) {
155 $commonsCachedValues = $wgMemc->get( $keys[1] );
156 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
157 && isset($commonsCachedValues['version'])
158 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
159 && isset($commonsCachedValues['mime'])) {
160 wfDebug( "Pulling image metadata from shared repository cache\n" );
161 $this->name
= $commonsCachedValues['name'];
162 $this->imagePath
= $commonsCachedValues['imagePath'];
163 $this->fileExists
= $commonsCachedValues['fileExists'];
164 $this->width
= $commonsCachedValues['width'];
165 $this->height
= $commonsCachedValues['height'];
166 $this->bits
= $commonsCachedValues['bits'];
167 $this->type
= $commonsCachedValues['type'];
168 $this->mime
= $commonsCachedValues['mime'];
169 $this->metadata
= $commonsCachedValues['metadata'];
170 $this->size
= $commonsCachedValues['size'];
171 $this->fromSharedDirectory
= true;
172 $this->dataLoaded
= true;
173 $this->imagePath
= $this->getFullPath(true);
177 wfDebug( "Pulling image metadata from local cache\n" );
178 $this->name
= $cachedValues['name'];
179 $this->imagePath
= $cachedValues['imagePath'];
180 $this->fileExists
= $cachedValues['fileExists'];
181 $this->width
= $cachedValues['width'];
182 $this->height
= $cachedValues['height'];
183 $this->bits
= $cachedValues['bits'];
184 $this->type
= $cachedValues['type'];
185 $this->mime
= $cachedValues['mime'];
186 $this->metadata
= $cachedValues['metadata'];
187 $this->size
= $cachedValues['size'];
188 $this->fromSharedDirectory
= false;
189 $this->dataLoaded
= true;
190 $this->imagePath
= $this->getFullPath();
193 if ( $this->dataLoaded
) {
194 wfIncrStats( 'image_cache_hit' );
196 wfIncrStats( 'image_cache_miss' );
199 wfProfileOut( __METHOD__
);
200 return $this->dataLoaded
;
204 * Save the image metadata to memcached
206 function saveToCache() {
207 global $wgMemc, $wgUseSharedUploads;
209 $keys = $this->getCacheKeys();
210 // We can't cache negative metadata for non-existent files,
211 // because if the file later appears in commons, the local
212 // keys won't be purged.
213 if ( $this->fileExists ||
!$wgUseSharedUploads ) {
214 $cachedValues = array(
215 'version' => MW_IMAGE_VERSION
,
216 'name' => $this->name
,
217 'imagePath' => $this->imagePath
,
218 'fileExists' => $this->fileExists
,
219 'fromShared' => $this->fromSharedDirectory
,
220 'width' => $this->width
,
221 'height' => $this->height
,
222 'bits' => $this->bits
,
223 'type' => $this->type
,
224 'mime' => $this->mime
,
225 'metadata' => $this->metadata
,
226 'size' => $this->size
);
228 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
230 // However we should clear them, so they aren't leftover
231 // if we've deleted the file.
232 $wgMemc->delete( $keys[0] );
237 * Load metadata from the file itself
239 function loadFromFile() {
240 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
241 wfProfileIn( __METHOD__
);
242 $this->imagePath
= $this->getFullPath();
243 $this->fileExists
= file_exists( $this->imagePath
);
244 $this->fromSharedDirectory
= false;
247 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
249 # If the file is not found, and a shared upload directory is used, look for it there.
250 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
251 # In case we're on a wgCapitalLinks=false wiki, we
252 # capitalize the first letter of the filename before
253 # looking it up in the shared repository.
254 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
255 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
256 if ( $this->fileExists
) {
257 $this->name
= $sharedImage->name
;
258 $this->imagePath
= $this->getFullPath(true);
259 $this->fromSharedDirectory
= true;
264 if ( $this->fileExists
) {
265 $magic=& MimeMagic
::singleton();
267 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
268 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
271 $this->size
= filesize( $this->imagePath
);
273 $magic=& MimeMagic
::singleton();
276 wfSuppressWarnings();
277 if( $this->mime
== 'image/svg' ) {
278 $gis = wfGetSVGsize( $this->imagePath
);
279 } elseif( $this->mime
== 'image/vnd.djvu' ) {
280 $deja = new DjVuImage( $this->imagePath
);
281 $gis = $deja->getImageSize();
282 } elseif ( !$magic->isPHPImageType( $this->mime
) ) {
283 # Don't try to get the width and height of sound and video files, that's bad for performance
286 $gis = getimagesize( $this->imagePath
);
290 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
294 $this->type
= MEDIATYPE_UNKNOWN
;
295 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
299 $this->width
= $gis[0];
300 $this->height
= $gis[1];
306 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
308 #NOTE: we have to set this flag early to avoid load() to be called
309 # be some of the functions below. This may lead to recursion or other bad things!
310 # as ther's only one thread of execution, this should be safe anyway.
311 $this->dataLoaded
= true;
314 if ( $this->mime
== 'image/vnd.djvu' ) {
315 $this->metadata
= $deja->retrieveMetaData();
317 $this->metadata
= serialize( $this->retrieveExifData( $this->imagePath
) );
320 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
321 else $this->bits
= 0;
323 wfProfileOut( __METHOD__
);
327 * Load image metadata from the DB
329 function loadFromDB() {
330 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
331 wfProfileIn( __METHOD__
);
333 $dbr = wfGetDB( DB_SLAVE
);
334 $this->checkDBSchema($dbr);
336 $row = $dbr->selectRow( 'image',
337 array( 'img_size', 'img_width', 'img_height', 'img_bits',
338 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
339 array( 'img_name' => $this->name
), __METHOD__
);
341 $this->fromSharedDirectory
= false;
342 $this->fileExists
= true;
343 $this->loadFromRow( $row );
344 $this->imagePath
= $this->getFullPath();
345 // Check for rows from a previous schema, quietly upgrade them
346 if ( is_null($this->type
) ) {
349 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
350 # In case we're on a wgCapitalLinks=false wiki, we
351 # capitalize the first letter of the filename before
352 # looking it up in the shared repository.
353 $name = $wgContLang->ucfirst($this->name
);
354 $dbc = Image
::getCommonsDB();
356 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
358 'img_size', 'img_width', 'img_height', 'img_bits',
359 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
360 array( 'img_name' => $name ), __METHOD__
);
362 $this->fromSharedDirectory
= true;
363 $this->fileExists
= true;
364 $this->imagePath
= $this->getFullPath(true);
366 $this->loadFromRow( $row );
368 // Check for rows from a previous schema, quietly upgrade them
369 if ( is_null($this->type
) ) {
381 $this->fileExists
= false;
382 $this->fromSharedDirectory
= false;
383 $this->metadata
= serialize ( array() ) ;
387 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
388 $this->dataLoaded
= true;
389 wfProfileOut( __METHOD__
);
393 * Load image metadata from a DB result row
395 function loadFromRow( &$row ) {
396 $this->size
= $row->img_size
;
397 $this->width
= $row->img_width
;
398 $this->height
= $row->img_height
;
399 $this->bits
= $row->img_bits
;
400 $this->type
= $row->img_media_type
;
402 $major= $row->img_major_mime
;
403 $minor= $row->img_minor_mime
;
405 if (!$major) $this->mime
= "unknown/unknown";
407 if (!$minor) $minor= "unknown";
408 $this->mime
= $major.'/'.$minor;
411 $this->metadata
= $row->img_metadata
;
412 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
414 $this->dataLoaded
= true;
418 * Load image metadata from cache or DB, unless already loaded
421 global $wgSharedUploadDBname, $wgUseSharedUploads;
422 if ( !$this->dataLoaded
) {
423 if ( !$this->loadFromCache() ) {
425 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
426 $this->loadFromFile();
427 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
428 // We can do negative caching for local images, because the cache
429 // will be purged on upload. But we can't do it when shared images
430 // are enabled, since updates to that won't purge foreign caches.
431 $this->saveToCache();
434 $this->dataLoaded
= true;
439 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
440 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
442 function upgradeRow() {
443 global $wgDBname, $wgSharedUploadDBname;
444 wfProfileIn( __METHOD__
);
446 $this->loadFromFile();
448 if ( $this->fromSharedDirectory
) {
449 if ( !$wgSharedUploadDBname ) {
450 wfProfileOut( __METHOD__
);
454 // Write to the other DB using selectDB, not database selectors
455 // This avoids breaking replication in MySQL
456 $dbw = Image
::getCommonsDB();
458 $dbw = wfGetDB( DB_MASTER
);
461 $this->checkDBSchema($dbw);
463 list( $major, $minor ) = self
::splitMime( $this->mime
);
465 wfDebug(__METHOD__
.': upgrading '.$this->name
." to 1.5 schema\n");
467 $dbw->update( 'image',
469 'img_width' => $this->width
,
470 'img_height' => $this->height
,
471 'img_bits' => $this->bits
,
472 'img_media_type' => $this->type
,
473 'img_major_mime' => $major,
474 'img_minor_mime' => $minor,
475 'img_metadata' => $this->metadata
,
476 ), array( 'img_name' => $this->name
), __METHOD__
478 if ( $this->fromSharedDirectory
) {
479 $dbw->selectDB( $wgDBname );
481 wfProfileOut( __METHOD__
);
485 * Split an internet media type into its two components; if not
486 * a two-part name, set the minor type to 'unknown'.
488 * @param $mime "text/html" etc
489 * @return array ("text", "html") etc
491 static function splitMime( $mime ) {
492 if( strpos( $mime, '/' ) !== false ) {
493 return explode( '/', $mime, 2 );
495 return array( $mime, 'unknown' );
500 * Return the name of this image
508 * Return the associated title object
511 function getTitle() {
516 * Return the URL of the image file
522 if($this->fileExists
) {
523 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
531 function getViewURL() {
532 if( $this->mustRender()) {
533 if( $this->canRender() ) {
534 return $this->createThumb( $this->getWidth() );
537 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
538 return $this->getURL(); #hm... return NULL?
541 return $this->getURL();
546 * Return the image path of the image in the
547 * local file system as an absolute path
550 function getImagePath() {
552 return $this->imagePath
;
556 * Return the width of the image
558 * Returns -1 if the file specified is not a known image type
561 function getWidth() {
567 * Return the height of the image
569 * Returns -1 if the file specified is not a known image type
572 function getHeight() {
574 return $this->height
;
578 * Return the size of the image file, in bytes
587 * Returns the mime type of the file.
589 function getMimeType() {
595 * Return the type of the media in the file.
596 * Use the value returned by this function with the MEDIATYPE_xxx constants.
598 function getMediaType() {
604 * Checks if the file can be presented to the browser as a bitmap.
606 * Currently, this checks if the file is an image format
607 * that can be converted to a format
608 * supported by all browsers (namely GIF, PNG and JPEG),
609 * or if it is an SVG image and SVG conversion is enabled.
611 * @todo remember the result of this check.
613 function canRender() {
614 global $wgUseImageMagick, $wgDjvuRenderer;
616 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
618 $mime= $this->getMimeType();
620 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
622 #if it's SVG, check if there's a converter enabled
623 if ($mime === 'image/svg') {
624 global $wgSVGConverters, $wgSVGConverter;
626 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
627 wfDebug( "Image::canRender: SVG is ready!\n" );
630 wfDebug( "Image::canRender: SVG renderer missing\n" );
634 #image formats available on ALL browsers
635 if ( $mime === 'image/gif'
636 ||
$mime === 'image/png'
637 ||
$mime === 'image/jpeg' ) return true;
639 #image formats that can be converted to the above formats
640 if ($wgUseImageMagick) {
641 #convertable by ImageMagick (there are more...)
642 if ( $mime === 'image/vnd.wap.wbmp'
643 ||
$mime === 'image/x-xbitmap'
644 ||
$mime === 'image/x-xpixmap'
645 #|| $mime === 'image/x-icon' #file may be split into multiple parts
646 ||
$mime === 'image/x-portable-anymap'
647 ||
$mime === 'image/x-portable-bitmap'
648 ||
$mime === 'image/x-portable-graymap'
649 ||
$mime === 'image/x-portable-pixmap'
650 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
651 ||
$mime === 'image/x-rgb'
652 ||
$mime === 'image/x-bmp'
653 ||
$mime === 'image/tiff' ) return true;
656 #convertable by the PHP GD image lib
657 if ( $mime === 'image/vnd.wap.wbmp'
658 ||
$mime === 'image/x-xbitmap' ) return true;
660 if ( $mime === 'image/vnd.djvu' && isset( $wgDjvuRenderer ) && $wgDjvuRenderer ) return true;
667 * Return true if the file is of a type that can't be directly
668 * rendered by typical browsers and needs to be re-rasterized.
670 * This returns true for everything but the bitmap types
671 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
672 * also return true for any non-image formats.
676 function mustRender() {
677 $mime= $this->getMimeType();
679 if ( $mime === "image/gif"
680 ||
$mime === "image/png"
681 ||
$mime === "image/jpeg" ) return false;
687 * Determines if this media file may be shown inline on a page.
689 * This is currently synonymous to canRender(), but this could be
690 * extended to also allow inline display of other media,
691 * like flash animations or videos. If you do so, please keep in mind that
692 * that could be a security risk.
694 function allowInlineDisplay() {
695 return $this->canRender();
699 * Determines if this media file is in a format that is unlikely to
700 * contain viruses or malicious content. It uses the global
701 * $wgTrustedMediaFormats list to determine if the file is safe.
703 * This is used to show a warning on the description page of non-safe files.
704 * It may also be used to disallow direct [[media:...]] links to such files.
706 * Note that this function will always return true if allowInlineDisplay()
707 * or isTrustedFile() is true for this file.
709 function isSafeFile() {
710 if ($this->allowInlineDisplay()) return true;
711 if ($this->isTrustedFile()) return true;
713 global $wgTrustedMediaFormats;
715 $type= $this->getMediaType();
716 $mime= $this->getMimeType();
717 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
719 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
720 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
722 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
723 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
728 /** Returns true if the file is flagged as trusted. Files flagged that way
729 * can be linked to directly, even if that is not allowed for this type of
732 * This is a dummy function right now and always returns false. It could be
733 * implemented to extract a flag from the database. The trusted flag could be
734 * set on upload, if the user has sufficient privileges, to bypass script-
735 * and html-filters. It may even be coupled with cryptographics signatures
738 function isTrustedFile() {
739 #this could be implemented to check a flag in the databas,
740 #look for signatures, etc
745 * Return the escapeLocalURL of this image
748 function getEscapeLocalURL( $query=false) {
750 if ( $query === false ) {
751 if ( $this->page
!= 1 ) {
752 $query = 'page=' . $this->page
;
757 return $this->title
->escapeLocalURL( $query );
761 * Return the escapeFullURL of this image
764 function getEscapeFullURL() {
766 return $this->title
->escapeFullURL();
770 * Return the URL of an image, provided its name.
772 * @param string $name Name of the image, without the leading "Image:"
773 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
774 * @return string URL of $name image
778 function imageUrl( $name, $fromSharedDirectory = false ) {
779 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
780 if($fromSharedDirectory) {
782 $path = $wgSharedUploadPath;
784 $base = $wgUploadBaseUrl;
785 $path = $wgUploadPath;
787 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
788 return wfUrlencode( $url );
792 * Returns true if the image file exists on disk.
793 * @return boolean Whether image file exist on disk.
798 return $this->fileExists
;
805 function thumbUrl( $width, $subdir='thumb') {
806 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
807 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
809 // Generate thumb.php URL if possible
813 if ( $this->fromSharedDirectory
) {
814 if ( $wgSharedThumbnailScriptPath ) {
815 $script = $wgSharedThumbnailScriptPath;
818 if ( $wgThumbnailScriptPath ) {
819 $script = $wgThumbnailScriptPath;
823 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
824 if( $this->mustRender() ) {
828 $name = $this->thumbName( $width );
829 if($this->fromSharedDirectory
) {
831 $path = $wgSharedUploadPath;
833 $base = $wgUploadBaseUrl;
834 $path = $wgUploadPath;
836 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
837 $url = "{$base}{$path}/{$subdir}" .
838 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
839 . $this->name
.'/'.$name;
840 $url = wfUrlencode( $url );
842 $url = "{$base}{$path}/{$subdir}/{$name}";
845 return array( $script !== false, $url );
849 * Return the file name of a thumbnail of the specified width
851 * @param integer $width Width of the thumbnail image
852 * @param boolean $shared Does the thumbnail come from the shared repository?
855 function thumbName( $width ) {
856 $thumb = $width."px-".$this->name
;
857 if ( $this->page
!= 1 ) {
858 $thumb = "page{$this->page}-$thumb";
861 if( $this->mustRender() ) {
862 if( $this->canRender() ) {
863 # Rasterize to PNG (for SVG vector images, etc)
867 #should we use iconThumb here to get a symbolic thumbnail?
868 #or should we fail with an internal error?
869 return NULL; //can't make bitmap
876 * Create a thumbnail of the image having the specified width/height.
877 * The thumbnail will not be created if the width is larger than the
878 * image's width. Let the browser do the scaling in this case.
879 * The thumbnail is stored on disk and is only computed if the thumbnail
880 * file does not exist OR if it is older than the image.
883 * Keeps aspect ratio of original image. If both width and height are
884 * specified, the generated image will be no bigger than width x height,
885 * and will also have correct aspect ratio.
887 * @param integer $width maximum width of the generated thumbnail
888 * @param integer $height maximum height of the image (optional)
891 function createThumb( $width, $height=-1 ) {
892 $thumb = $this->getThumbnail( $width, $height );
893 if( is_null( $thumb ) ) return '';
894 return $thumb->getUrl();
898 * As createThumb, but returns a ThumbnailImage object. This can
899 * provide access to the actual file, the real size of the thumb,
900 * and can produce a convenient <img> tag for you.
902 * For non-image formats, this may return a filetype-specific icon.
904 * @param integer $width maximum width of the generated thumbnail
905 * @param integer $height maximum height of the image (optional)
906 * @param boolean $render True to render the thumbnail if it doesn't exist,
907 * false to just return the URL
909 * @return ThumbnailImage or null on failure
912 function getThumbnail( $width, $height=-1, $render = true ) {
913 wfProfileIn( __METHOD__
);
914 if ($this->canRender()) {
917 if ( $width > $this->width
* $height / $this->height
) {
918 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
922 $thumb = $this->renderThumb( $width );
924 // Don't render, just return the URL
925 if ( $this->validateThumbParams( $width, $height ) ) {
926 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
927 $url = $this->getURL();
929 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $width );
931 $thumb = new ThumbnailImage( $url, $width, $height );
937 // not a bitmap or renderable image, don't try.
938 $thumb = $this->iconThumb();
940 wfProfileOut( __METHOD__
);
945 * @return ThumbnailImage
947 function iconThumb() {
948 global $wgStylePath, $wgStyleDirectory;
950 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
951 foreach( $try as $icon ) {
952 $path = '/common/images/icons/' . $icon;
953 $filepath = $wgStyleDirectory . $path;
954 if( file_exists( $filepath ) ) {
955 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
962 * Validate thumbnail parameters and fill in the correct height
964 * @param integer &$width Specified width (input/output)
965 * @param integer &$height Height (output only)
966 * @return false to indicate that an error should be returned to the user.
968 function validateThumbParams( &$width, &$height ) {
969 global $wgSVGMaxSize, $wgMaxImageArea;
973 if ( ! $this->exists() )
975 # If there is no image, there will be no thumbnail
979 $width = intval( $width );
981 # Sanity check $width
982 if( $width <= 0 ||
$this->width
<= 0) {
987 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
988 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
989 # an exception for it.
990 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
991 $this->getMimeType() !== 'image/jpeg' &&
992 $this->width
* $this->height
> $wgMaxImageArea )
997 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
998 if ( $this->mustRender() ) {
999 $width = min( $width, $wgSVGMaxSize );
1000 } elseif ( $width > $this->width
- 1 ) {
1001 $width = $this->width
;
1002 $height = $this->height
;
1006 $height = round( $this->height
* $width / $this->width
);
1011 * Create a thumbnail of the image having the specified width.
1012 * The thumbnail will not be created if the width is larger than the
1013 * image's width. Let the browser do the scaling in this case.
1014 * The thumbnail is stored on disk and is only computed if the thumbnail
1015 * file does not exist OR if it is older than the image.
1016 * Returns an object which can return the pathname, URL, and physical
1017 * pixel size of the thumbnail -- or null on failure.
1019 * @return ThumbnailImage or null on failure
1022 function renderThumb( $width, $useScript = true ) {
1023 global $wgUseSquid, $wgThumbnailEpoch;
1025 wfProfileIn( __METHOD__
);
1029 if ( !$this->validateThumbParams( $width, $height ) ) {
1031 wfProfileOut( __METHOD__
);
1035 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1036 # validateThumbParams (or the user) wants us to return the unscaled image
1037 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1038 wfProfileOut( __METHOD__
);
1042 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1043 if ( $isScriptUrl && $useScript ) {
1044 // Use thumb.php to render the image
1045 $thumb = new ThumbnailImage( $url, $width, $height );
1046 wfProfileOut( __METHOD__
);
1050 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
1051 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
1052 $thumbPath = $thumbDir.'/'.$thumbName;
1054 if ( is_dir( $thumbPath ) ) {
1055 // Directory where file should be
1056 // This happened occasionally due to broken migration code in 1.5
1057 // Rename to broken-*
1058 global $wgUploadDirectory;
1059 for ( $i = 0; $i < 100 ; $i++
) {
1060 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1061 if ( !file_exists( $broken ) ) {
1062 rename( $thumbPath, $broken );
1066 // Code below will ask if it exists, and the answer is now no
1071 if ( !file_exists( $thumbPath ) ||
1072 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1074 // Create the directory if it doesn't exist
1075 if ( is_file( $thumbDir ) ) {
1076 // File where thumb directory should be, destroy if possible
1077 @unlink
( $thumbDir );
1079 wfMkdirParents( $thumbDir );
1081 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1085 // Migration from old directory structure
1086 if ( is_file( $oldThumbPath ) ) {
1087 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1088 if ( file_exists( $thumbPath ) ) {
1089 if ( !is_dir( $thumbPath ) ) {
1090 // Old image in the way of rename
1091 unlink( $thumbPath );
1093 // This should have been dealt with already
1094 throw new MWException( "Directory where image should be: $thumbPath" );
1097 // Rename the old image into the new location
1098 rename( $oldThumbPath, $thumbPath );
1101 unlink( $oldThumbPath );
1105 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1106 if ( $this->lastError
=== true ) {
1108 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1109 // Log the error but output anyway.
1110 // With luck it's a transitory error...
1115 # This has to be done after the image is updated and present for all machines on NFS,
1116 # or else the old version might be stored into the squid again
1117 if ( $wgUseSquid ) {
1118 $urlArr = array( $url );
1119 wfPurgeSquidServers($urlArr);
1125 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1129 wfProfileOut( __METHOD__
);
1131 } // END OF function renderThumb
1134 * Really render a thumbnail
1135 * Call this only for images for which canRender() returns true.
1137 * @param string $thumbPath Path to thumbnail
1138 * @param int $width Desired width in pixels
1139 * @param int $height Desired height in pixels
1140 * @return bool True on error, false or error string on failure.
1143 function reallyRenderThumb( $thumbPath, $width, $height ) {
1144 global $wgSVGConverters, $wgSVGConverter;
1145 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1146 global $wgCustomConvertCommand;
1147 global $wgDjvuRenderer, $wgDjvuPostProcessor;
1155 if( $this->mime
=== "image/svg" ) {
1156 #Right now we have only SVG
1158 global $wgSVGConverters, $wgSVGConverter;
1159 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1160 global $wgSVGConverterPath;
1162 array( '$path/', '$width', '$height', '$input', '$output' ),
1163 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1166 wfEscapeShellArg( $this->imagePath
),
1167 wfEscapeShellArg( $thumbPath ) ),
1168 $wgSVGConverters[$wgSVGConverter] );
1169 wfProfileIn( 'rsvg' );
1170 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1171 $err = wfShellExec( $cmd, $retval );
1172 wfProfileOut( 'rsvg' );
1175 if ( $this->mime
=== "image/vnd.djvu" && $wgDjvuRenderer ) {
1177 // The file contains several images. First, extract the
1178 // page in hi-res, if it doesn't yet exist. Then, thumbnail
1181 $cmd = "{$wgDjvuRenderer} -page={$this->page} -size=${width}x${height} " .
1182 wfEscapeShellArg( $this->imagePath
) .
1183 " | {$wgDjvuPostProcessor} > " . wfEscapeShellArg($thumbPath);
1184 wfProfileIn( 'ddjvu' );
1185 wfDebug( "reallyRenderThumb DJVU: $cmd\n" );
1186 $err = wfShellExec( $cmd, $retval );
1187 wfProfileOut( 'ddjvu' );
1189 } elseif ( $wgUseImageMagick ) {
1192 if ( $this->mime
== 'image/jpeg' ) {
1193 $quality = "-quality 80"; // 80%
1194 } elseif ( $this->mime
== 'image/png' ) {
1195 $quality = "-quality 95"; // zlib 9, adaptive filtering
1197 $quality = ''; // default
1200 # Specify white background color, will be used for transparent images
1201 # in Internet Explorer/Windows instead of default black.
1203 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1204 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1205 # the wrong size in the second case.
1207 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1208 " {$quality} -background white -size {$width} ".
1209 wfEscapeShellArg($this->imagePath
) .
1210 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1212 // For the -resize option a "!" is needed to force exact size,
1213 // or ImageMagick may decide your ratio is wrong and slice off
1215 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1217 wfEscapeShellArg($thumbPath) . " 2>&1";
1218 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1219 wfProfileIn( 'convert' );
1220 $err = wfShellExec( $cmd, $retval );
1221 wfProfileOut( 'convert' );
1222 } elseif( $wgCustomConvertCommand ) {
1223 # Use a custom convert command
1224 # Variables: %s %d %w %h
1225 $src = wfEscapeShellArg( $this->imagePath
);
1226 $dst = wfEscapeShellArg( $thumbPath );
1227 $cmd = $wgCustomConvertCommand;
1228 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1229 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1230 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1231 wfProfileIn( 'convert' );
1232 $err = wfShellExec( $cmd, $retval );
1233 wfProfileOut( 'convert' );
1235 # Use PHP's builtin GD library functions.
1237 # First find out what kind of file this is, and select the correct
1238 # input routine for this.
1241 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1242 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1243 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1244 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1245 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1247 if( !isset( $typemap[$this->mime
] ) ) {
1248 $err = 'Image type not supported';
1249 wfDebug( "$err\n" );
1252 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1254 if( !function_exists( $loader ) ) {
1255 $err = "Incomplete GD library configuration: missing function $loader";
1256 wfDebug( "$err\n" );
1259 if( $colorStyle == 'palette' ) {
1261 } elseif( $colorStyle == 'truecolor' ) {
1263 } elseif( $colorStyle == 'bits' ) {
1264 $truecolor = ( $this->bits
> 8 );
1267 $src_image = call_user_func( $loader, $this->imagePath
);
1269 $dst_image = imagecreatetruecolor( $width, $height );
1271 $dst_image = imagecreate( $width, $height );
1273 imagecopyresampled( $dst_image, $src_image,
1275 $width, $height, $this->width
, $this->height
);
1276 call_user_func( $saveType, $dst_image, $thumbPath );
1277 imagedestroy( $dst_image );
1278 imagedestroy( $src_image );
1283 # Check for zero-sized thumbnails. Those can be generated when
1284 # no disk space is available or some other error occurs
1286 if( file_exists( $thumbPath ) ) {
1287 $thumbstat = stat( $thumbPath );
1288 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1289 wfDebugLog( 'thumbnail',
1290 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1291 $thumbstat['size'], $thumbPath ) );
1292 unlink( $thumbPath );
1295 if ( $retval != 0 ) {
1296 wfDebugLog( 'thumbnail',
1297 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1298 wfHostname(), $retval, trim($err), $cmd ) );
1299 return wfMsg( 'thumbnail_error', $err );
1305 function getLastError() {
1306 return $this->lastError
;
1309 function imageJpegWrapper( $dst_image, $thumbPath ) {
1310 imageinterlace( $dst_image );
1311 imagejpeg( $dst_image, $thumbPath, 95 );
1315 * Get all thumbnail names previously generated for this image
1317 function getThumbnails( $shared = false ) {
1318 if ( Image
::isHashed( $shared ) ) {
1321 $dir = wfImageThumbDir( $this->name
, $shared );
1323 if ( is_dir( $dir ) ) {
1324 $handle = opendir( $dir );
1327 while ( false !== ( $file = readdir($handle) ) ) {
1328 if ( $file{0} != '.' ) {
1332 closedir( $handle );
1343 * Refresh metadata in memcached, but don't touch thumbnails or squid
1345 function purgeMetadataCache() {
1347 $this->loadFromFile();
1348 $this->saveToCache();
1352 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1354 function purgeCache( $archiveFiles = array(), $shared = false ) {
1357 // Refresh metadata cache
1358 $this->purgeMetadataCache();
1360 // Delete thumbnails
1361 $files = $this->getThumbnails( $shared );
1362 $dir = wfImageThumbDir( $this->name
, $shared );
1364 foreach ( $files as $file ) {
1366 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1367 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $m[1] );
1369 @unlink
( "$dir/$file" );
1374 if ( $wgUseSquid ) {
1375 $urls[] = $this->getURL();
1376 foreach ( $archiveFiles as $file ) {
1377 $urls[] = wfImageArchiveUrl( $file );
1379 wfPurgeSquidServers( $urls );
1384 * Purge the image description page, but don't go after
1385 * pages using the image. Use when modifying file history
1386 * but not the current data.
1388 function purgeDescription() {
1389 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1390 $page->invalidateCache();
1391 $page->purgeSquid();
1395 * Purge metadata and all affected pages when the image is created,
1396 * deleted, or majorly updated. A set of additional URLs may be
1397 * passed to purge, such as specific image files which have changed.
1398 * @param $urlArray array
1400 function purgeEverything( $urlArr=array() ) {
1401 // Delete thumbnails and refresh image metadata cache
1402 $this->purgeCache();
1403 $this->purgeDescription();
1405 // Purge cache of all pages using this image
1406 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1407 $update->doUpdate();
1410 function checkDBSchema(&$db) {
1411 static $checkDone = false;
1412 global $wgCheckDBSchema;
1413 if (!$wgCheckDBSchema ||
$checkDone) {
1416 # img_name must be unique
1417 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1418 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1422 # new fields must exist
1424 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1425 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1426 # something. The only reason I put the above schema check in was because the absence of that particular
1427 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1430 if ( !$db->fieldExists( 'image', 'img_media_type' )
1431 || !$db->fieldExists( 'image', 'img_metadata' )
1432 || !$db->fieldExists( 'image', 'img_width' ) ) {
1434 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1440 * Return the image history of this image, line by line.
1441 * starts with current version, then old versions.
1442 * uses $this->historyLine to check which line to return:
1443 * 0 return line for current version
1444 * 1 query for old versions, return first one
1445 * 2, ... return next old version from above query
1449 function nextHistoryLine() {
1450 $dbr = wfGetDB( DB_SLAVE
);
1452 $this->checkDBSchema($dbr);
1454 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1455 $this->historyRes
= $dbr->select( 'image',
1459 'img_user','img_user_text',
1463 "'' AS oi_archive_name"
1465 array( 'img_name' => $this->title
->getDBkey() ),
1468 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1471 } else if ( $this->historyLine
== 1 ) {
1472 $this->historyRes
= $dbr->select( 'oldimage',
1474 'oi_size AS img_size',
1475 'oi_description AS img_description',
1476 'oi_user AS img_user',
1477 'oi_user_text AS img_user_text',
1478 'oi_timestamp AS img_timestamp',
1479 'oi_width as img_width',
1480 'oi_height as img_height',
1483 array( 'oi_name' => $this->title
->getDBkey() ),
1485 array( 'ORDER BY' => 'oi_timestamp DESC' )
1488 $this->historyLine ++
;
1490 return $dbr->fetchObject( $this->historyRes
);
1494 * Reset the history pointer to the first element of the history
1497 function resetHistory() {
1498 $this->historyLine
= 0;
1502 * Return the full filesystem path to the file. Note that this does
1503 * not mean that a file actually exists under that location.
1505 * This path depends on whether directory hashing is active or not,
1506 * i.e. whether the images are all found in the same directory,
1507 * or in hashed paths like /images/3/3c.
1510 * @param boolean $fromSharedDirectory Return the path to the file
1511 * in a shared repository (see $wgUseSharedRepository and related
1512 * options in DefaultSettings.php) instead of a local one.
1515 function getFullPath( $fromSharedRepository = false ) {
1516 global $wgUploadDirectory, $wgSharedUploadDirectory;
1518 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1521 // $wgSharedUploadDirectory may be false, if thumb.php is used
1523 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1535 public static function isHashed( $shared ) {
1536 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1537 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1541 * Record an image upload in the upload log and the image table
1543 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1544 global $wgUser, $wgUseCopyrightUpload;
1546 $dbw = wfGetDB( DB_MASTER
);
1548 $this->checkDBSchema($dbw);
1550 // Delete thumbnails and refresh the metadata cache
1551 $this->purgeCache();
1553 // Fail now if the image isn't there
1554 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1555 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1559 if ( $wgUseCopyrightUpload ) {
1560 if ( $license != '' ) {
1561 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1563 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1564 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1566 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1568 if ( $license != '' ) {
1569 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1570 $textdesc = $filedesc .
1571 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1577 $now = $dbw->timestamp();
1580 if (strpos($this->mime
,'/')!==false) {
1581 list($major,$minor)= explode('/',$this->mime
,2);
1584 $major= $this->mime
;
1588 # Test to see if the row exists using INSERT IGNORE
1589 # This avoids race conditions by locking the row until the commit, and also
1590 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1591 $dbw->insert( 'image',
1593 'img_name' => $this->name
,
1594 'img_size'=> $this->size
,
1595 'img_width' => intval( $this->width
),
1596 'img_height' => intval( $this->height
),
1597 'img_bits' => $this->bits
,
1598 'img_media_type' => $this->type
,
1599 'img_major_mime' => $major,
1600 'img_minor_mime' => $minor,
1601 'img_timestamp' => $now,
1602 'img_description' => $desc,
1603 'img_user' => $wgUser->getID(),
1604 'img_user_text' => $wgUser->getName(),
1605 'img_metadata' => $this->metadata
,
1611 if( $dbw->affectedRows() == 0 ) {
1612 # Collision, this is an update of an image
1613 # Insert previous contents into oldimage
1614 $dbw->insertSelect( 'oldimage', 'image',
1616 'oi_name' => 'img_name',
1617 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1618 'oi_size' => 'img_size',
1619 'oi_width' => 'img_width',
1620 'oi_height' => 'img_height',
1621 'oi_bits' => 'img_bits',
1622 'oi_timestamp' => 'img_timestamp',
1623 'oi_description' => 'img_description',
1624 'oi_user' => 'img_user',
1625 'oi_user_text' => 'img_user_text',
1626 ), array( 'img_name' => $this->name
), __METHOD__
1629 # Update the current image row
1630 $dbw->update( 'image',
1632 'img_size' => $this->size
,
1633 'img_width' => intval( $this->width
),
1634 'img_height' => intval( $this->height
),
1635 'img_bits' => $this->bits
,
1636 'img_media_type' => $this->type
,
1637 'img_major_mime' => $major,
1638 'img_minor_mime' => $minor,
1639 'img_timestamp' => $now,
1640 'img_description' => $desc,
1641 'img_user' => $wgUser->getID(),
1642 'img_user_text' => $wgUser->getName(),
1643 'img_metadata' => $this->metadata
,
1644 ), array( /* WHERE */
1645 'img_name' => $this->name
1649 # This is a new image
1650 # Update the image count
1651 $site_stats = $dbw->tableName( 'site_stats' );
1652 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1655 $descTitle = $this->getTitle();
1656 $article = new Article( $descTitle );
1658 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1659 $suppressRC = true; // There's already a log entry, so don't double the RC load
1661 if( $descTitle->exists() ) {
1662 // TODO: insert a null revision into the page history for this update.
1664 $wgUser->addWatch( $descTitle );
1667 # Invalidate the cache for the description page
1668 $descTitle->invalidateCache();
1669 $descTitle->purgeSquid();
1671 // New image; create the description page.
1672 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1676 $log = new LogPage( 'upload' );
1677 $log->addEntry( 'upload', $descTitle, $desc );
1679 # Commit the transaction now, in case something goes wrong later
1680 # The most important thing is that images don't get lost, especially archives
1681 $dbw->immediateCommit();
1683 # Invalidate cache for all pages using this image
1684 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1685 $update->doUpdate();
1691 * Get an array of Title objects which are articles which use this image
1692 * Also adds their IDs to the link cache
1694 * This is mostly copied from Title::getLinksTo()
1696 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1698 function getLinksTo( $options = '' ) {
1699 wfProfileIn( __METHOD__
);
1702 $db = wfGetDB( DB_MASTER
);
1704 $db = wfGetDB( DB_SLAVE
);
1706 $linkCache =& LinkCache
::singleton();
1708 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1709 $encName = $db->addQuotes( $this->name
);
1710 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1711 $res = $db->query( $sql, __METHOD__
);
1714 if ( $db->numRows( $res ) ) {
1715 while ( $row = $db->fetchObject( $res ) ) {
1716 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1717 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1718 $retVal[] = $titleObj;
1722 $db->freeResult( $res );
1723 wfProfileOut( __METHOD__
);
1728 * Retrive Exif data from the file and prune unrecognized tags
1729 * and/or tags with invalid contents
1734 private function retrieveExifData( $filename ) {
1738 if ( $this->getMimeType() !== "image/jpeg" )
1742 if( $wgShowEXIF && file_exists( $filename ) ) {
1743 $exif = new Exif( $filename );
1744 return $exif->getFilteredData();
1750 function getExifData() {
1752 if ( $this->metadata
=== '0' ||
$this->mime
== 'image/vnd.djvu' )
1755 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1756 $ret = unserialize( $this->metadata
);
1758 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1759 $newver = Exif
::version();
1761 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1762 $this->purgeMetadataCache();
1763 $this->updateExifData( $newver );
1765 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1766 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1767 $format = new FormatExif( $ret );
1769 return $format->getFormattedData();
1772 function updateExifData( $version ) {
1773 if ( $this->getImagePath() === false ) # Not a local image
1776 # Get EXIF data from image
1777 $exif = $this->retrieveExifData( $this->imagePath
);
1778 if ( count( $exif ) ) {
1779 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1780 $this->metadata
= serialize( $exif );
1782 $this->metadata
= '0';
1785 # Update EXIF data in database
1786 $dbw = wfGetDB( DB_MASTER
);
1788 $this->checkDBSchema($dbw);
1790 $dbw->update( 'image',
1791 array( 'img_metadata' => $this->metadata
),
1792 array( 'img_name' => $this->name
),
1798 * Returns true if the image does not come from the shared
1803 function isLocal() {
1804 return !$this->fromSharedDirectory
;
1808 * Was this image ever deleted from the wiki?
1812 function wasDeleted() {
1813 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1814 return ( $title->isDeleted() > 0 );
1818 * Delete all versions of the image.
1820 * Moves the files into an archive directory (or deletes them)
1821 * and removes the database rows.
1823 * Cache purging is done; logging is caller's responsibility.
1826 * @return true on success, false on some kind of failure
1828 function delete( $reason, $suppress=false ) {
1829 $transaction = new FSTransaction();
1830 $urlArr = array( $this->getURL() );
1832 if( !FileStore
::lock() ) {
1833 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1838 $dbw = wfGetDB( DB_MASTER
);
1841 // Delete old versions
1842 $result = $dbw->select( 'oldimage',
1843 array( 'oi_archive_name' ),
1844 array( 'oi_name' => $this->name
) );
1846 while( $row = $dbw->fetchObject( $result ) ) {
1847 $oldName = $row->oi_archive_name
;
1849 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1851 // We'll need to purge this URL from caches...
1852 $urlArr[] = wfImageArchiveUrl( $oldName );
1854 $dbw->freeResult( $result );
1856 // And the current version...
1857 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1859 $dbw->immediateCommit();
1860 } catch( MWException
$e ) {
1861 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1862 $transaction->rollback();
1863 FileStore
::unlock();
1867 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1868 $transaction->commit();
1869 FileStore
::unlock();
1872 // Update site_stats
1873 $site_stats = $dbw->tableName( 'site_stats' );
1874 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1876 $this->purgeEverything( $urlArr );
1883 * Delete an old version of the image.
1885 * Moves the file into an archive directory (or deletes it)
1886 * and removes the database row.
1888 * Cache purging is done; logging is caller's responsibility.
1891 * @throws MWException or FSException on database or filestore failure
1892 * @return true on success, false on some kind of failure
1894 function deleteOld( $archiveName, $reason, $suppress=false ) {
1895 $transaction = new FSTransaction();
1898 if( !FileStore
::lock() ) {
1899 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1903 $transaction = new FSTransaction();
1905 $dbw = wfGetDB( DB_MASTER
);
1907 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1908 $dbw->immediateCommit();
1909 } catch( MWException
$e ) {
1910 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1911 $transaction->rollback();
1912 FileStore
::unlock();
1916 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1917 $transaction->commit();
1918 FileStore
::unlock();
1920 $this->purgeDescription();
1924 if ( $wgUseSquid ) {
1926 wfImageArchiveUrl( $archiveName ),
1928 wfPurgeSquidServers( $urlArr );
1934 * Delete the current version of a file.
1935 * May throw a database error.
1936 * @return true on success, false on failure
1938 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1939 return $this->prepareDeleteVersion(
1940 $this->getFullPath(),
1944 'fa_name' => 'img_name',
1945 'fa_archive_name' => 'NULL',
1946 'fa_size' => 'img_size',
1947 'fa_width' => 'img_width',
1948 'fa_height' => 'img_height',
1949 'fa_metadata' => 'img_metadata',
1950 'fa_bits' => 'img_bits',
1951 'fa_media_type' => 'img_media_type',
1952 'fa_major_mime' => 'img_major_mime',
1953 'fa_minor_mime' => 'img_minor_mime',
1954 'fa_description' => 'img_description',
1955 'fa_user' => 'img_user',
1956 'fa_user_text' => 'img_user_text',
1957 'fa_timestamp' => 'img_timestamp' ),
1958 array( 'img_name' => $this->name
),
1964 * Delete a given older version of a file.
1965 * May throw a database error.
1966 * @return true on success, false on failure
1968 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1969 $oldpath = wfImageArchiveDir( $this->name
) .
1970 DIRECTORY_SEPARATOR
. $archiveName;
1971 return $this->prepareDeleteVersion(
1976 'fa_name' => 'oi_name',
1977 'fa_archive_name' => 'oi_archive_name',
1978 'fa_size' => 'oi_size',
1979 'fa_width' => 'oi_width',
1980 'fa_height' => 'oi_height',
1981 'fa_metadata' => 'NULL',
1982 'fa_bits' => 'oi_bits',
1983 'fa_media_type' => 'NULL',
1984 'fa_major_mime' => 'NULL',
1985 'fa_minor_mime' => 'NULL',
1986 'fa_description' => 'oi_description',
1987 'fa_user' => 'oi_user',
1988 'fa_user_text' => 'oi_user_text',
1989 'fa_timestamp' => 'oi_timestamp' ),
1991 'oi_name' => $this->name
,
1992 'oi_archive_name' => $archiveName ),
1998 * Do the dirty work of backing up an image row and its file
1999 * (if $wgSaveDeletedFiles is on) and removing the originals.
2001 * Must be run while the file store is locked and a database
2002 * transaction is open to avoid race conditions.
2004 * @return FSTransaction
2006 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
2007 global $wgUser, $wgSaveDeletedFiles;
2009 // Dupe the file into the file store
2010 if( file_exists( $path ) ) {
2011 if( $wgSaveDeletedFiles ) {
2014 $store = FileStore
::get( $group );
2015 $key = FileStore
::calculateKey( $path, $this->extension
);
2016 $transaction = $store->insert( $key, $path,
2017 FileStore
::DELETE_ORIGINAL
);
2021 $transaction = FileStore
::deleteFile( $path );
2024 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
2027 $transaction = new FSTransaction(); // empty
2030 if( $transaction === false ) {
2032 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
2033 throw new MWException( "Could not archive and delete file $path" );
2037 // Bitfields to further supress the image content
2038 // Note that currently, live images are stored elsewhere
2039 // and cannot be partially deleted
2042 $bitfield |
= self
::DELETED_FILE
;
2043 $bitfield |
= self
::DELETED_COMMENT
;
2044 $bitfield |
= self
::DELETED_USER
;
2045 $bitfield |
= self
::DELETED_RESTRICTED
;
2048 $dbw = wfGetDB( DB_MASTER
);
2049 $storageMap = array(
2050 'fa_storage_group' => $dbw->addQuotes( $group ),
2051 'fa_storage_key' => $dbw->addQuotes( $key ),
2053 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2054 'fa_deleted_timestamp' => $dbw->timestamp(),
2055 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
2056 'fa_deleted' => $bitfield);
2057 $allFields = array_merge( $storageMap, $fieldMap );
2060 if( $wgSaveDeletedFiles ) {
2061 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2063 $dbw->delete( $table, $where, $fname );
2064 } catch( DBQueryError
$e ) {
2065 // Something went horribly wrong!
2066 // Leave the file as it was...
2067 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
2068 $transaction->rollback();
2072 return $transaction;
2076 * Restore all or specified deleted revisions to the given file.
2077 * Permissions and logging are left to the caller.
2079 * May throw database exceptions on error.
2081 * @param $versions set of record ids of deleted items to restore,
2082 * or empty to restore all revisions.
2083 * @return the number of file revisions restored if successful,
2084 * or false on failure
2086 function restore( $versions=array(), $Unsuppress=false ) {
2089 if( !FileStore
::lock() ) {
2090 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
2094 $transaction = new FSTransaction();
2096 $dbw = wfGetDB( DB_MASTER
);
2099 // Re-confirm whether this image presently exists;
2100 // if no we'll need to create an image record for the
2101 // first item we restore.
2102 $exists = $dbw->selectField( 'image', '1',
2103 array( 'img_name' => $this->name
),
2106 // Fetch all or selected archived revisions for the file,
2107 // sorted from the most recent to the oldest.
2108 $conditions = array( 'fa_name' => $this->name
);
2110 $conditions['fa_id'] = $versions;
2113 $result = $dbw->select( 'filearchive', '*',
2116 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2118 if( $dbw->numRows( $result ) < count( $versions ) ) {
2119 // There's some kind of conflict or confusion;
2120 // we can't restore everything we were asked to.
2121 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2123 FileStore
::unlock();
2127 if( $dbw->numRows( $result ) == 0 ) {
2129 wfDebug( __METHOD__
.": nothing to do\n" );
2131 FileStore
::unlock();
2136 while( $row = $dbw->fetchObject( $result ) ) {
2137 if ( $Unsuppress ) {
2138 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
2139 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
2140 // Skip restoring file revisions that the user cannot restore
2144 $store = FileStore
::get( $row->fa_storage_group
);
2146 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2150 if( $revisions == 1 && !$exists ) {
2151 $destDir = wfImageDir( $row->fa_name
);
2152 if ( !is_dir( $destDir ) ) {
2153 wfMkdirParents( $destDir );
2155 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2157 // We may have to fill in data if this was originally
2158 // an archived file revision.
2159 if( is_null( $row->fa_metadata
) ) {
2160 $tempFile = $store->filePath( $row->fa_storage_key
);
2161 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2163 $magic = MimeMagic
::singleton();
2164 $mime = $magic->guessMimeType( $tempFile, true );
2165 $media_type = $magic->getMediaType( $tempFile, $mime );
2166 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2168 $metadata = $row->fa_metadata
;
2169 $major_mime = $row->fa_major_mime
;
2170 $minor_mime = $row->fa_minor_mime
;
2171 $media_type = $row->fa_media_type
;
2176 'img_name' => $row->fa_name
,
2177 'img_size' => $row->fa_size
,
2178 'img_width' => $row->fa_width
,
2179 'img_height' => $row->fa_height
,
2180 'img_metadata' => $metadata,
2181 'img_bits' => $row->fa_bits
,
2182 'img_media_type' => $media_type,
2183 'img_major_mime' => $major_mime,
2184 'img_minor_mime' => $minor_mime,
2185 'img_description' => $row->fa_description
,
2186 'img_user' => $row->fa_user
,
2187 'img_user_text' => $row->fa_user_text
,
2188 'img_timestamp' => $row->fa_timestamp
);
2190 $archiveName = $row->fa_archive_name
;
2191 if( $archiveName == '' ) {
2192 // This was originally a current version; we
2193 // have to devise a new archive name for it.
2194 // Format is <timestamp of archiving>!<name>
2196 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2197 '!' . $row->fa_name
;
2199 $destDir = wfImageArchiveDir( $row->fa_name
);
2200 if ( !is_dir( $destDir ) ) {
2201 wfMkdirParents( $destDir );
2203 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2205 $table = 'oldimage';
2207 'oi_name' => $row->fa_name
,
2208 'oi_archive_name' => $archiveName,
2209 'oi_size' => $row->fa_size
,
2210 'oi_width' => $row->fa_width
,
2211 'oi_height' => $row->fa_height
,
2212 'oi_bits' => $row->fa_bits
,
2213 'oi_description' => $row->fa_description
,
2214 'oi_user' => $row->fa_user
,
2215 'oi_user_text' => $row->fa_user_text
,
2216 'oi_timestamp' => $row->fa_timestamp
);
2219 $dbw->insert( $table, $fields, __METHOD__
);
2220 /// @fixme this delete is not totally safe, potentially
2221 $dbw->delete( 'filearchive',
2222 array( 'fa_id' => $row->fa_id
),
2225 // Check if any other stored revisions use this file;
2226 // if so, we shouldn't remove the file from the deletion
2227 // archives so they will still work.
2228 $useCount = $dbw->selectField( 'filearchive',
2231 'fa_storage_group' => $row->fa_storage_group
,
2232 'fa_storage_key' => $row->fa_storage_key
),
2234 if( $useCount == 0 ) {
2235 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2236 $flags = FileStore
::DELETE_ORIGINAL
;
2241 $transaction->add( $store->export( $row->fa_storage_key
,
2242 $destPath, $flags ) );
2245 $dbw->immediateCommit();
2246 } catch( MWException
$e ) {
2247 wfDebug( __METHOD__
." caught error, aborting\n" );
2248 $transaction->rollback();
2252 $transaction->commit();
2253 FileStore
::unlock();
2255 if( $revisions > 0 ) {
2257 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2259 // Update site_stats
2260 $site_stats = $dbw->tableName( 'site_stats' );
2261 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2263 $this->purgeEverything();
2265 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2266 $this->purgeDescription();
2274 * Select a page from a multipage document. Determines the page used for
2275 * rendering thumbnails.
2277 * @param $page Integer: page number, starting with 1
2279 function selectPage( $page ) {
2280 if( $this->initializeMultiPageXML() ) {
2281 wfDebug( __METHOD__
." selecting page $page \n" );
2282 $this->page
= $page;
2283 $o = $this->multiPageXML
->BODY
[0]->OBJECT[$page-1];
2284 $this->height
= intval( $o['height'] );
2285 $this->width
= intval( $o['width'] );
2287 wfDebug( __METHOD__
." selectPage($page) for bogus multipage xml on '$this->name'\n" );
2293 * Lazy-initialize multipage XML metadata for DjVu files.
2294 * @return bool true if $this->multiPageXML is set up and ready;
2295 * false if corrupt or otherwise failing
2297 function initializeMultiPageXML() {
2299 if ( isset( $this->multiPageXML
) ) {
2304 # Check for files uploaded prior to DJVU support activation,
2307 if( empty( $this->metadata
) ||
$this->metadata
== serialize( array() ) ) {
2308 $deja = new DjVuImage( $this->imagePath
);
2309 $this->metadata
= $deja->retrieveMetaData();
2310 $this->purgeMetadataCache();
2312 # Update metadata in the database
2313 $dbw = wfGetDB( DB_MASTER
);
2314 $dbw->update( 'image',
2315 array( 'img_metadata' => $this->metadata
),
2316 array( 'img_name' => $this->name
),
2320 wfSuppressWarnings();
2322 $this->multiPageXML
= new SimpleXMLElement( $this->metadata
);
2323 } catch( Exception
$e ) {
2324 wfDebug( "Bogus multipage XML metadata on '$this->name'\n" );
2325 $this->multiPageXML
= null;
2327 wfRestoreWarnings();
2328 return isset( $this->multiPageXML
);
2332 * Returns 'true' if this image is a multipage document, e.g. a DJVU
2337 function isMultipage() {
2338 return ( $this->mime
== 'image/vnd.djvu' );
2342 * Returns the number of pages of a multipage document, or NULL for
2343 * documents which aren't multipage documents
2345 function pageCount() {
2346 if ( ! $this->isMultipage() ) {
2349 if( $this->initializeMultiPageXML() ) {
2350 return count( $this->multiPageXML
->xpath( '//OBJECT' ) );
2352 wfDebug( "Requested pageCount() for bogus multi-page metadata for '$this->name'\n" );
2357 static function getCommonsDB() {
2359 global $wgLoadBalancer, $wgSharedUploadDBname;
2360 if ( !isset( $dbc ) ) {
2361 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
2362 $dbinfo = $wgLoadBalancer->mServers
[$i];
2363 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
2364 $dbinfo['password'], $wgSharedUploadDBname );
2374 * Returns a file object from the filearchive table
2375 * In the future, all current and old image storage
2376 * may use FileStore. There will be a "old" storage
2377 * for current and previous file revisions as well as
2378 * the "deleted" group for archived revisions
2379 * @param $title, the corresponding image page title
2380 * @param $id, the image id, a unique key
2381 * @param $key, optional storage key
2382 * @return ResultWrapper
2384 function ArchivedFile( $title, $id=0, $key='' ) {
2385 if( !is_object( $title ) ) {
2386 throw new MWException( 'Image constructor given bogus title.' );
2388 $conds = ($id) ?
"fa_id = $id" : "fa_storage_key = '$key'";
2389 if( $title->getNamespace() == NS_IMAGE
) {
2390 $dbr = wfGetDB( DB_SLAVE
);
2391 $res = $dbr->select( 'filearchive',
2411 'fa_name' => $title->getDbKey(),
2414 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2416 if ( $dbr->numRows( $res ) == 0 ) {
2417 // this revision does not exist?
2420 $ret = $dbr->resultObject( $res );
2421 $row = $ret->fetchObject();
2423 // initialize fields for filestore image object
2424 $this->mId
= intval($row->fa_id
);
2425 $this->mName
= $row->fa_name
;
2426 $this->mGroup
= $row->fa_storage_group
;
2427 $this->mKey
= $row->fa_storage_key
;
2428 $this->mSize
= $row->fa_size
;
2429 $this->mBits
= $row->fa_bits
;
2430 $this->mWidth
= $row->fa_width
;
2431 $this->mHeight
= $row->fa_height
;
2432 $this->mMetaData
= $row->fa_metadata
;
2433 $this->mMime
= "$row->fa_major_mime/$row->fa_minor_mime";
2434 $this->mType
= $row->fa_media_type
;
2435 $this->mDescription
= $row->fa_description
;
2436 $this->mUser
= $row->fa_user
;
2437 $this->mUserText
= $row->fa_user_text
;
2438 $this->mTimestamp
= $row->fa_timestamp
;
2439 $this->mDeleted
= $row->fa_deleted
;
2441 throw new MWException( 'This title does not correspond to an image page.' );
2448 * int $field one of DELETED_* bitfield constants
2449 * for file or revision rows
2452 function isDeleted( $field ) {
2453 return ($this->mDeleted
& $field) == $field;
2457 * Determine if the current user is allowed to view a particular
2458 * field of this FileStore image file, if it's marked as deleted.
2462 function userCan( $field ) {
2463 if( isset($this->mDeleted
) && ($this->mDeleted
& $field) == $field ) {
2466 $permission = ( $this->mDeleted
& Revision
::DELETED_RESTRICTED
) == Revision
::DELETED_RESTRICTED
2469 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2470 return $wgUser->isAllowed( $permission );
2478 * Wrapper class for thumbnail images
2480 class ThumbnailImage
{
2482 * @param string $path Filesystem path to the thumb
2483 * @param string $url URL path to the thumb
2486 function ThumbnailImage( $url, $width, $height, $path = false ) {
2488 $this->width
= round( $width );
2489 $this->height
= round( $height );
2490 # These should be integers when they get here.
2491 # If not, there's a bug somewhere. But let's at
2492 # least produce valid HTML code regardless.
2493 $this->path
= $path;
2497 * @return string The thumbnail URL
2504 * Return HTML <img ... /> tag for the thumbnail, will include
2505 * width and height attributes and a blank alt text (as required).
2507 * You can set or override additional attributes by passing an
2508 * associative array of name => data pairs. The data will be escaped
2509 * for HTML output, so should be in plaintext.
2511 * @param array $attribs
2515 function toHtml( $attribs = array() ) {
2516 $attribs['src'] = $this->url
;
2517 $attribs['width'] = $this->width
;
2518 $attribs['height'] = $this->height
;
2519 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2522 foreach( $attribs as $name => $data ) {
2523 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2532 * Aliases for backwards compatibility with 1.6
2534 define( 'MW_IMG_DELETED_FILE', Image
::DELETED_FILE
);
2535 define( 'MW_IMG_DELETED_COMMENT', Image
::DELETED_COMMENT
);
2536 define( 'MW_IMG_DELETED_USER', Image
::DELETED_USER
);
2537 define( 'MW_IMG_DELETED_RESTRICTED', Image
::DELETED_RESTRICTED
);