Fix #6622: image::newFromTitle deprecated but still used
[mediawiki.git] / includes / Image.php
blobc5cf3e9e575366ce4ce02d82df6adae77f6632b9
1 <?php
2 /**
3 * @package MediaWiki
4 */
6 /**
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
15 /**
16 * Bump this number when serialized cache records may be incompatible.
18 define( 'MW_IMAGE_VERSION', 1 );
20 /**
21 * Class to represent an image
23 * Provides methods to retrieve paths (physical, logical, URL),
24 * to generate thumbnails or for uploading.
25 * @package MediaWiki
27 class Image
29 /**#@+
30 * @private
32 var $name, # name of the image (constructor)
33 $imagePath, # Path of the image (loadFromXxx)
34 $url, # Image URL (accessor)
35 $title, # Title object for this image (constructor)
36 $fileExists, # does the image file exist on disk? (loadFromXxx)
37 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
38 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
39 $historyRes, # result of the query for the image's history (nextHistoryLine)
40 $width, # \
41 $height, # |
42 $bits, # --- returned by getimagesize (loadFromXxx)
43 $attr, # /
44 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
45 $mime, # MIME type, determined by MimeMagic::guessMimeType
46 $size, # Size in bytes (loadFromXxx)
47 $metadata, # Metadata
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $lastError; # Error string associated with a thumbnail display error
52 /**#@-*/
54 /**
55 * Create an Image object from an image name
57 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
58 * @public
60 function newFromName( $name ) {
61 $title = Title::makeTitleSafe( NS_IMAGE, $name );
62 if ( is_object( $title ) ) {
63 return new Image( $title );
64 } else {
65 return NULL;
69 function Image( $title ) {
70 if( !is_object( $title ) ) {
71 throw new MWException( 'Image constructor given bogus title.' );
73 $this->title =& $title;
74 $this->name = $title->getDBkey();
75 $this->metadata = serialize ( array() ) ;
77 $n = strrpos( $this->name, '.' );
78 $this->extension = Image::normalizeExtension( $n ?
79 substr( $this->name, $n + 1 ) : '' );
80 $this->historyLine = 0;
82 $this->dataLoaded = false;
86 /**
87 * Normalize a file extension to the common form, and ensure it's clean.
88 * Extensions with non-alphanumeric characters will be discarded.
90 * @param $ext string (without the .)
91 * @return string
93 static function normalizeExtension( $ext ) {
94 $lower = strtolower( $ext );
95 $squish = array(
96 'htm' => 'html',
97 'jpeg' => 'jpg',
98 'mpeg' => 'mpg',
99 'tiff' => 'tif' );
100 if( isset( $squish[$lower] ) ) {
101 return $squish[$lower];
102 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
103 return $lower;
104 } else {
105 return '';
110 * Get the memcached keys
111 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
113 function getCacheKeys( ) {
114 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
116 $hashedName = md5($this->name);
117 $keys = array( "$wgDBname:Image:$hashedName" );
118 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
119 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
121 return $keys;
125 * Try to load image metadata from memcached. Returns true on success.
127 function loadFromCache() {
128 global $wgUseSharedUploads, $wgMemc;
129 wfProfileIn( __METHOD__ );
130 $this->dataLoaded = false;
131 $keys = $this->getCacheKeys();
132 $cachedValues = $wgMemc->get( $keys[0] );
134 // Check if the key existed and belongs to this version of MediaWiki
135 if (!empty($cachedValues) && is_array($cachedValues)
136 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
137 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
139 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
140 # if this is shared file, we need to check if image
141 # in shared repository has not changed
142 if ( isset( $keys[1] ) ) {
143 $commonsCachedValues = $wgMemc->get( $keys[1] );
144 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
145 && isset($commonsCachedValues['version'])
146 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
147 && isset($commonsCachedValues['mime'])) {
148 wfDebug( "Pulling image metadata from shared repository cache\n" );
149 $this->name = $commonsCachedValues['name'];
150 $this->imagePath = $commonsCachedValues['imagePath'];
151 $this->fileExists = $commonsCachedValues['fileExists'];
152 $this->width = $commonsCachedValues['width'];
153 $this->height = $commonsCachedValues['height'];
154 $this->bits = $commonsCachedValues['bits'];
155 $this->type = $commonsCachedValues['type'];
156 $this->mime = $commonsCachedValues['mime'];
157 $this->metadata = $commonsCachedValues['metadata'];
158 $this->size = $commonsCachedValues['size'];
159 $this->fromSharedDirectory = true;
160 $this->dataLoaded = true;
161 $this->imagePath = $this->getFullPath(true);
164 } else {
165 wfDebug( "Pulling image metadata from local cache\n" );
166 $this->name = $cachedValues['name'];
167 $this->imagePath = $cachedValues['imagePath'];
168 $this->fileExists = $cachedValues['fileExists'];
169 $this->width = $cachedValues['width'];
170 $this->height = $cachedValues['height'];
171 $this->bits = $cachedValues['bits'];
172 $this->type = $cachedValues['type'];
173 $this->mime = $cachedValues['mime'];
174 $this->metadata = $cachedValues['metadata'];
175 $this->size = $cachedValues['size'];
176 $this->fromSharedDirectory = false;
177 $this->dataLoaded = true;
178 $this->imagePath = $this->getFullPath();
181 if ( $this->dataLoaded ) {
182 wfIncrStats( 'image_cache_hit' );
183 } else {
184 wfIncrStats( 'image_cache_miss' );
187 wfProfileOut( __METHOD__ );
188 return $this->dataLoaded;
192 * Save the image metadata to memcached
194 function saveToCache() {
195 global $wgMemc;
196 $this->load();
197 $keys = $this->getCacheKeys();
198 if ( $this->fileExists ) {
199 // We can't cache negative metadata for non-existent files,
200 // because if the file later appears in commons, the local
201 // keys won't be purged.
202 $cachedValues = array(
203 'version' => MW_IMAGE_VERSION,
204 'name' => $this->name,
205 'imagePath' => $this->imagePath,
206 'fileExists' => $this->fileExists,
207 'fromShared' => $this->fromSharedDirectory,
208 'width' => $this->width,
209 'height' => $this->height,
210 'bits' => $this->bits,
211 'type' => $this->type,
212 'mime' => $this->mime,
213 'metadata' => $this->metadata,
214 'size' => $this->size );
216 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
217 } else {
218 // However we should clear them, so they aren't leftover
219 // if we've deleted the file.
220 $wgMemc->delete( $keys[0] );
225 * Load metadata from the file itself
227 function loadFromFile() {
228 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
229 wfProfileIn( __METHOD__ );
230 $this->imagePath = $this->getFullPath();
231 $this->fileExists = file_exists( $this->imagePath );
232 $this->fromSharedDirectory = false;
233 $gis = array();
235 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
237 # If the file is not found, and a shared upload directory is used, look for it there.
238 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
239 # In case we're on a wgCapitalLinks=false wiki, we
240 # capitalize the first letter of the filename before
241 # looking it up in the shared repository.
242 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
243 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
244 if ( $this->fileExists ) {
245 $this->name = $sharedImage->name;
246 $this->imagePath = $this->getFullPath(true);
247 $this->fromSharedDirectory = true;
252 if ( $this->fileExists ) {
253 $magic=& wfGetMimeMagic();
255 $this->mime = $magic->guessMimeType($this->imagePath,true);
256 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
258 # Get size in bytes
259 $this->size = filesize( $this->imagePath );
261 $magic=& wfGetMimeMagic();
263 # Height and width
264 wfSuppressWarnings();
265 if( $this->mime == 'image/svg' ) {
266 $gis = wfGetSVGsize( $this->imagePath );
267 } elseif( $this->mime == 'image/vnd.djvu' ) {
268 $deja = new DjVuImage( $this->imagePath );
269 $gis = $deja->getImageSize();
270 } elseif ( !$magic->isPHPImageType( $this->mime ) ) {
271 # Don't try to get the width and height of sound and video files, that's bad for performance
272 $gis = false;
273 } else {
274 $gis = getimagesize( $this->imagePath );
276 wfRestoreWarnings();
278 wfDebug(__METHOD__.': '.$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
280 else {
281 $this->mime = NULL;
282 $this->type = MEDIATYPE_UNKNOWN;
283 wfDebug(__METHOD__.': '.$this->imagePath." NOT FOUND!\n");
286 if( $gis ) {
287 $this->width = $gis[0];
288 $this->height = $gis[1];
289 } else {
290 $this->width = 0;
291 $this->height = 0;
294 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
296 #NOTE: we have to set this flag early to avoid load() to be called
297 # be some of the functions below. This may lead to recursion or other bad things!
298 # as ther's only one thread of execution, this should be safe anyway.
299 $this->dataLoaded = true;
302 $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
304 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
305 else $this->bits = 0;
307 wfProfileOut( __METHOD__ );
311 * Load image metadata from the DB
313 function loadFromDB() {
314 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
315 wfProfileIn( __METHOD__ );
317 $dbr =& wfGetDB( DB_SLAVE );
319 $this->checkDBSchema($dbr);
321 $row = $dbr->selectRow( 'image',
322 array( 'img_size', 'img_width', 'img_height', 'img_bits',
323 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
324 array( 'img_name' => $this->name ), __METHOD__ );
325 if ( $row ) {
326 $this->fromSharedDirectory = false;
327 $this->fileExists = true;
328 $this->loadFromRow( $row );
329 $this->imagePath = $this->getFullPath();
330 // Check for rows from a previous schema, quietly upgrade them
331 if ( is_null($this->type) ) {
332 $this->upgradeRow();
334 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
335 # In case we're on a wgCapitalLinks=false wiki, we
336 # capitalize the first letter of the filename before
337 # looking it up in the shared repository.
338 $name = $wgContLang->ucfirst($this->name);
339 $dbc =& wfGetDB( DB_SLAVE, 'commons' );
341 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
342 array(
343 'img_size', 'img_width', 'img_height', 'img_bits',
344 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
345 array( 'img_name' => $name ), __METHOD__ );
346 if ( $row ) {
347 $this->fromSharedDirectory = true;
348 $this->fileExists = true;
349 $this->imagePath = $this->getFullPath(true);
350 $this->name = $name;
351 $this->loadFromRow( $row );
353 // Check for rows from a previous schema, quietly upgrade them
354 if ( is_null($this->type) ) {
355 $this->upgradeRow();
360 if ( !$row ) {
361 $this->size = 0;
362 $this->width = 0;
363 $this->height = 0;
364 $this->bits = 0;
365 $this->type = 0;
366 $this->fileExists = false;
367 $this->fromSharedDirectory = false;
368 $this->metadata = serialize ( array() ) ;
371 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
372 $this->dataLoaded = true;
373 wfProfileOut( __METHOD__ );
377 * Load image metadata from a DB result row
379 function loadFromRow( &$row ) {
380 $this->size = $row->img_size;
381 $this->width = $row->img_width;
382 $this->height = $row->img_height;
383 $this->bits = $row->img_bits;
384 $this->type = $row->img_media_type;
386 $major= $row->img_major_mime;
387 $minor= $row->img_minor_mime;
389 if (!$major) $this->mime = "unknown/unknown";
390 else {
391 if (!$minor) $minor= "unknown";
392 $this->mime = $major.'/'.$minor;
395 $this->metadata = $row->img_metadata;
396 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
398 $this->dataLoaded = true;
402 * Load image metadata from cache or DB, unless already loaded
404 function load() {
405 global $wgSharedUploadDBname, $wgUseSharedUploads;
406 if ( !$this->dataLoaded ) {
407 if ( !$this->loadFromCache() ) {
408 $this->loadFromDB();
409 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
410 $this->loadFromFile();
411 } elseif ( $this->fileExists ) {
412 $this->saveToCache();
415 $this->dataLoaded = true;
420 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
421 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
423 function upgradeRow() {
424 global $wgDBname, $wgSharedUploadDBname;
425 wfProfileIn( __METHOD__ );
427 $this->loadFromFile();
429 if ( $this->fromSharedDirectory ) {
430 if ( !$wgSharedUploadDBname ) {
431 wfProfileOut( __METHOD__ );
432 return;
435 // Write to the other DB using selectDB, not database selectors
436 // This avoids breaking replication in MySQL
437 $dbw =& wfGetDB( DB_MASTER, 'commons' );
438 $dbw->selectDB( $wgSharedUploadDBname );
439 } else {
440 $dbw =& wfGetDB( DB_MASTER );
443 $this->checkDBSchema($dbw);
445 list( $major, $minor ) = self::splitMime( $this->mime );
447 wfDebug(__METHOD__.': upgrading '.$this->name." to 1.5 schema\n");
449 $dbw->update( 'image',
450 array(
451 'img_width' => $this->width,
452 'img_height' => $this->height,
453 'img_bits' => $this->bits,
454 'img_media_type' => $this->type,
455 'img_major_mime' => $major,
456 'img_minor_mime' => $minor,
457 'img_metadata' => $this->metadata,
458 ), array( 'img_name' => $this->name ), __METHOD__
460 if ( $this->fromSharedDirectory ) {
461 $dbw->selectDB( $wgDBname );
463 wfProfileOut( __METHOD__ );
467 * Split an internet media type into its two components; if not
468 * a two-part name, set the minor type to 'unknown'.
470 * @param $mime "text/html" etc
471 * @return array ("text", "html") etc
473 static function splitMime( $mime ) {
474 if( strpos( $mime, '/' ) !== false ) {
475 return explode( '/', $mime, 2 );
476 } else {
477 return array( $mime, 'unknown' );
482 * Return the name of this image
483 * @public
485 function getName() {
486 return $this->name;
490 * Return the associated title object
491 * @public
493 function getTitle() {
494 return $this->title;
498 * Return the URL of the image file
499 * @public
501 function getURL() {
502 if ( !$this->url ) {
503 $this->load();
504 if($this->fileExists) {
505 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
506 } else {
507 $this->url = '';
510 return $this->url;
513 function getViewURL() {
514 if( $this->mustRender()) {
515 if( $this->canRender() ) {
516 return $this->createThumb( $this->getWidth() );
518 else {
519 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
520 return $this->getURL(); #hm... return NULL?
522 } else {
523 return $this->getURL();
528 * Return the image path of the image in the
529 * local file system as an absolute path
530 * @public
532 function getImagePath() {
533 $this->load();
534 return $this->imagePath;
538 * Return the width of the image
540 * Returns -1 if the file specified is not a known image type
541 * @public
543 function getWidth() {
544 $this->load();
545 return $this->width;
549 * Return the height of the image
551 * Returns -1 if the file specified is not a known image type
552 * @public
554 function getHeight() {
555 $this->load();
556 return $this->height;
560 * Return the size of the image file, in bytes
561 * @public
563 function getSize() {
564 $this->load();
565 return $this->size;
569 * Returns the mime type of the file.
571 function getMimeType() {
572 $this->load();
573 return $this->mime;
577 * Return the type of the media in the file.
578 * Use the value returned by this function with the MEDIATYPE_xxx constants.
580 function getMediaType() {
581 $this->load();
582 return $this->type;
586 * Checks if the file can be presented to the browser as a bitmap.
588 * Currently, this checks if the file is an image format
589 * that can be converted to a format
590 * supported by all browsers (namely GIF, PNG and JPEG),
591 * or if it is an SVG image and SVG conversion is enabled.
593 * @todo remember the result of this check.
595 function canRender() {
596 global $wgUseImageMagick;
598 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
600 $mime= $this->getMimeType();
602 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
604 #if it's SVG, check if there's a converter enabled
605 if ($mime === 'image/svg') {
606 global $wgSVGConverters, $wgSVGConverter;
608 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
609 wfDebug( "Image::canRender: SVG is ready!\n" );
610 return true;
611 } else {
612 wfDebug( "Image::canRender: SVG renderer missing\n" );
616 #image formats available on ALL browsers
617 if ( $mime === 'image/gif'
618 || $mime === 'image/png'
619 || $mime === 'image/jpeg' ) return true;
621 #image formats that can be converted to the above formats
622 if ($wgUseImageMagick) {
623 #convertable by ImageMagick (there are more...)
624 if ( $mime === 'image/vnd.wap.wbmp'
625 || $mime === 'image/x-xbitmap'
626 || $mime === 'image/x-xpixmap'
627 #|| $mime === 'image/x-icon' #file may be split into multiple parts
628 || $mime === 'image/x-portable-anymap'
629 || $mime === 'image/x-portable-bitmap'
630 || $mime === 'image/x-portable-graymap'
631 || $mime === 'image/x-portable-pixmap'
632 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
633 || $mime === 'image/x-rgb'
634 || $mime === 'image/x-bmp'
635 || $mime === 'image/tiff' ) return true;
637 else {
638 #convertable by the PHP GD image lib
639 if ( $mime === 'image/vnd.wap.wbmp'
640 || $mime === 'image/x-xbitmap' ) return true;
643 return false;
648 * Return true if the file is of a type that can't be directly
649 * rendered by typical browsers and needs to be re-rasterized.
651 * This returns true for everything but the bitmap types
652 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
653 * also return true for any non-image formats.
655 * @return bool
657 function mustRender() {
658 $mime= $this->getMimeType();
660 if ( $mime === "image/gif"
661 || $mime === "image/png"
662 || $mime === "image/jpeg" ) return false;
664 return true;
668 * Determines if this media file may be shown inline on a page.
670 * This is currently synonymous to canRender(), but this could be
671 * extended to also allow inline display of other media,
672 * like flash animations or videos. If you do so, please keep in mind that
673 * that could be a security risk.
675 function allowInlineDisplay() {
676 return $this->canRender();
680 * Determines if this media file is in a format that is unlikely to
681 * contain viruses or malicious content. It uses the global
682 * $wgTrustedMediaFormats list to determine if the file is safe.
684 * This is used to show a warning on the description page of non-safe files.
685 * It may also be used to disallow direct [[media:...]] links to such files.
687 * Note that this function will always return true if allowInlineDisplay()
688 * or isTrustedFile() is true for this file.
690 function isSafeFile() {
691 if ($this->allowInlineDisplay()) return true;
692 if ($this->isTrustedFile()) return true;
694 global $wgTrustedMediaFormats;
696 $type= $this->getMediaType();
697 $mime= $this->getMimeType();
698 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
700 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
701 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
703 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
704 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
706 return false;
709 /** Returns true if the file is flagged as trusted. Files flagged that way
710 * can be linked to directly, even if that is not allowed for this type of
711 * file normally.
713 * This is a dummy function right now and always returns false. It could be
714 * implemented to extract a flag from the database. The trusted flag could be
715 * set on upload, if the user has sufficient privileges, to bypass script-
716 * and html-filters. It may even be coupled with cryptographics signatures
717 * or such.
719 function isTrustedFile() {
720 #this could be implemented to check a flag in the databas,
721 #look for signatures, etc
722 return false;
726 * Return the escapeLocalURL of this image
727 * @public
729 function getEscapeLocalURL() {
730 $this->getTitle();
731 return $this->title->escapeLocalURL();
735 * Return the escapeFullURL of this image
736 * @public
738 function getEscapeFullURL() {
739 $this->getTitle();
740 return $this->title->escapeFullURL();
744 * Return the URL of an image, provided its name.
746 * @param string $name Name of the image, without the leading "Image:"
747 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
748 * @return string URL of $name image
749 * @public
750 * @static
752 function imageUrl( $name, $fromSharedDirectory = false ) {
753 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
754 if($fromSharedDirectory) {
755 $base = '';
756 $path = $wgSharedUploadPath;
757 } else {
758 $base = $wgUploadBaseUrl;
759 $path = $wgUploadPath;
761 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
762 return wfUrlencode( $url );
766 * Returns true if the image file exists on disk.
767 * @return boolean Whether image file exist on disk.
768 * @public
770 function exists() {
771 $this->load();
772 return $this->fileExists;
776 * @todo document
777 * @private
779 function thumbUrl( $width, $subdir='thumb') {
780 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
781 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
783 // Generate thumb.php URL if possible
784 $script = false;
785 $url = false;
787 if ( $this->fromSharedDirectory ) {
788 if ( $wgSharedThumbnailScriptPath ) {
789 $script = $wgSharedThumbnailScriptPath;
791 } else {
792 if ( $wgThumbnailScriptPath ) {
793 $script = $wgThumbnailScriptPath;
796 if ( $script ) {
797 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
798 if( $this->mustRender() ) {
799 $url.= '&r=1';
801 } else {
802 $name = $this->thumbName( $width );
803 if($this->fromSharedDirectory) {
804 $base = '';
805 $path = $wgSharedUploadPath;
806 } else {
807 $base = $wgUploadBaseUrl;
808 $path = $wgUploadPath;
810 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
811 $url = "{$base}{$path}/{$subdir}" .
812 wfGetHashPath($this->name, $this->fromSharedDirectory)
813 . $this->name.'/'.$name;
814 $url = wfUrlencode( $url );
815 } else {
816 $url = "{$base}{$path}/{$subdir}/{$name}";
819 return array( $script !== false, $url );
823 * Return the file name of a thumbnail of the specified width
825 * @param integer $width Width of the thumbnail image
826 * @param boolean $shared Does the thumbnail come from the shared repository?
827 * @private
829 function thumbName( $width ) {
830 $thumb = $width."px-".$this->name;
832 if( $this->mustRender() ) {
833 if( $this->canRender() ) {
834 # Rasterize to PNG (for SVG vector images, etc)
835 $thumb .= '.png';
837 else {
838 #should we use iconThumb here to get a symbolic thumbnail?
839 #or should we fail with an internal error?
840 return NULL; //can't make bitmap
843 return $thumb;
847 * Create a thumbnail of the image having the specified width/height.
848 * The thumbnail will not be created if the width is larger than the
849 * image's width. Let the browser do the scaling in this case.
850 * The thumbnail is stored on disk and is only computed if the thumbnail
851 * file does not exist OR if it is older than the image.
852 * Returns the URL.
854 * Keeps aspect ratio of original image. If both width and height are
855 * specified, the generated image will be no bigger than width x height,
856 * and will also have correct aspect ratio.
858 * @param integer $width maximum width of the generated thumbnail
859 * @param integer $height maximum height of the image (optional)
860 * @public
862 function createThumb( $width, $height=-1 ) {
863 $thumb = $this->getThumbnail( $width, $height );
864 if( is_null( $thumb ) ) return '';
865 return $thumb->getUrl();
869 * As createThumb, but returns a ThumbnailImage object. This can
870 * provide access to the actual file, the real size of the thumb,
871 * and can produce a convenient <img> tag for you.
873 * For non-image formats, this may return a filetype-specific icon.
875 * @param integer $width maximum width of the generated thumbnail
876 * @param integer $height maximum height of the image (optional)
877 * @param boolean $render True to render the thumbnail if it doesn't exist,
878 * false to just return the URL
880 * @return ThumbnailImage or null on failure
881 * @public
883 function getThumbnail( $width, $height=-1, $render = true ) {
884 wfProfileIn( __METHOD__ );
885 if ($this->canRender()) {
886 if ( $height > 0 ) {
887 $this->load();
888 if ( $width > $this->width * $height / $this->height ) {
889 $width = wfFitBoxWidth( $this->width, $this->height, $height );
892 if ( $render ) {
893 $thumb = $this->renderThumb( $width );
894 } else {
895 // Don't render, just return the URL
896 if ( $this->validateThumbParams( $width, $height ) ) {
897 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
898 $url = $this->getURL();
899 } else {
900 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
902 $thumb = new ThumbnailImage( $url, $width, $height );
903 } else {
904 $thumb = null;
907 } else {
908 // not a bitmap or renderable image, don't try.
909 $thumb = $this->iconThumb();
911 wfProfileOut( __METHOD__ );
912 return $thumb;
916 * @return ThumbnailImage
918 function iconThumb() {
919 global $wgStylePath, $wgStyleDirectory;
921 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
922 foreach( $try as $icon ) {
923 $path = '/common/images/icons/' . $icon;
924 $filepath = $wgStyleDirectory . $path;
925 if( file_exists( $filepath ) ) {
926 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
929 return null;
933 * Validate thumbnail parameters and fill in the correct height
935 * @param integer &$width Specified width (input/output)
936 * @param integer &$height Height (output only)
937 * @return false to indicate that an error should be returned to the user.
939 function validateThumbParams( &$width, &$height ) {
940 global $wgSVGMaxSize, $wgMaxImageArea;
942 $this->load();
944 if ( ! $this->exists() )
946 # If there is no image, there will be no thumbnail
947 return false;
950 $width = intval( $width );
952 # Sanity check $width
953 if( $width <= 0 || $this->width <= 0) {
954 # BZZZT
955 return false;
958 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
959 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
960 # an exception for it.
961 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
962 $this->getMimeType() !== 'image/jpeg' &&
963 $this->width * $this->height > $wgMaxImageArea )
965 return false;
968 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
969 if ( $this->mustRender() ) {
970 $width = min( $width, $wgSVGMaxSize );
971 } elseif ( $width > $this->width - 1 ) {
972 $width = $this->width;
973 $height = $this->height;
974 return true;
977 $height = round( $this->height * $width / $this->width );
978 return true;
982 * Create a thumbnail of the image having the specified width.
983 * The thumbnail will not be created if the width is larger than the
984 * image's width. Let the browser do the scaling in this case.
985 * The thumbnail is stored on disk and is only computed if the thumbnail
986 * file does not exist OR if it is older than the image.
987 * Returns an object which can return the pathname, URL, and physical
988 * pixel size of the thumbnail -- or null on failure.
990 * @return ThumbnailImage or null on failure
991 * @private
993 function renderThumb( $width, $useScript = true ) {
994 global $wgUseSquid, $wgThumbnailEpoch;
996 wfProfileIn( __METHOD__ );
998 $this->load();
999 $height = -1;
1000 if ( !$this->validateThumbParams( $width, $height ) ) {
1001 # Validation error
1002 wfProfileOut( __METHOD__ );
1003 return null;
1006 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
1007 # validateThumbParams (or the user) wants us to return the unscaled image
1008 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1009 wfProfileOut( __METHOD__ );
1010 return $thumb;
1013 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1014 if ( $isScriptUrl && $useScript ) {
1015 // Use thumb.php to render the image
1016 $thumb = new ThumbnailImage( $url, $width, $height );
1017 wfProfileOut( __METHOD__ );
1018 return $thumb;
1021 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
1022 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
1023 $thumbPath = $thumbDir.'/'.$thumbName;
1025 if ( is_dir( $thumbPath ) ) {
1026 // Directory where file should be
1027 // This happened occasionally due to broken migration code in 1.5
1028 // Rename to broken-*
1029 global $wgUploadDirectory;
1030 for ( $i = 0; $i < 100 ; $i++ ) {
1031 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1032 if ( !file_exists( $broken ) ) {
1033 rename( $thumbPath, $broken );
1034 break;
1037 // Code below will ask if it exists, and the answer is now no
1038 clearstatcache();
1041 $done = true;
1042 if ( !file_exists( $thumbPath ) ||
1043 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) )
1045 // Create the directory if it doesn't exist
1046 if ( is_file( $thumbDir ) ) {
1047 // File where thumb directory should be, destroy if possible
1048 @unlink( $thumbDir );
1050 wfMkdirParents( $thumbDir );
1052 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
1053 '/'.$thumbName;
1054 $done = false;
1056 // Migration from old directory structure
1057 if ( is_file( $oldThumbPath ) ) {
1058 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
1059 if ( file_exists( $thumbPath ) ) {
1060 if ( !is_dir( $thumbPath ) ) {
1061 // Old image in the way of rename
1062 unlink( $thumbPath );
1063 } else {
1064 // This should have been dealt with already
1065 throw new MWException( "Directory where image should be: $thumbPath" );
1068 // Rename the old image into the new location
1069 rename( $oldThumbPath, $thumbPath );
1070 $done = true;
1071 } else {
1072 unlink( $oldThumbPath );
1075 if ( !$done ) {
1076 $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
1077 if ( $this->lastError === true ) {
1078 $done = true;
1079 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1080 // Log the error but output anyway.
1081 // With luck it's a transitory error...
1082 $done = true;
1085 # Purge squid
1086 # This has to be done after the image is updated and present for all machines on NFS,
1087 # or else the old version might be stored into the squid again
1088 if ( $wgUseSquid ) {
1089 $urlArr = array( $url );
1090 wfPurgeSquidServers($urlArr);
1095 if ( $done ) {
1096 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1097 } else {
1098 $thumb = null;
1100 wfProfileOut( __METHOD__ );
1101 return $thumb;
1102 } // END OF function renderThumb
1105 * Really render a thumbnail
1106 * Call this only for images for which canRender() returns true.
1108 * @param string $thumbPath Path to thumbnail
1109 * @param int $width Desired width in pixels
1110 * @param int $height Desired height in pixels
1111 * @return bool True on error, false or error string on failure.
1112 * @private
1114 function reallyRenderThumb( $thumbPath, $width, $height ) {
1115 global $wgSVGConverters, $wgSVGConverter;
1116 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1117 global $wgCustomConvertCommand;
1119 $this->load();
1121 $err = false;
1122 $cmd = "";
1123 $retval = 0;
1125 if( $this->mime === "image/svg" ) {
1126 #Right now we have only SVG
1128 global $wgSVGConverters, $wgSVGConverter;
1129 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1130 global $wgSVGConverterPath;
1131 $cmd = str_replace(
1132 array( '$path/', '$width', '$height', '$input', '$output' ),
1133 array( $wgSVGConverterPath ? "$wgSVGConverterPath/" : "",
1134 intval( $width ),
1135 intval( $height ),
1136 wfEscapeShellArg( $this->imagePath ),
1137 wfEscapeShellArg( $thumbPath ) ),
1138 $wgSVGConverters[$wgSVGConverter] );
1139 wfProfileIn( 'rsvg' );
1140 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1141 $err = wfShellExec( $cmd, $retval );
1142 wfProfileOut( 'rsvg' );
1144 } elseif ( $wgUseImageMagick ) {
1145 # use ImageMagick
1147 if ( $this->mime == 'image/jpeg' ) {
1148 $quality = "-quality 80"; // 80%
1149 } elseif ( $this->mime == 'image/png' ) {
1150 $quality = "-quality 95"; // zlib 9, adaptive filtering
1151 } else {
1152 $quality = ''; // default
1155 # Specify white background color, will be used for transparent images
1156 # in Internet Explorer/Windows instead of default black.
1158 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1159 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1160 # the wrong size in the second case.
1162 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1163 " {$quality} -background white -size {$width} ".
1164 wfEscapeShellArg($this->imagePath) .
1165 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1166 ' -coalesce ' .
1167 // For the -resize option a "!" is needed to force exact size,
1168 // or ImageMagick may decide your ratio is wrong and slice off
1169 // a pixel.
1170 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1171 " -depth 8 " .
1172 wfEscapeShellArg($thumbPath) . " 2>&1";
1173 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1174 wfProfileIn( 'convert' );
1175 $err = wfShellExec( $cmd, $retval );
1176 wfProfileOut( 'convert' );
1177 } elseif( $wgCustomConvertCommand ) {
1178 # Use a custom convert command
1179 # Variables: %s %d %w %h
1180 $src = wfEscapeShellArg( $this->imagePath );
1181 $dst = wfEscapeShellArg( $thumbPath );
1182 $cmd = $wgCustomConvertCommand;
1183 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1184 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1185 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1186 wfProfileIn( 'convert' );
1187 $err = wfShellExec( $cmd, $retval );
1188 wfProfileOut( 'convert' );
1189 } else {
1190 # Use PHP's builtin GD library functions.
1192 # First find out what kind of file this is, and select the correct
1193 # input routine for this.
1195 $typemap = array(
1196 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1197 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1198 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1199 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1200 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1202 if( !isset( $typemap[$this->mime] ) ) {
1203 $err = 'Image type not supported';
1204 wfDebug( "$err\n" );
1205 return $err;
1207 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1209 if( !function_exists( $loader ) ) {
1210 $err = "Incomplete GD library configuration: missing function $loader";
1211 wfDebug( "$err\n" );
1212 return $err;
1214 if( $colorStyle == 'palette' ) {
1215 $truecolor = false;
1216 } elseif( $colorStyle == 'truecolor' ) {
1217 $truecolor = true;
1218 } elseif( $colorStyle == 'bits' ) {
1219 $truecolor = ( $this->bits > 8 );
1222 $src_image = call_user_func( $loader, $this->imagePath );
1223 if ( $truecolor ) {
1224 $dst_image = imagecreatetruecolor( $width, $height );
1225 } else {
1226 $dst_image = imagecreate( $width, $height );
1228 imagecopyresampled( $dst_image, $src_image,
1229 0,0,0,0,
1230 $width, $height, $this->width, $this->height );
1231 call_user_func( $saveType, $dst_image, $thumbPath );
1232 imagedestroy( $dst_image );
1233 imagedestroy( $src_image );
1237 # Check for zero-sized thumbnails. Those can be generated when
1238 # no disk space is available or some other error occurs
1240 if( file_exists( $thumbPath ) ) {
1241 $thumbstat = stat( $thumbPath );
1242 if( $thumbstat['size'] == 0 || $retval != 0 ) {
1243 wfDebugLog( 'thumbnail',
1244 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1245 $thumbstat['size'], $thumbPath ) );
1246 unlink( $thumbPath );
1249 if ( $retval != 0 ) {
1250 wfDebugLog( 'thumbnail',
1251 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1252 wfHostname(), $retval, trim($err), $cmd ) );
1253 return wfMsg( 'thumbnail_error', $err );
1254 } else {
1255 return true;
1259 function getLastError() {
1260 return $this->lastError;
1263 function imageJpegWrapper( $dst_image, $thumbPath ) {
1264 imageinterlace( $dst_image );
1265 imagejpeg( $dst_image, $thumbPath, 95 );
1269 * Get all thumbnail names previously generated for this image
1271 function getThumbnails( $shared = false ) {
1272 if ( Image::isHashed( $shared ) ) {
1273 $this->load();
1274 $files = array();
1275 $dir = wfImageThumbDir( $this->name, $shared );
1277 // This generates an error on failure, hence the @
1278 $handle = @opendir( $dir );
1280 if ( $handle ) {
1281 while ( false !== ( $file = readdir($handle) ) ) {
1282 if ( $file{0} != '.' ) {
1283 $files[] = $file;
1286 closedir( $handle );
1288 } else {
1289 $files = array();
1292 return $files;
1296 * Refresh metadata in memcached, but don't touch thumbnails or squid
1298 function purgeMetadataCache() {
1299 clearstatcache();
1300 $this->loadFromFile();
1301 $this->saveToCache();
1305 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1307 function purgeCache( $archiveFiles = array(), $shared = false ) {
1308 global $wgUseSquid;
1310 // Refresh metadata cache
1311 $this->purgeMetadataCache();
1313 // Delete thumbnails
1314 $files = $this->getThumbnails( $shared );
1315 $dir = wfImageThumbDir( $this->name, $shared );
1316 $urls = array();
1317 foreach ( $files as $file ) {
1318 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1319 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1320 @unlink( "$dir/$file" );
1324 // Purge the squid
1325 if ( $wgUseSquid ) {
1326 $urls[] = $this->getViewURL();
1327 foreach ( $archiveFiles as $file ) {
1328 $urls[] = wfImageArchiveUrl( $file );
1330 wfPurgeSquidServers( $urls );
1335 * Purge the image description page, but don't go after
1336 * pages using the image. Use when modifying file history
1337 * but not the current data.
1339 function purgeDescription() {
1340 $page = Title::makeTitle( NS_IMAGE, $this->name );
1341 $page->invalidateCache();
1342 $page->purgeSquid();
1346 * Purge metadata and all affected pages when the image is created,
1347 * deleted, or majorly updated. A set of additional URLs may be
1348 * passed to purge, such as specific image files which have changed.
1349 * @param $urlArray array
1351 function purgeEverything( $urlArr=array() ) {
1352 // Delete thumbnails and refresh image metadata cache
1353 $this->purgeCache();
1354 $this->purgeDescription();
1356 // Purge cache of all pages using this image
1357 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1358 $update->doUpdate();
1361 function checkDBSchema(&$db) {
1362 global $wgCheckDBSchema;
1363 if (!$wgCheckDBSchema) {
1364 return;
1366 # img_name must be unique
1367 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1368 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1371 # new fields must exist
1373 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1374 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1375 # something. The only reason I put the above schema check in was because the absence of that particular
1376 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1377 # uploads. -- TS
1379 if ( !$db->fieldExists( 'image', 'img_media_type' )
1380 || !$db->fieldExists( 'image', 'img_metadata' )
1381 || !$db->fieldExists( 'image', 'img_width' ) ) {
1383 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1389 * Return the image history of this image, line by line.
1390 * starts with current version, then old versions.
1391 * uses $this->historyLine to check which line to return:
1392 * 0 return line for current version
1393 * 1 query for old versions, return first one
1394 * 2, ... return next old version from above query
1396 * @public
1398 function nextHistoryLine() {
1399 $dbr =& wfGetDB( DB_SLAVE );
1401 $this->checkDBSchema($dbr);
1403 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1404 $this->historyRes = $dbr->select( 'image',
1405 array(
1406 'img_size',
1407 'img_description',
1408 'img_user','img_user_text',
1409 'img_timestamp',
1410 'img_width',
1411 'img_height',
1412 "'' AS oi_archive_name"
1414 array( 'img_name' => $this->title->getDBkey() ),
1415 __METHOD__
1417 if ( 0 == wfNumRows( $this->historyRes ) ) {
1418 return FALSE;
1420 } else if ( $this->historyLine == 1 ) {
1421 $this->historyRes = $dbr->select( 'oldimage',
1422 array(
1423 'oi_size AS img_size',
1424 'oi_description AS img_description',
1425 'oi_user AS img_user',
1426 'oi_user_text AS img_user_text',
1427 'oi_timestamp AS img_timestamp',
1428 'oi_width as img_width',
1429 'oi_height as img_height',
1430 'oi_archive_name'
1432 array( 'oi_name' => $this->title->getDBkey() ),
1433 __METHOD__,
1434 array( 'ORDER BY' => 'oi_timestamp DESC' )
1437 $this->historyLine ++;
1439 return $dbr->fetchObject( $this->historyRes );
1443 * Reset the history pointer to the first element of the history
1444 * @public
1446 function resetHistory() {
1447 $this->historyLine = 0;
1451 * Return the full filesystem path to the file. Note that this does
1452 * not mean that a file actually exists under that location.
1454 * This path depends on whether directory hashing is active or not,
1455 * i.e. whether the images are all found in the same directory,
1456 * or in hashed paths like /images/3/3c.
1458 * @public
1459 * @param boolean $fromSharedDirectory Return the path to the file
1460 * in a shared repository (see $wgUseSharedRepository and related
1461 * options in DefaultSettings.php) instead of a local one.
1464 function getFullPath( $fromSharedRepository = false ) {
1465 global $wgUploadDirectory, $wgSharedUploadDirectory;
1467 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1468 $wgUploadDirectory;
1470 // $wgSharedUploadDirectory may be false, if thumb.php is used
1471 if ( $dir ) {
1472 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1473 } else {
1474 $fullpath = false;
1477 return $fullpath;
1481 * @return bool
1482 * @static
1484 public static function isHashed( $shared ) {
1485 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1486 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1490 * Record an image upload in the upload log and the image table
1492 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1493 global $wgUser, $wgUseCopyrightUpload;
1495 $dbw =& wfGetDB( DB_MASTER );
1497 $this->checkDBSchema($dbw);
1499 // Delete thumbnails and refresh the metadata cache
1500 $this->purgeCache();
1502 // Fail now if the image isn't there
1503 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1504 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1505 return false;
1508 if ( $wgUseCopyrightUpload ) {
1509 if ( $license != '' ) {
1510 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1512 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1513 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1514 "$licensetxt" .
1515 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1516 } else {
1517 if ( $license != '' ) {
1518 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1519 $textdesc = $filedesc .
1520 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1521 } else {
1522 $textdesc = $desc;
1526 $now = $dbw->timestamp();
1528 #split mime type
1529 if (strpos($this->mime,'/')!==false) {
1530 list($major,$minor)= explode('/',$this->mime,2);
1532 else {
1533 $major= $this->mime;
1534 $minor= "unknown";
1537 # Test to see if the row exists using INSERT IGNORE
1538 # This avoids race conditions by locking the row until the commit, and also
1539 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1540 $dbw->insert( 'image',
1541 array(
1542 'img_name' => $this->name,
1543 'img_size'=> $this->size,
1544 'img_width' => intval( $this->width ),
1545 'img_height' => intval( $this->height ),
1546 'img_bits' => $this->bits,
1547 'img_media_type' => $this->type,
1548 'img_major_mime' => $major,
1549 'img_minor_mime' => $minor,
1550 'img_timestamp' => $now,
1551 'img_description' => $desc,
1552 'img_user' => $wgUser->getID(),
1553 'img_user_text' => $wgUser->getName(),
1554 'img_metadata' => $this->metadata,
1556 __METHOD__,
1557 'IGNORE'
1560 if( $dbw->affectedRows() == 0 ) {
1561 # Collision, this is an update of an image
1562 # Insert previous contents into oldimage
1563 $dbw->insertSelect( 'oldimage', 'image',
1564 array(
1565 'oi_name' => 'img_name',
1566 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1567 'oi_size' => 'img_size',
1568 'oi_width' => 'img_width',
1569 'oi_height' => 'img_height',
1570 'oi_bits' => 'img_bits',
1571 'oi_timestamp' => 'img_timestamp',
1572 'oi_description' => 'img_description',
1573 'oi_user' => 'img_user',
1574 'oi_user_text' => 'img_user_text',
1575 ), array( 'img_name' => $this->name ), __METHOD__
1578 # Update the current image row
1579 $dbw->update( 'image',
1580 array( /* SET */
1581 'img_size' => $this->size,
1582 'img_width' => intval( $this->width ),
1583 'img_height' => intval( $this->height ),
1584 'img_bits' => $this->bits,
1585 'img_media_type' => $this->type,
1586 'img_major_mime' => $major,
1587 'img_minor_mime' => $minor,
1588 'img_timestamp' => $now,
1589 'img_description' => $desc,
1590 'img_user' => $wgUser->getID(),
1591 'img_user_text' => $wgUser->getName(),
1592 'img_metadata' => $this->metadata,
1593 ), array( /* WHERE */
1594 'img_name' => $this->name
1595 ), __METHOD__
1597 } else {
1598 # This is a new image
1599 # Update the image count
1600 $site_stats = $dbw->tableName( 'site_stats' );
1601 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1604 $descTitle = $this->getTitle();
1605 $article = new Article( $descTitle );
1606 $minor = false;
1607 $watch = $watch || $wgUser->isWatched( $descTitle );
1608 $suppressRC = true; // There's already a log entry, so don't double the RC load
1610 if( $descTitle->exists() ) {
1611 // TODO: insert a null revision into the page history for this update.
1612 if( $watch ) {
1613 $wgUser->addWatch( $descTitle );
1616 # Invalidate the cache for the description page
1617 $descTitle->invalidateCache();
1618 $descTitle->purgeSquid();
1619 } else {
1620 // New image; create the description page.
1621 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1624 # Add the log entry
1625 $log = new LogPage( 'upload' );
1626 $log->addEntry( 'upload', $descTitle, $desc );
1628 # Commit the transaction now, in case something goes wrong later
1629 # The most important thing is that images don't get lost, especially archives
1630 $dbw->immediateCommit();
1632 # Invalidate cache for all pages using this image
1633 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1634 $update->doUpdate();
1636 return true;
1640 * Get an array of Title objects which are articles which use this image
1641 * Also adds their IDs to the link cache
1643 * This is mostly copied from Title::getLinksTo()
1645 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1647 function getLinksTo( $options = '' ) {
1648 wfProfileIn( __METHOD__ );
1650 if ( $options ) {
1651 $db =& wfGetDB( DB_MASTER );
1652 } else {
1653 $db =& wfGetDB( DB_SLAVE );
1655 $linkCache =& LinkCache::singleton();
1657 extract( $db->tableNames( 'page', 'imagelinks' ) );
1658 $encName = $db->addQuotes( $this->name );
1659 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1660 $res = $db->query( $sql, __METHOD__ );
1662 $retVal = array();
1663 if ( $db->numRows( $res ) ) {
1664 while ( $row = $db->fetchObject( $res ) ) {
1665 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1666 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1667 $retVal[] = $titleObj;
1671 $db->freeResult( $res );
1672 wfProfileOut( __METHOD__ );
1673 return $retVal;
1677 * Retrive Exif data from the file and prune unrecognized tags
1678 * and/or tags with invalid contents
1680 * @param $filename
1681 * @return array
1683 private function retrieveExifData( $filename ) {
1684 global $wgShowEXIF;
1687 if ( $this->getMimeType() !== "image/jpeg" )
1688 return array();
1691 if( $wgShowEXIF && file_exists( $filename ) ) {
1692 $exif = new Exif( $filename );
1693 return $exif->getFilteredData();
1696 return array();
1699 function getExifData() {
1700 global $wgRequest;
1701 if ( $this->metadata === '0' )
1702 return array();
1704 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1705 $ret = unserialize( $this->metadata );
1707 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1708 $newver = Exif::version();
1710 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1711 $this->purgeMetadataCache();
1712 $this->updateExifData( $newver );
1714 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1715 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1716 $format = new FormatExif( $ret );
1718 return $format->getFormattedData();
1721 function updateExifData( $version ) {
1722 if ( $this->getImagePath() === false ) # Not a local image
1723 return;
1725 # Get EXIF data from image
1726 $exif = $this->retrieveExifData( $this->imagePath );
1727 if ( count( $exif ) ) {
1728 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1729 $this->metadata = serialize( $exif );
1730 } else {
1731 $this->metadata = '0';
1734 # Update EXIF data in database
1735 $dbw =& wfGetDB( DB_MASTER );
1737 $this->checkDBSchema($dbw);
1739 $dbw->update( 'image',
1740 array( 'img_metadata' => $this->metadata ),
1741 array( 'img_name' => $this->name ),
1742 __METHOD__
1747 * Returns true if the image does not come from the shared
1748 * image repository.
1750 * @return bool
1752 function isLocal() {
1753 return !$this->fromSharedDirectory;
1757 * Was this image ever deleted from the wiki?
1759 * @return bool
1761 function wasDeleted() {
1762 $title = Title::makeTitle( NS_IMAGE, $this->name );
1763 return ( $title->isDeleted() > 0 );
1767 * Delete all versions of the image.
1769 * Moves the files into an archive directory (or deletes them)
1770 * and removes the database rows.
1772 * Cache purging is done; logging is caller's responsibility.
1774 * @param $reason
1775 * @return true on success, false on some kind of failure
1777 function delete( $reason ) {
1778 $transaction = new FSTransaction();
1779 $urlArr = array( $this->getURL() );
1781 if( !FileStore::lock() ) {
1782 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1783 return false;
1786 try {
1787 $dbw = wfGetDB( DB_MASTER );
1788 $dbw->begin();
1790 // Delete old versions
1791 $result = $dbw->select( 'oldimage',
1792 array( 'oi_archive_name' ),
1793 array( 'oi_name' => $this->name ) );
1795 while( $row = $dbw->fetchObject( $result ) ) {
1796 $oldName = $row->oi_archive_name;
1798 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1800 // We'll need to purge this URL from caches...
1801 $urlArr[] = wfImageArchiveUrl( $oldName );
1803 $dbw->freeResult( $result );
1805 // And the current version...
1806 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1808 $dbw->immediateCommit();
1809 } catch( MWException $e ) {
1810 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1811 $transaction->rollback();
1812 FileStore::unlock();
1813 throw $e;
1816 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1817 $transaction->commit();
1818 FileStore::unlock();
1821 // Update site_stats
1822 $site_stats = $dbw->tableName( 'site_stats' );
1823 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1825 $this->purgeEverything( $urlArr );
1827 return true;
1832 * Delete an old version of the image.
1834 * Moves the file into an archive directory (or deletes it)
1835 * and removes the database row.
1837 * Cache purging is done; logging is caller's responsibility.
1839 * @param $reason
1840 * @throws MWException or FSException on database or filestore failure
1841 * @return true on success, false on some kind of failure
1843 function deleteOld( $archiveName, $reason ) {
1844 $transaction = new FSTransaction();
1845 $urlArr = array();
1847 if( !FileStore::lock() ) {
1848 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1849 return false;
1852 $transaction = new FSTransaction();
1853 try {
1854 $dbw = wfGetDB( DB_MASTER );
1855 $dbw->begin();
1856 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1857 $dbw->immediateCommit();
1858 } catch( MWException $e ) {
1859 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1860 $transaction->rollback();
1861 FileStore::unlock();
1862 throw $e;
1865 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1866 $transaction->commit();
1867 FileStore::unlock();
1869 $this->purgeDescription();
1871 // Squid purging
1872 global $wgUseSquid;
1873 if ( $wgUseSquid ) {
1874 $urlArr = array(
1875 wfImageArchiveUrl( $archiveName ),
1877 wfPurgeSquidServers( $urlArr );
1879 return true;
1883 * Delete the current version of a file.
1884 * May throw a database error.
1885 * @return true on success, false on failure
1887 private function prepareDeleteCurrent( $reason ) {
1888 return $this->prepareDeleteVersion(
1889 $this->getFullPath(),
1890 $reason,
1891 'image',
1892 array(
1893 'fa_name' => 'img_name',
1894 'fa_archive_name' => 'NULL',
1895 'fa_size' => 'img_size',
1896 'fa_width' => 'img_width',
1897 'fa_height' => 'img_height',
1898 'fa_metadata' => 'img_metadata',
1899 'fa_bits' => 'img_bits',
1900 'fa_media_type' => 'img_media_type',
1901 'fa_major_mime' => 'img_major_mime',
1902 'fa_minor_mime' => 'img_minor_mime',
1903 'fa_description' => 'img_description',
1904 'fa_user' => 'img_user',
1905 'fa_user_text' => 'img_user_text',
1906 'fa_timestamp' => 'img_timestamp' ),
1907 array( 'img_name' => $this->name ),
1908 __METHOD__ );
1912 * Delete a given older version of a file.
1913 * May throw a database error.
1914 * @return true on success, false on failure
1916 private function prepareDeleteOld( $archiveName, $reason ) {
1917 $oldpath = wfImageArchiveDir( $this->name ) .
1918 DIRECTORY_SEPARATOR . $archiveName;
1919 return $this->prepareDeleteVersion(
1920 $oldpath,
1921 $reason,
1922 'oldimage',
1923 array(
1924 'fa_name' => 'oi_name',
1925 'fa_archive_name' => 'oi_archive_name',
1926 'fa_size' => 'oi_size',
1927 'fa_width' => 'oi_width',
1928 'fa_height' => 'oi_height',
1929 'fa_metadata' => 'NULL',
1930 'fa_bits' => 'oi_bits',
1931 'fa_media_type' => 'NULL',
1932 'fa_major_mime' => 'NULL',
1933 'fa_minor_mime' => 'NULL',
1934 'fa_description' => 'oi_description',
1935 'fa_user' => 'oi_user',
1936 'fa_user_text' => 'oi_user_text',
1937 'fa_timestamp' => 'oi_timestamp' ),
1938 array(
1939 'oi_name' => $this->name,
1940 'oi_archive_name' => $archiveName ),
1941 __METHOD__ );
1945 * Do the dirty work of backing up an image row and its file
1946 * (if $wgSaveDeletedFiles is on) and removing the originals.
1948 * Must be run while the file store is locked and a database
1949 * transaction is open to avoid race conditions.
1951 * @return FSTransaction
1953 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1954 global $wgUser, $wgSaveDeletedFiles;
1956 // Dupe the file into the file store
1957 if( file_exists( $path ) ) {
1958 if( $wgSaveDeletedFiles ) {
1959 $group = 'deleted';
1961 $store = FileStore::get( $group );
1962 $key = FileStore::calculateKey( $path, $this->extension );
1963 $transaction = $store->insert( $key, $path,
1964 FileStore::DELETE_ORIGINAL );
1965 } else {
1966 $group = null;
1967 $key = null;
1968 $transaction = FileStore::deleteFile( $path );
1970 } else {
1971 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
1972 $group = null;
1973 $key = null;
1974 $transaction = new FSTransaction(); // empty
1977 if( $transaction === false ) {
1978 // Fail to restore?
1979 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
1980 throw new MWException( "Could not archive and delete file $path" );
1981 return false;
1984 $dbw = wfGetDB( DB_MASTER );
1985 $storageMap = array(
1986 'fa_storage_group' => $dbw->addQuotes( $group ),
1987 'fa_storage_key' => $dbw->addQuotes( $key ),
1989 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1990 'fa_deleted_timestamp' => $dbw->timestamp(),
1991 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
1992 $allFields = array_merge( $storageMap, $fieldMap );
1994 try {
1995 if( $wgSaveDeletedFiles ) {
1996 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1998 $dbw->delete( $table, $where, $fname );
1999 } catch( DBQueryError $e ) {
2000 // Something went horribly wrong!
2001 // Leave the file as it was...
2002 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
2003 $transaction->rollback();
2004 throw $e;
2007 return $transaction;
2011 * Restore all or specified deleted revisions to the given file.
2012 * Permissions and logging are left to the caller.
2014 * May throw database exceptions on error.
2016 * @param $versions set of record ids of deleted items to restore,
2017 * or empty to restore all revisions.
2018 * @return the number of file revisions restored if successful,
2019 * or false on failure
2021 function restore( $versions=array() ) {
2022 if( !FileStore::lock() ) {
2023 wfDebug( __METHOD__." could not acquire filestore lock\n" );
2024 return false;
2027 $transaction = new FSTransaction();
2028 try {
2029 $dbw = wfGetDB( DB_MASTER );
2030 $dbw->begin();
2032 // Re-confirm whether this image presently exists;
2033 // if no we'll need to create an image record for the
2034 // first item we restore.
2035 $exists = $dbw->selectField( 'image', '1',
2036 array( 'img_name' => $this->name ),
2037 __METHOD__ );
2039 // Fetch all or selected archived revisions for the file,
2040 // sorted from the most recent to the oldest.
2041 $conditions = array( 'fa_name' => $this->name );
2042 if( $versions ) {
2043 $conditions['fa_id'] = $versions;
2046 $result = $dbw->select( 'filearchive', '*',
2047 $conditions,
2048 __METHOD__,
2049 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2051 if( $dbw->numRows( $result ) < count( $versions ) ) {
2052 // There's some kind of conflict or confusion;
2053 // we can't restore everything we were asked to.
2054 wfDebug( __METHOD__.": couldn't find requested items\n" );
2055 $dbw->rollback();
2056 FileStore::unlock();
2057 return false;
2060 if( $dbw->numRows( $result ) == 0 ) {
2061 // Nothing to do.
2062 wfDebug( __METHOD__.": nothing to do\n" );
2063 $dbw->rollback();
2064 FileStore::unlock();
2065 return true;
2068 $revisions = 0;
2069 while( $row = $dbw->fetchObject( $result ) ) {
2070 $revisions++;
2071 $store = FileStore::get( $row->fa_storage_group );
2072 if( !$store ) {
2073 wfDebug( __METHOD__.": skipping row with no file.\n" );
2074 continue;
2077 if( $revisions == 1 && !$exists ) {
2078 $destDir = wfImageDir( $row->fa_name );
2079 if ( !is_dir( $destDir ) ) {
2080 wfMkdirParents( $destDir );
2082 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
2084 // We may have to fill in data if this was originally
2085 // an archived file revision.
2086 if( is_null( $row->fa_metadata ) ) {
2087 $tempFile = $store->filePath( $row->fa_storage_key );
2088 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2090 $magic = wfGetMimeMagic();
2091 $mime = $magic->guessMimeType( $tempFile, true );
2092 $media_type = $magic->getMediaType( $tempFile, $mime );
2093 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
2094 } else {
2095 $metadata = $row->fa_metadata;
2096 $major_mime = $row->fa_major_mime;
2097 $minor_mime = $row->fa_minor_mime;
2098 $media_type = $row->fa_media_type;
2101 $table = 'image';
2102 $fields = array(
2103 'img_name' => $row->fa_name,
2104 'img_size' => $row->fa_size,
2105 'img_width' => $row->fa_width,
2106 'img_height' => $row->fa_height,
2107 'img_metadata' => $metadata,
2108 'img_bits' => $row->fa_bits,
2109 'img_media_type' => $media_type,
2110 'img_major_mime' => $major_mime,
2111 'img_minor_mime' => $minor_mime,
2112 'img_description' => $row->fa_description,
2113 'img_user' => $row->fa_user,
2114 'img_user_text' => $row->fa_user_text,
2115 'img_timestamp' => $row->fa_timestamp );
2116 } else {
2117 $archiveName = $row->fa_archive_name;
2118 if( $archiveName == '' ) {
2119 // This was originally a current version; we
2120 // have to devise a new archive name for it.
2121 // Format is <timestamp of archiving>!<name>
2122 $archiveName =
2123 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
2124 '!' . $row->fa_name;
2126 $destDir = wfImageArchiveDir( $row->fa_name );
2127 if ( !is_dir( $destDir ) ) {
2128 wfMkdirParents( $destDir );
2130 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
2132 $table = 'oldimage';
2133 $fields = array(
2134 'oi_name' => $row->fa_name,
2135 'oi_archive_name' => $archiveName,
2136 'oi_size' => $row->fa_size,
2137 'oi_width' => $row->fa_width,
2138 'oi_height' => $row->fa_height,
2139 'oi_bits' => $row->fa_bits,
2140 'oi_description' => $row->fa_description,
2141 'oi_user' => $row->fa_user,
2142 'oi_user_text' => $row->fa_user_text,
2143 'oi_timestamp' => $row->fa_timestamp );
2146 $dbw->insert( $table, $fields, __METHOD__ );
2147 /// @fixme this delete is not totally safe, potentially
2148 $dbw->delete( 'filearchive',
2149 array( 'fa_id' => $row->fa_id ),
2150 __METHOD__ );
2152 // Check if any other stored revisions use this file;
2153 // if so, we shouldn't remove the file from the deletion
2154 // archives so they will still work.
2155 $useCount = $dbw->selectField( 'filearchive',
2156 'COUNT(*)',
2157 array(
2158 'fa_storage_group' => $row->fa_storage_group,
2159 'fa_storage_key' => $row->fa_storage_key ),
2160 __METHOD__ );
2161 if( $useCount == 0 ) {
2162 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2163 $flags = FileStore::DELETE_ORIGINAL;
2164 } else {
2165 $flags = 0;
2168 $transaction->add( $store->export( $row->fa_storage_key,
2169 $destPath, $flags ) );
2172 $dbw->immediateCommit();
2173 } catch( MWException $e ) {
2174 wfDebug( __METHOD__." caught error, aborting\n" );
2175 $transaction->rollback();
2176 throw $e;
2179 $transaction->commit();
2180 FileStore::unlock();
2182 if( $revisions > 0 ) {
2183 if( !$exists ) {
2184 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
2186 // Update site_stats
2187 $site_stats = $dbw->tableName( 'site_stats' );
2188 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2190 $this->purgeEverything();
2191 } else {
2192 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
2193 $this->purgeDescription();
2197 return $revisions;
2200 } //class
2203 * Wrapper class for thumbnail images
2204 * @package MediaWiki
2206 class ThumbnailImage {
2208 * @param string $path Filesystem path to the thumb
2209 * @param string $url URL path to the thumb
2210 * @private
2212 function ThumbnailImage( $url, $width, $height, $path = false ) {
2213 $this->url = $url;
2214 $this->width = round( $width );
2215 $this->height = round( $height );
2216 # These should be integers when they get here.
2217 # If not, there's a bug somewhere. But let's at
2218 # least produce valid HTML code regardless.
2219 $this->path = $path;
2223 * @return string The thumbnail URL
2225 function getUrl() {
2226 return $this->url;
2230 * Return HTML <img ... /> tag for the thumbnail, will include
2231 * width and height attributes and a blank alt text (as required).
2233 * You can set or override additional attributes by passing an
2234 * associative array of name => data pairs. The data will be escaped
2235 * for HTML output, so should be in plaintext.
2237 * @param array $attribs
2238 * @return string
2239 * @public
2241 function toHtml( $attribs = array() ) {
2242 $attribs['src'] = $this->url;
2243 $attribs['width'] = $this->width;
2244 $attribs['height'] = $this->height;
2245 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2247 $html = '<img ';
2248 foreach( $attribs as $name => $data ) {
2249 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2251 $html .= '/>';
2252 return $html;