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 $fromInstantCommons, # load this image from the InstantCommons repository
39 $description, #added in for instantCommons
40 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
41 $historyRes, # result of the query for the image's history (nextHistoryLine)
44 $bits, # --- returned by getimagesize (loadFromXxx)
46 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
47 $mime, # MIME type, determined by MimeMagic::guessMimeType
48 $size, # Size in bytes (loadFromXxx)
50 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
51 $page, # Page to render when creating thumbnails
52 $lastError; # Error string associated with a thumbnail display error
58 * Create an Image object from an image name
60 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
63 public static function newFromName( $name ) {
64 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
65 if ( is_object( $title ) ) {
66 return new Image( $title );
73 * Obsolete factory function, use constructor
76 function newFromTitle( $title ) {
77 return new Image( $title );
80 function Image( $title ) {
81 if( !is_object( $title ) ) {
82 throw new MWException( 'Image constructor given bogus title.' );
84 $this->title
=& $title;
85 $this->name
= $title->getDBkey();
86 $this->metadata
= serialize ( array() ) ;
88 $n = strrpos( $this->name
, '.' );
89 $this->extension
= Image
::normalizeExtension( $n ?
90 substr( $this->name
, $n +
1 ) : '' );
91 $this->historyLine
= 0;
94 $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 'fromInstantCommons' => $this->fromInstantCommons
,
221 'width' => $this->width
,
222 'height' => $this->height
,
223 'bits' => $this->bits
,
224 'type' => $this->type
,
225 'mime' => $this->mime
,
226 'metadata' => $this->metadata
,
227 'size' => $this->size
);
229 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
231 // However we should clear them, so they aren't leftover
232 // if we've deleted the file.
233 $wgMemc->delete( $keys[0] );
238 * Load metadata from the file itself
240 function loadFromFile() {
241 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
242 wfProfileIn( __METHOD__
);
243 $this->imagePath
= $this->getFullPath();
244 $this->fileExists
= file_exists( $this->imagePath
);
245 $this->fromSharedDirectory
= false;
248 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
250 # If the file is not found, and a shared upload directory is used, look for it there.
251 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
252 # In case we're on a wgCapitalLinks=false wiki, we
253 # capitalize the first letter of the filename before
254 # looking it up in the shared repository.
255 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
256 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
257 if ( $this->fileExists
) {
258 $this->name
= $sharedImage->name
;
259 $this->imagePath
= $this->getFullPath(true);
260 $this->fromSharedDirectory
= true;
266 if ( $this->fileExists
) {
267 $magic=& MimeMagic
::singleton();
269 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
270 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
273 $this->size
= filesize( $this->imagePath
);
275 $magic=& MimeMagic
::singleton();
278 wfSuppressWarnings();
279 if( $this->mime
== 'image/svg' ) {
280 $gis = wfGetSVGsize( $this->imagePath
);
281 } elseif( $this->mime
== 'image/vnd.djvu' ) {
282 $deja = new DjVuImage( $this->imagePath
);
283 $gis = $deja->getImageSize();
284 } elseif ( !$magic->isPHPImageType( $this->mime
) ) {
285 # Don't try to get the width and height of sound and video files, that's bad for performance
288 $gis = getimagesize( $this->imagePath
);
292 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
296 $this->type
= MEDIATYPE_UNKNOWN
;
297 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
301 $this->width
= $gis[0];
302 $this->height
= $gis[1];
308 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
310 #NOTE: we have to set this flag early to avoid load() to be called
311 # be some of the functions below. This may lead to recursion or other bad things!
312 # as ther's only one thread of execution, this should be safe anyway.
313 $this->dataLoaded
= true;
316 if ( $this->mime
== 'image/vnd.djvu' ) {
317 $this->metadata
= $deja->retrieveMetaData();
319 $this->metadata
= serialize( $this->retrieveExifData( $this->imagePath
) );
322 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
323 else $this->bits
= 0;
325 wfProfileOut( __METHOD__
);
329 * Load image metadata from the DB
331 function loadFromDB() {
332 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang, $wgUseInstantCommons, $wgInstantCommonsServerPath, $wgUploadDirectory;
333 wfProfileIn( __METHOD__
);
335 $dbr =& wfGetDB( DB_SLAVE
);
336 $this->checkDBSchema($dbr);
338 $row = $dbr->selectRow( 'image',
339 array( 'img_size', 'img_width', 'img_height', 'img_bits',
340 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata','img_description' ),
341 array( 'img_name' => $this->name
), __METHOD__
);
343 $this->fromSharedDirectory
= false;
344 $this->fileExists
= true;
345 $this->loadFromRow( $row );
346 $this->imagePath
= $this->getFullPath();
347 // Check for rows from a previous schema, quietly upgrade them
348 if ( is_null($this->type
) ) {
351 } elseif ( ($wgUseSharedUploads && $wgSharedUploadDBname)) {
352 # In case we're on a wgCapitalLinks=false wiki, we
353 # capitalize the first letter of the filename before
354 # looking it up in the shared repository.
355 $name = $wgContLang->ucfirst($this->name
);
356 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
358 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
360 'img_size', 'img_width', 'img_height', 'img_bits',
361 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata', 'img_description' ),
362 array( 'img_name' => $name ), __METHOD__
);
364 $this->fromSharedDirectory
= true;
365 $this->fileExists
= true;
366 $this->imagePath
= $this->getFullPath(true);
368 $this->loadFromRow( $row );
370 // Check for rows from a previous schema, quietly upgrade them
371 if ( is_null($this->type
) ) {
375 } elseif ( $wgUseInstantCommons && $wgInstantCommonsServerPath ){
376 //NB: We enter into this loop even when we're uploading to the wiki.
377 //Download the file from the InstantCommonsServer.
378 //store it in the image database and return an Image object It should
379 //return an object identical to a database row as above
381 $ch = curl_init($wgInstantCommonsServerPath.'/api.php?action=instantcommons&format=xml&media='.$this->name
);
382 $fp = fopen("icresponse.xml", "w");
383 curl_setopt($ch, CURLOPT_FILE
, $fp);
384 curl_setopt($ch, CURLOPT_HEADER
, 0);
387 //offer various methods of fetching the remote
390 if(function_exists('json_decode'))
392 $row = utf8_decode(json_decode(fread($fp)));
396 wfDebug('Reading aborted'.__METHOD__.':'.__LINE__.' in '.__FILE__);
398 $p =& new ApiInstantCommons('instantcommons', 'maint');
402 //$fpr = fopen('icresponse.xml', 'r');
403 //$xmlString = fread($fpr, 409600);
404 $xmlString = file_get_contents('icresponse.xml');
405 wfDebug("xmlS=".$xmlString.__METHOD__
.':'.__LINE__
.' in '.__FILE__
);
406 if(trim($xmlString)!=""){
407 //$row = ($p->parse($xmlString));
408 //$row = $row[0]['children'][0]['children'][0]['attrs'];
411 //create the local file directory ($this->mSavedFile)
412 UploadForm
::saveUploadedFile( $row['NAME'],
414 ); //just creates the path
415 //now download the file to the final location
416 $ch = curl_init($wgInstantCommonsServerPath.$row['URL']);
417 $fp = fopen("{$this->mSavedFile}", "w");
418 curl_setopt($ch, CURLOPT_FILE
, $fp);
419 curl_setopt($ch, CURLOPT_HEADER
, 0);
424 //set further properties
425 $this->fromInstantCommons
= true; //TODO:THIS IS NOT STORED!
426 $this->fileExists
= true;
427 $this->imagePath
= $this->getFullPath(false, true);
428 $this->width
= $row['WIDTH'];
429 $this->height
= $row['HEIGHT'];
430 $this->metadata
= stripslashes($row['METADATA']);
431 $this->bits
= $row['BITS'];
432 $this->type
= $row['TYPE'];
433 $this->mime
= $row['MIME'];
434 $this->size
= $row['SIZE'];
435 $this->dataLoaded
= $row['DATALOADED'];
436 $this->attr
= $row['ATTR'];
437 $this->historyLine
= $row['HISTORYLINE'];
438 $this->historyRes
= $row['HISTORYRES'];
440 * Update the upload log and create the description page
441 * if it's a new file.
443 $success = $this->recordUpload('Downloaded with InstantCommons!', $row['DESCRIPTION']);
445 wfRunHooks( 'UploadComplete', array( &$this ) );
459 $this->fileExists
= false;
460 $this->fromSharedDirectory
= false;
461 $this->metadata
= serialize ( array() ) ;
465 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
466 $this->dataLoaded
= true;
467 wfProfileOut( __METHOD__
);
471 * Load image metadata from a DB result row
473 function loadFromRow( &$row ) {
474 $this->size
= $row->img_size
;
475 $this->width
= $row->img_width
;
476 $this->height
= $row->img_height
;
477 $this->bits
= $row->img_bits
;
478 $this->type
= $row->img_media_type
;
479 $this->description
= $row->img_description
;
481 $major= $row->img_major_mime
;
482 $minor= $row->img_minor_mime
;
484 if (!$major) $this->mime
= "unknown/unknown";
486 if (!$minor) $minor= "unknown";
487 $this->mime
= $major.'/'.$minor;
490 $this->metadata
= $row->img_metadata
;
491 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
493 $this->dataLoaded
= true;
497 * Load image metadata from cache or DB, unless already loaded
500 global $wgSharedUploadDBname, $wgUseSharedUploads, $wgUseInstantCommons;
501 if ( !$this->dataLoaded
) {
502 if ( !$this->loadFromCache() ) {
504 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
505 $this->loadFromFile();
506 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
507 // We can do negative caching for local images, because the cache
508 // will be purged on upload. But we can't do it when shared images
509 // are enabled, since updates to that won't purge foreign caches.
510 $this->saveToCache();
513 $this->dataLoaded
= true;
518 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
519 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
521 function upgradeRow() {
522 global $wgDBname, $wgSharedUploadDBname;
523 wfProfileIn( __METHOD__
);
525 $this->loadFromFile();
527 if ( $this->fromSharedDirectory
) {
528 if ( !$wgSharedUploadDBname ) {
529 wfProfileOut( __METHOD__
);
533 // Write to the other DB using selectDB, not database selectors
534 // This avoids breaking replication in MySQL
535 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
536 $dbw->selectDB( $wgSharedUploadDBname );
538 $dbw =& wfGetDB( DB_MASTER
);
541 $this->checkDBSchema($dbw);
543 list( $major, $minor ) = self
::splitMime( $this->mime
);
545 wfDebug(__METHOD__
.': upgrading '.$this->name
." to 1.5 schema\n");
547 $dbw->update( 'image',
549 'img_width' => $this->width
,
550 'img_height' => $this->height
,
551 'img_bits' => $this->bits
,
552 'img_media_type' => $this->type
,
553 'img_major_mime' => $major,
554 'img_minor_mime' => $minor,
555 'img_metadata' => $this->metadata
,
556 ), array( 'img_name' => $this->name
), __METHOD__
558 if ( $this->fromSharedDirectory
) {
559 $dbw->selectDB( $wgDBname );
561 wfProfileOut( __METHOD__
);
565 * Split an internet media type into its two components; if not
566 * a two-part name, set the minor type to 'unknown'.
568 * @param $mime "text/html" etc
569 * @return array ("text", "html") etc
571 static function splitMime( $mime ) {
572 if( strpos( $mime, '/' ) !== false ) {
573 return explode( '/', $mime, 2 );
575 return array( $mime, 'unknown' );
580 * Return the name of this image
588 * Return the associated title object
591 function getTitle() {
596 * Return the URL of the image file
602 if($this->fileExists
) {
603 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
, $this->fromInstantCommons
);
611 function getViewURL() {
612 if( $this->mustRender()) {
613 if( $this->canRender() ) {
614 return $this->createThumb( $this->getWidth() );
617 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
618 return $this->getURL(); #hm... return NULL?
621 return $this->getURL();
626 * Return the image path of the image in the
627 * local file system as an absolute path
630 function getImagePath() {
632 return $this->imagePath
;
636 * Return the width of the image
638 * Returns -1 if the file specified is not a known image type
641 function getWidth() {
647 * Return the height of the image
649 * Returns -1 if the file specified is not a known image type
652 function getHeight() {
654 return $this->height
;
658 * Return the size of the image file, in bytes
667 * Returns the mime type of the file.
669 function getMimeType() {
675 * Return the type of the media in the file.
676 * Use the value returned by this function with the MEDIATYPE_xxx constants.
678 function getMediaType() {
684 * Checks if the file can be presented to the browser as a bitmap.
686 * Currently, this checks if the file is an image format
687 * that can be converted to a format
688 * supported by all browsers (namely GIF, PNG and JPEG),
689 * or if it is an SVG image and SVG conversion is enabled.
691 * @todo remember the result of this check.
693 function canRender() {
694 global $wgUseImageMagick, $wgDjvuRenderer;
696 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
698 $mime= $this->getMimeType();
700 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
702 #if it's SVG, check if there's a converter enabled
703 if ($mime === 'image/svg') {
704 global $wgSVGConverters, $wgSVGConverter;
706 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
707 wfDebug( "Image::canRender: SVG is ready!\n" );
710 wfDebug( "Image::canRender: SVG renderer missing\n" );
714 #image formats available on ALL browsers
715 if ( $mime === 'image/gif'
716 ||
$mime === 'image/png'
717 ||
$mime === 'image/jpeg' ) return true;
719 #image formats that can be converted to the above formats
720 if ($wgUseImageMagick) {
721 #convertable by ImageMagick (there are more...)
722 if ( $mime === 'image/vnd.wap.wbmp'
723 ||
$mime === 'image/x-xbitmap'
724 ||
$mime === 'image/x-xpixmap'
725 #|| $mime === 'image/x-icon' #file may be split into multiple parts
726 ||
$mime === 'image/x-portable-anymap'
727 ||
$mime === 'image/x-portable-bitmap'
728 ||
$mime === 'image/x-portable-graymap'
729 ||
$mime === 'image/x-portable-pixmap'
730 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
731 ||
$mime === 'image/x-rgb'
732 ||
$mime === 'image/x-bmp'
733 ||
$mime === 'image/tiff' ) return true;
736 #convertable by the PHP GD image lib
737 if ( $mime === 'image/vnd.wap.wbmp'
738 ||
$mime === 'image/x-xbitmap' ) return true;
740 if ( $mime === 'image/vnd.djvu' && isset( $wgDjvuRenderer ) && $wgDjvuRenderer ) return true;
747 * Return true if the file is of a type that can't be directly
748 * rendered by typical browsers and needs to be re-rasterized.
750 * This returns true for everything but the bitmap types
751 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
752 * also return true for any non-image formats.
756 function mustRender() {
757 $mime= $this->getMimeType();
759 if ( $mime === "image/gif"
760 ||
$mime === "image/png"
761 ||
$mime === "image/jpeg" ) return false;
767 * Determines if this media file may be shown inline on a page.
769 * This is currently synonymous to canRender(), but this could be
770 * extended to also allow inline display of other media,
771 * like flash animations or videos. If you do so, please keep in mind that
772 * that could be a security risk.
774 function allowInlineDisplay() {
775 return $this->canRender();
779 * Determines if this media file is in a format that is unlikely to
780 * contain viruses or malicious content. It uses the global
781 * $wgTrustedMediaFormats list to determine if the file is safe.
783 * This is used to show a warning on the description page of non-safe files.
784 * It may also be used to disallow direct [[media:...]] links to such files.
786 * Note that this function will always return true if allowInlineDisplay()
787 * or isTrustedFile() is true for this file.
789 function isSafeFile() {
790 if ($this->allowInlineDisplay()) return true;
791 if ($this->isTrustedFile()) return true;
793 global $wgTrustedMediaFormats;
795 $type= $this->getMediaType();
796 $mime= $this->getMimeType();
797 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
799 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
800 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
802 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
803 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
808 /** Returns true if the file is flagged as trusted. Files flagged that way
809 * can be linked to directly, even if that is not allowed for this type of
812 * This is a dummy function right now and always returns false. It could be
813 * implemented to extract a flag from the database. The trusted flag could be
814 * set on upload, if the user has sufficient privileges, to bypass script-
815 * and html-filters. It may even be coupled with cryptographics signatures
818 function isTrustedFile() {
819 #this could be implemented to check a flag in the databas,
820 #look for signatures, etc
825 * Return the escapeLocalURL of this image
828 function getEscapeLocalURL( $query=false) {
830 if ( $query === false ) {
831 if ( $this->page
!= 1 ) {
832 $query = 'page=' . $this->page
;
837 return $this->title
->escapeLocalURL( $query );
841 * Return the escapeFullURL of this image
844 function getEscapeFullURL() {
846 return $this->title
->escapeFullURL();
850 * Return the URL of an image, provided its name.
852 * @param string $name Name of the image, without the leading "Image:"
853 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
854 * @return string URL of $name image
858 function imageUrl( $name, $fromSharedDirectory = false, $fromInstantCommons = false ) {
859 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath, $wgInstantCommonsServerPath;
860 if($fromInstantCommons) { //check if this is set first before checking shared directory
862 $path = $wgInstantCommonsServerPath;
864 else if($fromSharedDirectory) {
866 $path = $wgSharedUploadPath;
868 $base = $wgUploadBaseUrl;
869 $path = $wgUploadPath;
871 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory, $fromInstantCommons) . "{$name}";
872 return wfUrlencode( $url );
876 * Returns true if the image file exists on disk.
877 * @return boolean Whether image file exist on disk.
882 return $this->fileExists
;
889 function thumbUrl( $width, $subdir='thumb') {
890 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath, $wgInstantCommonsServerPath;
891 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
893 // Generate thumb.php URL if possible
897 if ( $this->fromSharedDirectory
) {
898 if ( $wgSharedThumbnailScriptPath ) {
899 $script = $wgSharedThumbnailScriptPath;
902 if ( $wgThumbnailScriptPath ) {
903 $script = $wgThumbnailScriptPath;
907 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
908 if( $this->mustRender() ) {
912 $name = $this->thumbName( $width );
913 if($this->fromSharedDirectory
) {
915 $path = $wgSharedUploadPath;
917 $base = $wgUploadBaseUrl;
918 $path = $wgUploadPath;
920 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
921 $url = "{$base}{$path}/{$subdir}" .
922 wfGetHashPath($this->name
, $this->fromSharedDirectory
, $this->fromInstantCommons
)
923 . $this->name
.'/'.$name;
924 $url = wfUrlencode( $url );
926 $url = "{$base}{$path}/{$subdir}/{$name}";
929 return array( $script !== false, $url );
933 * Return the file name of a thumbnail of the specified width
935 * @param integer $width Width of the thumbnail image
936 * @param boolean $shared Does the thumbnail come from the shared repository?
939 function thumbName( $width ) {
940 $thumb = $width."px-".$this->name
;
941 if ( $this->page
!= 1 ) {
942 $thumb = "page{$this->page}-$thumb";
945 if( $this->mustRender() ) {
946 if( $this->canRender() ) {
947 # Rasterize to PNG (for SVG vector images, etc)
951 #should we use iconThumb here to get a symbolic thumbnail?
952 #or should we fail with an internal error?
953 return NULL; //can't make bitmap
960 * Create a thumbnail of the image having the specified width/height.
961 * The thumbnail will not be created if the width is larger than the
962 * image's width. Let the browser do the scaling in this case.
963 * The thumbnail is stored on disk and is only computed if the thumbnail
964 * file does not exist OR if it is older than the image.
967 * Keeps aspect ratio of original image. If both width and height are
968 * specified, the generated image will be no bigger than width x height,
969 * and will also have correct aspect ratio.
971 * @param integer $width maximum width of the generated thumbnail
972 * @param integer $height maximum height of the image (optional)
975 function createThumb( $width, $height=-1 ) {
976 $thumb = $this->getThumbnail( $width, $height );
977 if( is_null( $thumb ) ) return '';
978 return $thumb->getUrl();
982 * As createThumb, but returns a ThumbnailImage object. This can
983 * provide access to the actual file, the real size of the thumb,
984 * and can produce a convenient <img> tag for you.
986 * For non-image formats, this may return a filetype-specific icon.
988 * @param integer $width maximum width of the generated thumbnail
989 * @param integer $height maximum height of the image (optional)
990 * @param boolean $render True to render the thumbnail if it doesn't exist,
991 * false to just return the URL
993 * @return ThumbnailImage or null on failure
996 function getThumbnail( $width, $height=-1, $render = true ) {
997 wfProfileIn( __METHOD__
);
998 if ($this->canRender()) {
1001 if ( $width > $this->width
* $height / $this->height
) {
1002 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
1006 $thumb = $this->renderThumb( $width );
1008 // Don't render, just return the URL
1009 if ( $this->validateThumbParams( $width, $height ) ) {
1010 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1011 $url = $this->getURL();
1013 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $width );
1015 $thumb = new ThumbnailImage( $url, $width, $height );
1021 // not a bitmap or renderable image, don't try.
1022 $thumb = $this->iconThumb();
1024 wfProfileOut( __METHOD__
);
1029 * @return ThumbnailImage
1031 function iconThumb() {
1032 global $wgStylePath, $wgStyleDirectory;
1034 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
1035 foreach( $try as $icon ) {
1036 $path = '/common/images/icons/' . $icon;
1037 $filepath = $wgStyleDirectory . $path;
1038 if( file_exists( $filepath ) ) {
1039 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1046 * Validate thumbnail parameters and fill in the correct height
1048 * @param integer &$width Specified width (input/output)
1049 * @param integer &$height Height (output only)
1050 * @return false to indicate that an error should be returned to the user.
1052 function validateThumbParams( &$width, &$height ) {
1053 global $wgSVGMaxSize, $wgMaxImageArea;
1057 if ( ! $this->exists() )
1059 # If there is no image, there will be no thumbnail
1063 $width = intval( $width );
1065 # Sanity check $width
1066 if( $width <= 0 ||
$this->width
<= 0) {
1071 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
1072 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
1073 # an exception for it.
1074 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
1075 $this->getMimeType() !== 'image/jpeg' &&
1076 $this->width
* $this->height
> $wgMaxImageArea )
1081 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
1082 if ( $this->mustRender() ) {
1083 $width = min( $width, $wgSVGMaxSize );
1084 } elseif ( $width > $this->width
- 1 ) {
1085 $width = $this->width
;
1086 $height = $this->height
;
1090 $height = round( $this->height
* $width / $this->width
);
1095 * Create a thumbnail of the image having the specified width.
1096 * The thumbnail will not be created if the width is larger than the
1097 * image's width. Let the browser do the scaling in this case.
1098 * The thumbnail is stored on disk and is only computed if the thumbnail
1099 * file does not exist OR if it is older than the image.
1100 * Returns an object which can return the pathname, URL, and physical
1101 * pixel size of the thumbnail -- or null on failure.
1103 * @return ThumbnailImage or null on failure
1106 function renderThumb( $width, $useScript = true ) {
1107 global $wgUseSquid, $wgThumbnailEpoch;
1109 wfProfileIn( __METHOD__
);
1113 if ( !$this->validateThumbParams( $width, $height ) ) {
1115 wfProfileOut( __METHOD__
);
1119 if ( !$this->mustRender() && $width == $this->width
&& $height == $this->height
) {
1120 # validateThumbParams (or the user) wants us to return the unscaled image
1121 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1122 wfProfileOut( __METHOD__
);
1126 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1127 if ( $isScriptUrl && $useScript ) {
1128 // Use thumb.php to render the image
1129 $thumb = new ThumbnailImage( $url, $width, $height );
1130 wfProfileOut( __METHOD__
);
1134 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
1135 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
1136 $thumbPath = $thumbDir.'/'.$thumbName;
1138 if ( is_dir( $thumbPath ) ) {
1139 // Directory where file should be
1140 // This happened occasionally due to broken migration code in 1.5
1141 // Rename to broken-*
1142 global $wgUploadDirectory;
1143 for ( $i = 0; $i < 100 ; $i++
) {
1144 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1145 if ( !file_exists( $broken ) ) {
1146 rename( $thumbPath, $broken );
1150 // Code below will ask if it exists, and the answer is now no
1155 if ( !file_exists( $thumbPath ) ||
1156 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) )
1158 // Create the directory if it doesn't exist
1159 if ( is_file( $thumbDir ) ) {
1160 // File where thumb directory should be, destroy if possible
1161 @unlink
( $thumbDir );
1163 wfMkdirParents( $thumbDir );
1165 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1169 // Migration from old directory structure
1170 if ( is_file( $oldThumbPath ) ) {
1171 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1172 if ( file_exists( $thumbPath ) ) {
1173 if ( !is_dir( $thumbPath ) ) {
1174 // Old image in the way of rename
1175 unlink( $thumbPath );
1177 // This should have been dealt with already
1178 throw new MWException( "Directory where image should be: $thumbPath" );
1181 // Rename the old image into the new location
1182 rename( $oldThumbPath, $thumbPath );
1185 unlink( $oldThumbPath );
1189 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1190 if ( $this->lastError
=== true ) {
1192 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1193 // Log the error but output anyway.
1194 // With luck it's a transitory error...
1199 # This has to be done after the image is updated and present for all machines on NFS,
1200 # or else the old version might be stored into the squid again
1201 if ( $wgUseSquid ) {
1202 $urlArr = array( $url );
1203 wfPurgeSquidServers($urlArr);
1209 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1213 wfProfileOut( __METHOD__
);
1215 } // END OF function renderThumb
1218 * Really render a thumbnail
1219 * Call this only for images for which canRender() returns true.
1221 * @param string $thumbPath Path to thumbnail
1222 * @param int $width Desired width in pixels
1223 * @param int $height Desired height in pixels
1224 * @return bool True on error, false or error string on failure.
1227 function reallyRenderThumb( $thumbPath, $width, $height ) {
1228 global $wgSVGConverters, $wgSVGConverter;
1229 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1230 global $wgCustomConvertCommand;
1231 global $wgDjvuRenderer, $wgDjvuPostProcessor;
1239 if( $this->mime
=== "image/svg" ) {
1240 #Right now we have only SVG
1242 global $wgSVGConverters, $wgSVGConverter;
1243 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1244 global $wgSVGConverterPath;
1246 array( '$path/', '$width', '$height', '$input', '$output' ),
1247 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1250 wfEscapeShellArg( $this->imagePath
),
1251 wfEscapeShellArg( $thumbPath ) ),
1252 $wgSVGConverters[$wgSVGConverter] );
1253 wfProfileIn( 'rsvg' );
1254 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1255 $err = wfShellExec( $cmd, $retval );
1256 wfProfileOut( 'rsvg' );
1259 if ( $this->mime
=== "image/vnd.djvu" && $wgDjvuRenderer ) {
1261 // The file contains several images. First, extract the
1262 // page in hi-res, if it doesn't yet exist. Then, thumbnail
1265 $cmd = "{$wgDjvuRenderer} -page={$this->page} -size=${width}x${height} " .
1266 wfEscapeShellArg( $this->imagePath
) .
1267 " | {$wgDjvuPostProcessor} > " . wfEscapeShellArg($thumbPath);
1268 wfProfileIn( 'ddjvu' );
1269 wfDebug( "reallyRenderThumb DJVU: $cmd\n" );
1270 $err = wfShellExec( $cmd, $retval );
1271 wfProfileOut( 'ddjvu' );
1273 } elseif ( $wgUseImageMagick ) {
1276 if ( $this->mime
== 'image/jpeg' ) {
1277 $quality = "-quality 80"; // 80%
1278 } elseif ( $this->mime
== 'image/png' ) {
1279 $quality = "-quality 95"; // zlib 9, adaptive filtering
1281 $quality = ''; // default
1284 # Specify white background color, will be used for transparent images
1285 # in Internet Explorer/Windows instead of default black.
1287 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1288 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1289 # the wrong size in the second case.
1291 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1292 " {$quality} -background white -size {$width} ".
1293 wfEscapeShellArg($this->imagePath
) .
1294 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1296 // For the -resize option a "!" is needed to force exact size,
1297 // or ImageMagick may decide your ratio is wrong and slice off
1299 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1301 wfEscapeShellArg($thumbPath) . " 2>&1";
1302 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1303 wfProfileIn( 'convert' );
1304 $err = wfShellExec( $cmd, $retval );
1305 wfProfileOut( 'convert' );
1306 } elseif( $wgCustomConvertCommand ) {
1307 # Use a custom convert command
1308 # Variables: %s %d %w %h
1309 $src = wfEscapeShellArg( $this->imagePath
);
1310 $dst = wfEscapeShellArg( $thumbPath );
1311 $cmd = $wgCustomConvertCommand;
1312 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1313 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1314 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1315 wfProfileIn( 'convert' );
1316 $err = wfShellExec( $cmd, $retval );
1317 wfProfileOut( 'convert' );
1319 # Use PHP's builtin GD library functions.
1321 # First find out what kind of file this is, and select the correct
1322 # input routine for this.
1325 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1326 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1327 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1328 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1329 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1331 if( !isset( $typemap[$this->mime
] ) ) {
1332 $err = 'Image type not supported';
1333 wfDebug( "$err\n" );
1336 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1338 if( !function_exists( $loader ) ) {
1339 $err = "Incomplete GD library configuration: missing function $loader";
1340 wfDebug( "$err\n" );
1343 if( $colorStyle == 'palette' ) {
1345 } elseif( $colorStyle == 'truecolor' ) {
1347 } elseif( $colorStyle == 'bits' ) {
1348 $truecolor = ( $this->bits
> 8 );
1351 $src_image = call_user_func( $loader, $this->imagePath
);
1353 $dst_image = imagecreatetruecolor( $width, $height );
1355 $dst_image = imagecreate( $width, $height );
1357 imagecopyresampled( $dst_image, $src_image,
1359 $width, $height, $this->width
, $this->height
);
1360 call_user_func( $saveType, $dst_image, $thumbPath );
1361 imagedestroy( $dst_image );
1362 imagedestroy( $src_image );
1367 # Check for zero-sized thumbnails. Those can be generated when
1368 # no disk space is available or some other error occurs
1370 if( file_exists( $thumbPath ) ) {
1371 $thumbstat = stat( $thumbPath );
1372 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1373 wfDebugLog( 'thumbnail',
1374 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1375 $thumbstat['size'], $thumbPath ) );
1376 unlink( $thumbPath );
1379 if ( $retval != 0 ) {
1380 wfDebugLog( 'thumbnail',
1381 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1382 wfHostname(), $retval, trim($err), $cmd ) );
1383 return wfMsg( 'thumbnail_error', $err );
1389 function getLastError() {
1390 return $this->lastError
;
1393 function imageJpegWrapper( $dst_image, $thumbPath ) {
1394 imageinterlace( $dst_image );
1395 imagejpeg( $dst_image, $thumbPath, 95 );
1399 * Get all thumbnail names previously generated for this image
1401 function getThumbnails( $shared = false ) {
1402 if ( Image
::isHashed( $shared ) ) {
1405 $dir = wfImageThumbDir( $this->name
, $shared );
1407 // This generates an error on failure, hence the @
1408 $handle = @opendir
( $dir );
1411 while ( false !== ( $file = readdir($handle) ) ) {
1412 if ( $file{0} != '.' ) {
1416 closedir( $handle );
1426 * Refresh metadata in memcached, but don't touch thumbnails or squid
1428 function purgeMetadataCache() {
1430 $this->loadFromFile();
1431 $this->saveToCache();
1435 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1437 function purgeCache( $archiveFiles = array(), $shared = false ) {
1440 // Refresh metadata cache
1441 $this->purgeMetadataCache();
1443 // Delete thumbnails
1444 $files = $this->getThumbnails( $shared );
1445 $dir = wfImageThumbDir( $this->name
, $shared );
1447 foreach ( $files as $file ) {
1449 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1450 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $m[1] );
1452 @unlink
( "$dir/$file" );
1457 if ( $wgUseSquid ) {
1458 $urls[] = $this->getURL();
1459 foreach ( $archiveFiles as $file ) {
1460 $urls[] = wfImageArchiveUrl( $file );
1462 wfPurgeSquidServers( $urls );
1467 * Purge the image description page, but don't go after
1468 * pages using the image. Use when modifying file history
1469 * but not the current data.
1471 function purgeDescription() {
1472 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1473 $page->invalidateCache();
1474 $page->purgeSquid();
1478 * Purge metadata and all affected pages when the image is created,
1479 * deleted, or majorly updated. A set of additional URLs may be
1480 * passed to purge, such as specific image files which have changed.
1481 * @param $urlArray array
1483 function purgeEverything( $urlArr=array() ) {
1484 // Delete thumbnails and refresh image metadata cache
1485 $this->purgeCache();
1486 $this->purgeDescription();
1488 // Purge cache of all pages using this image
1489 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1490 $update->doUpdate();
1493 function checkDBSchema(&$db) {
1494 static $checkDone = false;
1495 global $wgCheckDBSchema;
1496 if (!$wgCheckDBSchema ||
$checkDone) {
1499 # img_name must be unique
1500 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1501 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1505 # new fields must exist
1507 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1508 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1509 # something. The only reason I put the above schema check in was because the absence of that particular
1510 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1513 if ( !$db->fieldExists( 'image', 'img_media_type' )
1514 || !$db->fieldExists( 'image', 'img_metadata' )
1515 || !$db->fieldExists( 'image', 'img_width' ) ) {
1517 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1523 * Return the image history of this image, line by line.
1524 * starts with current version, then old versions.
1525 * uses $this->historyLine to check which line to return:
1526 * 0 return line for current version
1527 * 1 query for old versions, return first one
1528 * 2, ... return next old version from above query
1532 function nextHistoryLine() {
1533 $dbr =& wfGetDB( DB_SLAVE
);
1535 $this->checkDBSchema($dbr);
1537 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1538 $this->historyRes
= $dbr->select( 'image',
1542 'img_user','img_user_text',
1546 "'' AS oi_archive_name"
1548 array( 'img_name' => $this->title
->getDBkey() ),
1551 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1554 } else if ( $this->historyLine
== 1 ) {
1555 $this->historyRes
= $dbr->select( 'oldimage',
1557 'oi_size AS img_size',
1558 'oi_description AS img_description',
1559 'oi_user AS img_user',
1560 'oi_user_text AS img_user_text',
1561 'oi_timestamp AS img_timestamp',
1562 'oi_width as img_width',
1563 'oi_height as img_height',
1566 array( 'oi_name' => $this->title
->getDBkey() ),
1568 array( 'ORDER BY' => 'oi_timestamp DESC' )
1571 $this->historyLine ++
;
1573 return $dbr->fetchObject( $this->historyRes
);
1577 * Reset the history pointer to the first element of the history
1580 function resetHistory() {
1581 $this->historyLine
= 0;
1585 * Return the full filesystem path to the file. Note that this does
1586 * not mean that a file actually exists under that location.
1588 * This path depends on whether directory hashing is active or not,
1589 * i.e. whether the images are all found in the same directory,
1590 * or in hashed paths like /images/3/3c.
1593 * @param boolean $fromSharedDirectory Return the path to the file
1594 * in a shared repository (see $wgUseSharedRepository and related
1595 * options in DefaultSettings.php) instead of a local one.
1598 function getFullPath( $fromSharedRepository = false, $fromInstantCommons = false ) {
1599 global $wgUploadDirectory, $wgSharedUploadDirectory, $wgInstantCommonsServerPath;
1600 //use local repository paths only if InstantCommons path is not available
1601 $dir = $fromInstantCommons ?
$wgInstantCommonsServerPath : ($fromSharedRepository ?
$wgSharedUploadDirectory :
1602 $wgUploadDirectory);
1604 // $wgSharedUploadDirectory may be false, if thumb.php is used
1606 if($fromInstantCommons)
1607 {//TODO: Not the best thing to do here as it adds another 10k to
1608 //the default mediawiki install. Maybe point it to the default logo?
1609 $fullpath = 'downloading.png';
1613 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository, $fromInstantCommons) . $this->name
;
1626 public static function isHashed( $shared ) {
1627 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1628 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1632 * Record an image upload in the upload log and the image table
1634 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1635 global $wgUser, $wgUseCopyrightUpload;
1637 $dbw =& wfGetDB( DB_MASTER
);
1639 $this->checkDBSchema($dbw);
1641 // Delete thumbnails and refresh the metadata cache
1642 $this->purgeCache();
1644 // Fail now if the image isn't there
1645 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1646 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1650 if ( $wgUseCopyrightUpload ) {
1651 if ( $license != '' ) {
1652 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1654 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1655 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1657 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1659 if ( $license != '' ) {
1660 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1661 $textdesc = $filedesc .
1662 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1668 $now = $dbw->timestamp();
1671 if (strpos($this->mime
,'/')!==false) {
1672 list($major,$minor)= explode('/',$this->mime
,2);
1675 $major= $this->mime
;
1679 # Test to see if the row exists using INSERT IGNORE
1680 # This avoids race conditions by locking the row until the commit, and also
1681 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1682 $dbw->insert( 'image',
1684 'img_name' => $this->name
,
1685 'img_size'=> $this->size
,
1686 'img_width' => intval( $this->width
),
1687 'img_height' => intval( $this->height
),
1688 'img_bits' => $this->bits
,
1689 'img_media_type' => $this->type
,
1690 'img_major_mime' => $major,
1691 'img_minor_mime' => $minor,
1692 'img_timestamp' => $now,
1693 'img_description' => $desc,
1694 'img_user' => $wgUser->getID(),
1695 'img_user_text' => $wgUser->getName(),
1696 'img_metadata' => $this->metadata
,
1702 if( $dbw->affectedRows() == 0 ) {
1703 # Collision, this is an update of an image
1704 # Insert previous contents into oldimage
1705 $dbw->insertSelect( 'oldimage', 'image',
1707 'oi_name' => 'img_name',
1708 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1709 'oi_size' => 'img_size',
1710 'oi_width' => 'img_width',
1711 'oi_height' => 'img_height',
1712 'oi_bits' => 'img_bits',
1713 'oi_timestamp' => 'img_timestamp',
1714 'oi_description' => 'img_description',
1715 'oi_user' => 'img_user',
1716 'oi_user_text' => 'img_user_text',
1717 ), array( 'img_name' => $this->name
), __METHOD__
1720 # Update the current image row
1721 $dbw->update( 'image',
1723 'img_size' => $this->size
,
1724 'img_width' => intval( $this->width
),
1725 'img_height' => intval( $this->height
),
1726 'img_bits' => $this->bits
,
1727 'img_media_type' => $this->type
,
1728 'img_major_mime' => $major,
1729 'img_minor_mime' => $minor,
1730 'img_timestamp' => $now,
1731 'img_description' => $desc,
1732 'img_user' => $wgUser->getID(),
1733 'img_user_text' => $wgUser->getName(),
1734 'img_metadata' => $this->metadata
,
1735 ), array( /* WHERE */
1736 'img_name' => $this->name
1740 # This is a new image
1741 # Update the image count
1742 $site_stats = $dbw->tableName( 'site_stats' );
1743 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1746 $descTitle = $this->getTitle();
1747 $article = new Article( $descTitle );
1749 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1750 $suppressRC = true; // There's already a log entry, so don't double the RC load
1752 if( $descTitle->exists() ) {
1753 // TODO: insert a null revision into the page history for this update.
1755 $wgUser->addWatch( $descTitle );
1758 # Invalidate the cache for the description page
1759 $descTitle->invalidateCache();
1760 $descTitle->purgeSquid();
1762 // New image; create the description page.
1763 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1767 $log = new LogPage( 'upload' );
1768 $log->addEntry( 'upload', $descTitle, $desc );
1770 # Commit the transaction now, in case something goes wrong later
1771 # The most important thing is that images don't get lost, especially archives
1772 $dbw->immediateCommit();
1774 # Invalidate cache for all pages using this image
1775 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1776 $update->doUpdate();
1782 * Get an array of Title objects which are articles which use this image
1783 * Also adds their IDs to the link cache
1785 * This is mostly copied from Title::getLinksTo()
1787 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1789 function getLinksTo( $options = '' ) {
1790 wfProfileIn( __METHOD__
);
1793 $db =& wfGetDB( DB_MASTER
);
1795 $db =& wfGetDB( DB_SLAVE
);
1797 $linkCache =& LinkCache
::singleton();
1799 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1800 $encName = $db->addQuotes( $this->name
);
1801 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1802 $res = $db->query( $sql, __METHOD__
);
1805 if ( $db->numRows( $res ) ) {
1806 while ( $row = $db->fetchObject( $res ) ) {
1807 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1808 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1809 $retVal[] = $titleObj;
1813 $db->freeResult( $res );
1814 wfProfileOut( __METHOD__
);
1819 * Retrive Exif data from the file and prune unrecognized tags
1820 * and/or tags with invalid contents
1825 private function retrieveExifData( $filename ) {
1829 if ( $this->getMimeType() !== "image/jpeg" )
1833 if( $wgShowEXIF && file_exists( $filename ) ) {
1834 $exif = new Exif( $filename );
1835 return $exif->getFilteredData();
1841 function getExifData() {
1843 if ( $this->metadata
=== '0' ||
$this->mime
== 'image/vnd.djvu' )
1846 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1847 $ret = unserialize( $this->metadata
);
1849 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1850 $newver = Exif
::version();
1852 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1853 $this->purgeMetadataCache();
1854 $this->updateExifData( $newver );
1856 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1857 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1858 $format = new FormatExif( $ret );
1860 return $format->getFormattedData();
1863 function updateExifData( $version ) {
1864 if ( $this->getImagePath() === false ) # Not a local image
1867 # Get EXIF data from image
1868 $exif = $this->retrieveExifData( $this->imagePath
);
1869 if ( count( $exif ) ) {
1870 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1871 $this->metadata
= serialize( $exif );
1873 $this->metadata
= '0';
1876 # Update EXIF data in database
1877 $dbw =& wfGetDB( DB_MASTER
);
1879 $this->checkDBSchema($dbw);
1881 $dbw->update( 'image',
1882 array( 'img_metadata' => $this->metadata
),
1883 array( 'img_name' => $this->name
),
1889 * Returns true if the image does not come from the shared
1894 function isLocal() {
1895 return !$this->fromSharedDirectory
;
1899 * Was this image ever deleted from the wiki?
1903 function wasDeleted() {
1904 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1905 return ( $title->isDeleted() > 0 );
1909 * Delete all versions of the image.
1911 * Moves the files into an archive directory (or deletes them)
1912 * and removes the database rows.
1914 * Cache purging is done; logging is caller's responsibility.
1917 * @return true on success, false on some kind of failure
1919 function delete( $reason ) {
1920 $transaction = new FSTransaction();
1921 $urlArr = array( $this->getURL() );
1923 if( !FileStore
::lock() ) {
1924 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1929 $dbw = wfGetDB( DB_MASTER
);
1932 // Delete old versions
1933 $result = $dbw->select( 'oldimage',
1934 array( 'oi_archive_name' ),
1935 array( 'oi_name' => $this->name
) );
1937 while( $row = $dbw->fetchObject( $result ) ) {
1938 $oldName = $row->oi_archive_name
;
1940 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1942 // We'll need to purge this URL from caches...
1943 $urlArr[] = wfImageArchiveUrl( $oldName );
1945 $dbw->freeResult( $result );
1947 // And the current version...
1948 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1950 $dbw->immediateCommit();
1951 } catch( MWException
$e ) {
1952 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1953 $transaction->rollback();
1954 FileStore
::unlock();
1958 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1959 $transaction->commit();
1960 FileStore
::unlock();
1963 // Update site_stats
1964 $site_stats = $dbw->tableName( 'site_stats' );
1965 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1967 $this->purgeEverything( $urlArr );
1974 * Delete an old version of the image.
1976 * Moves the file into an archive directory (or deletes it)
1977 * and removes the database row.
1979 * Cache purging is done; logging is caller's responsibility.
1982 * @throws MWException or FSException on database or filestore failure
1983 * @return true on success, false on some kind of failure
1985 function deleteOld( $archiveName, $reason ) {
1986 $transaction = new FSTransaction();
1989 if( !FileStore
::lock() ) {
1990 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1994 $transaction = new FSTransaction();
1996 $dbw = wfGetDB( DB_MASTER
);
1998 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1999 $dbw->immediateCommit();
2000 } catch( MWException
$e ) {
2001 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
2002 $transaction->rollback();
2003 FileStore
::unlock();
2007 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
2008 $transaction->commit();
2009 FileStore
::unlock();
2011 $this->purgeDescription();
2015 if ( $wgUseSquid ) {
2017 wfImageArchiveUrl( $archiveName ),
2019 wfPurgeSquidServers( $urlArr );
2025 * Delete the current version of a file.
2026 * May throw a database error.
2027 * @return true on success, false on failure
2029 private function prepareDeleteCurrent( $reason ) {
2030 return $this->prepareDeleteVersion(
2031 $this->getFullPath(),
2035 'fa_name' => 'img_name',
2036 'fa_archive_name' => 'NULL',
2037 'fa_size' => 'img_size',
2038 'fa_width' => 'img_width',
2039 'fa_height' => 'img_height',
2040 'fa_metadata' => 'img_metadata',
2041 'fa_bits' => 'img_bits',
2042 'fa_media_type' => 'img_media_type',
2043 'fa_major_mime' => 'img_major_mime',
2044 'fa_minor_mime' => 'img_minor_mime',
2045 'fa_description' => 'img_description',
2046 'fa_user' => 'img_user',
2047 'fa_user_text' => 'img_user_text',
2048 'fa_timestamp' => 'img_timestamp' ),
2049 array( 'img_name' => $this->name
),
2054 * Delete a given older version of a file.
2055 * May throw a database error.
2056 * @return true on success, false on failure
2058 private function prepareDeleteOld( $archiveName, $reason ) {
2059 $oldpath = wfImageArchiveDir( $this->name
) .
2060 DIRECTORY_SEPARATOR
. $archiveName;
2061 return $this->prepareDeleteVersion(
2066 'fa_name' => 'oi_name',
2067 'fa_archive_name' => 'oi_archive_name',
2068 'fa_size' => 'oi_size',
2069 'fa_width' => 'oi_width',
2070 'fa_height' => 'oi_height',
2071 'fa_metadata' => 'NULL',
2072 'fa_bits' => 'oi_bits',
2073 'fa_media_type' => 'NULL',
2074 'fa_major_mime' => 'NULL',
2075 'fa_minor_mime' => 'NULL',
2076 'fa_description' => 'oi_description',
2077 'fa_user' => 'oi_user',
2078 'fa_user_text' => 'oi_user_text',
2079 'fa_timestamp' => 'oi_timestamp' ),
2081 'oi_name' => $this->name
,
2082 'oi_archive_name' => $archiveName ),
2087 * Do the dirty work of backing up an image row and its file
2088 * (if $wgSaveDeletedFiles is on) and removing the originals.
2090 * Must be run while the file store is locked and a database
2091 * transaction is open to avoid race conditions.
2093 * @return FSTransaction
2095 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
2096 global $wgUser, $wgSaveDeletedFiles;
2098 // Dupe the file into the file store
2099 if( file_exists( $path ) ) {
2100 if( $wgSaveDeletedFiles ) {
2103 $store = FileStore
::get( $group );
2104 $key = FileStore
::calculateKey( $path, $this->extension
);
2105 $transaction = $store->insert( $key, $path,
2106 FileStore
::DELETE_ORIGINAL
);
2110 $transaction = FileStore
::deleteFile( $path );
2113 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
2116 $transaction = new FSTransaction(); // empty
2119 if( $transaction === false ) {
2121 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
2122 throw new MWException( "Could not archive and delete file $path" );
2126 $dbw = wfGetDB( DB_MASTER
);
2127 $storageMap = array(
2128 'fa_storage_group' => $dbw->addQuotes( $group ),
2129 'fa_storage_key' => $dbw->addQuotes( $key ),
2131 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2132 'fa_deleted_timestamp' => $dbw->timestamp(),
2133 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2134 $allFields = array_merge( $storageMap, $fieldMap );
2137 if( $wgSaveDeletedFiles ) {
2138 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2140 $dbw->delete( $table, $where, $fname );
2141 } catch( DBQueryError
$e ) {
2142 // Something went horribly wrong!
2143 // Leave the file as it was...
2144 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
2145 $transaction->rollback();
2149 return $transaction;
2153 * Restore all or specified deleted revisions to the given file.
2154 * Permissions and logging are left to the caller.
2156 * May throw database exceptions on error.
2158 * @param $versions set of record ids of deleted items to restore,
2159 * or empty to restore all revisions.
2160 * @return the number of file revisions restored if successful,
2161 * or false on failure
2163 function restore( $versions=array() ) {
2164 if( !FileStore
::lock() ) {
2165 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
2169 $transaction = new FSTransaction();
2171 $dbw = wfGetDB( DB_MASTER
);
2174 // Re-confirm whether this image presently exists;
2175 // if no we'll need to create an image record for the
2176 // first item we restore.
2177 $exists = $dbw->selectField( 'image', '1',
2178 array( 'img_name' => $this->name
),
2181 // Fetch all or selected archived revisions for the file,
2182 // sorted from the most recent to the oldest.
2183 $conditions = array( 'fa_name' => $this->name
);
2185 $conditions['fa_id'] = $versions;
2188 $result = $dbw->select( 'filearchive', '*',
2191 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2193 if( $dbw->numRows( $result ) < count( $versions ) ) {
2194 // There's some kind of conflict or confusion;
2195 // we can't restore everything we were asked to.
2196 wfDebug( __METHOD__
.": couldn't find requested items\n" );
2198 FileStore
::unlock();
2202 if( $dbw->numRows( $result ) == 0 ) {
2204 wfDebug( __METHOD__
.": nothing to do\n" );
2206 FileStore
::unlock();
2211 while( $row = $dbw->fetchObject( $result ) ) {
2213 $store = FileStore
::get( $row->fa_storage_group
);
2215 wfDebug( __METHOD__
.": skipping row with no file.\n" );
2219 if( $revisions == 1 && !$exists ) {
2220 $destDir = wfImageDir( $row->fa_name
);
2221 if ( !is_dir( $destDir ) ) {
2222 wfMkdirParents( $destDir );
2224 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
2226 // We may have to fill in data if this was originally
2227 // an archived file revision.
2228 if( is_null( $row->fa_metadata
) ) {
2229 $tempFile = $store->filePath( $row->fa_storage_key
);
2230 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2232 $magic = MimeMagic
::singleton();
2233 $mime = $magic->guessMimeType( $tempFile, true );
2234 $media_type = $magic->getMediaType( $tempFile, $mime );
2235 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2237 $metadata = $row->fa_metadata
;
2238 $major_mime = $row->fa_major_mime
;
2239 $minor_mime = $row->fa_minor_mime
;
2240 $media_type = $row->fa_media_type
;
2245 'img_name' => $row->fa_name
,
2246 'img_size' => $row->fa_size
,
2247 'img_width' => $row->fa_width
,
2248 'img_height' => $row->fa_height
,
2249 'img_metadata' => $metadata,
2250 'img_bits' => $row->fa_bits
,
2251 'img_media_type' => $media_type,
2252 'img_major_mime' => $major_mime,
2253 'img_minor_mime' => $minor_mime,
2254 'img_description' => $row->fa_description
,
2255 'img_user' => $row->fa_user
,
2256 'img_user_text' => $row->fa_user_text
,
2257 'img_timestamp' => $row->fa_timestamp
);
2259 $archiveName = $row->fa_archive_name
;
2260 if( $archiveName == '' ) {
2261 // This was originally a current version; we
2262 // have to devise a new archive name for it.
2263 // Format is <timestamp of archiving>!<name>
2265 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2266 '!' . $row->fa_name
;
2268 $destDir = wfImageArchiveDir( $row->fa_name
);
2269 if ( !is_dir( $destDir ) ) {
2270 wfMkdirParents( $destDir );
2272 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
2274 $table = 'oldimage';
2276 'oi_name' => $row->fa_name
,
2277 'oi_archive_name' => $archiveName,
2278 'oi_size' => $row->fa_size
,
2279 'oi_width' => $row->fa_width
,
2280 'oi_height' => $row->fa_height
,
2281 'oi_bits' => $row->fa_bits
,
2282 'oi_description' => $row->fa_description
,
2283 'oi_user' => $row->fa_user
,
2284 'oi_user_text' => $row->fa_user_text
,
2285 'oi_timestamp' => $row->fa_timestamp
);
2288 $dbw->insert( $table, $fields, __METHOD__
);
2289 /// @fixme this delete is not totally safe, potentially
2290 $dbw->delete( 'filearchive',
2291 array( 'fa_id' => $row->fa_id
),
2294 // Check if any other stored revisions use this file;
2295 // if so, we shouldn't remove the file from the deletion
2296 // archives so they will still work.
2297 $useCount = $dbw->selectField( 'filearchive',
2300 'fa_storage_group' => $row->fa_storage_group
,
2301 'fa_storage_key' => $row->fa_storage_key
),
2303 if( $useCount == 0 ) {
2304 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2305 $flags = FileStore
::DELETE_ORIGINAL
;
2310 $transaction->add( $store->export( $row->fa_storage_key
,
2311 $destPath, $flags ) );
2314 $dbw->immediateCommit();
2315 } catch( MWException
$e ) {
2316 wfDebug( __METHOD__
." caught error, aborting\n" );
2317 $transaction->rollback();
2321 $transaction->commit();
2322 FileStore
::unlock();
2324 if( $revisions > 0 ) {
2326 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
2328 // Update site_stats
2329 $site_stats = $dbw->tableName( 'site_stats' );
2330 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2332 $this->purgeEverything();
2334 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
2335 $this->purgeDescription();
2343 * Select a page from a multipage document. Determines the page used for
2344 * rendering thumbnails.
2346 * @param $page Integer: page number, starting with 1
2348 function selectPage( $page ) {
2349 wfDebug( __METHOD__
." selecting page $page \n" );
2350 $this->page
= $page;
2351 if ( ! $this->dataLoaded
) {
2354 if ( ! isset( $this->multiPageXML
) ) {
2355 $this->initializeMultiPageXML();
2357 $o = $this->multiPageXML
->BODY
[0]->OBJECT[$page-1];
2358 $this->height
= intval( $o['height'] );
2359 $this->width
= intval( $o['width'] );
2362 function initializeMultiPageXML() {
2364 # Check for files uploaded prior to DJVU support activation
2365 # They have a '0' in their metadata field.
2367 if ( $this->metadata
== '0' ) {
2368 $deja = new DjVuImage( $this->imagePath
);
2369 $this->metadata
= $deja->retrieveMetaData();
2370 $this->purgeMetadataCache();
2372 # Update metadata in the database
2373 $dbw =& wfGetDB( DB_MASTER
);
2374 $dbw->update( 'image',
2375 array( 'img_metadata' => $this->metadata
),
2376 array( 'img_name' => $this->name
),
2380 wfSuppressWarnings();
2381 $this->multiPageXML
= new SimpleXMLElement( $this->metadata
);
2382 wfRestoreWarnings();
2386 * Returns 'true' if this image is a multipage document, e.g. a DJVU
2391 function isMultipage() {
2392 return ( $this->mime
== 'image/vnd.djvu' );
2396 * Returns the number of pages of a multipage document, or NULL for
2397 * documents which aren't multipage documents
2399 function pageCount() {
2400 if ( ! $this->isMultipage() ) {
2403 if ( ! isset( $this->multiPageXML
) ) {
2404 $this->initializeMultiPageXML();
2406 return count( $this->multiPageXML
->xpath( '//OBJECT' ) );
2412 * Wrapper class for thumbnail images
2413 * @package MediaWiki
2415 class ThumbnailImage
{
2417 * @param string $path Filesystem path to the thumb
2418 * @param string $url URL path to the thumb
2421 function ThumbnailImage( $url, $width, $height, $path = false ) {
2423 $this->width
= round( $width );
2424 $this->height
= round( $height );
2425 # These should be integers when they get here.
2426 # If not, there's a bug somewhere. But let's at
2427 # least produce valid HTML code regardless.
2428 $this->path
= $path;
2432 * @return string The thumbnail URL
2439 * Return HTML <img ... /> tag for the thumbnail, will include
2440 * width and height attributes and a blank alt text (as required).
2442 * You can set or override additional attributes by passing an
2443 * associative array of name => data pairs. The data will be escaped
2444 * for HTML output, so should be in plaintext.
2446 * @param array $attribs
2450 function toHtml( $attribs = array() ) {
2451 $attribs['src'] = $this->url
;
2452 $attribs['width'] = $this->width
;
2453 $attribs['height'] = $this->height
;
2454 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2457 foreach( $attribs as $name => $data ) {
2458 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';